-
Notifications
You must be signed in to change notification settings - Fork 4
/
KeyCommand.js
43 lines (39 loc) · 1.28 KB
/
KeyCommand.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { getRandomId } from 'source/common/math/random'
import { isObjectContain } from 'source/common/check'
// TODO: for single key, not support key sequence
const createKeyCommandHub = ({
eventSource = window.document,
isSkipPreventDefault = false // normally preventDefault won't hurt
}) => {
const keyCommandMap = new Map()
const keyCommandListener = (event) => keyCommandMap.forEach((keyCommand) => {
const { target, checkMap, callback } = keyCommand
if (target && !target.contains(event.target)) return
if (!isObjectContain(event, checkMap)) return
!isSkipPreventDefault && event.preventDefault()
callback(event, keyCommand)
})
let isActive = false
const getIsActive = () => isActive
const start = () => {
eventSource.addEventListener('keydown', keyCommandListener)
isActive = true
}
const stop = () => {
eventSource.removeEventListener('keydown', keyCommandListener)
isActive = false
}
const addKeyCommand = ({ id = getRandomId(), target, checkMap, callback }) => {
keyCommandMap.set(id, { id, target, checkMap, callback })
return id
}
const deleteKeyCommand = ({ id }) => keyCommandMap.delete(id)
return {
getIsActive,
start,
stop,
addKeyCommand,
deleteKeyCommand
}
}
export { createKeyCommandHub }