import storejs from 'storejs'
export class FnKeyDown {
curKeyCode: string;
monitorKeyCode: number;
isMonitorKeyCode: boolean;
isFocus: boolean;
keydownEven: any;
keyupEven: any;
focusEven: any;
blurEven: any;
constructor ({ isMonitorKeyCode = true }: any) {
this.curKeyCode = ''
this.isMonitorKeyCode = isMonitorKeyCode
this.isFocus = false
this.monitorKeyCode = 32
this.keydownEven = null
this.keyupEven = null
this.focusEven = null
this.blurEven = null
this.init()
}
init () {
this.removeEvent()
this.monitorKeyCode = this.getKeyCode().keyCode
this.keydownEven = (event: any) => {
if (this.isFocus && this.curKeyCode === '') return
if (this.curKeyCode === event.keyCode) {
return
}
if (this.isMonitorKeyCode) {
if (event.keyCode !== this.monitorKeyCode) {
return
}
}
this.curKeyCode = event.keyCode
this.monitorCallback(1, event)
}
this.keyupEven = (event: any) => {
if (this.isMonitorKeyCode) {
if (event.keyCode !== this.monitorKeyCode) {
return
}
}
if (this.isFocus) return
this.curKeyCode = ''
this.monitorCallback(0, event)
}
document.addEventListener('keydown', this.keydownEven, false)
document.addEventListener('keyup', this.keyupEven, false)
if (this.isMonitorKeyCode) {
this.focusEven = (event: any) => {
if (this.isFocus) return
this.isFocus = true
}
this.blurEven = (event: any) => {
if (this.isFocus === false) return
this.isFocus = false
}
document.addEventListener('focus', this.focusEven, true)
document.addEventListener('blur', this.blurEven, true)
}
}
monitorCallback (type: number, event: any) {
}
setKeyCode (res: { key: string; code: string; keyCode: number}) {
storejs.set('FnPttKeyInfo', res)
}
getKeyCode () {
const fnPttKeyInfo = storejs.get('FnPttKeyInfo') || { key: ' ', code: 'Space', keyCode: 32 }
return fnPttKeyInfo
}
removeEvent () {
this.keydownEven && document.removeEventListener('keydown', this.keydownEven)
this.keyupEven && document.removeEventListener('keyup', this.keyupEven)
this.focusEven && document.removeEventListener('focus', this.focusEven)
this.blurEven && document.removeEventListener('blur', this.blurEven)
}
}