V
V
veryoriginalnickname2021-12-25 11:35:49
JavaScript
veryoriginalnickname, 2021-12-25 11:35:49

Why doesn't keyup work on some shortcuts?

I am writing a thing that creates hotkeys, and the problem is that the keyup event does not fire on shortcuts like Alt + F.
Alt + F causes a Chrome pop-up menu, and neither focusout nor keyup react to it in any way. And it turns out that AltLeft and KeyF keys continue to lie in keysPressed, even if they have already been released. How can this be fixed?
The code:

type action = {
    shortcut: string[]
    callback: () => void
}

export default class Shortcutter {

    private keysPressedPretty: string = ''
    private keysPressed: { [key: string]: boolean } = {}
    private actions: { [shortcut: string]: () => void } = {}
    private _keyDown = this.onKeyDown.bind(this)
    private _keyUp = this.onKeyUp.bind(this)
    private _focusOut = this.onFocusOut.bind(this)

    constructor() {
        this.manageEvents(true)
    }

    public addAction(action: action) {
        const short = action.shortcut.join("+")
        this.actions[short] = action.callback
    }

    public destroy() {
        this.manageEvents(false)
    }

    private manageEvents(add: boolean) {
        const action = add ? 'addEventListener' : 'removeEventListener'
        // @ts-ignore
        document[action]('keyup', this._keyUp)
        // @ts-ignore
        document[action]('keydown', this._keyDown)
        document[action]('focusout', this._focusOut)
    }

    private onKeyDown(evt: KeyboardEvent) {
        this.keysPressed[evt.code] = true
        this.setKeysPressedPretty()
        if (this.actions[this.keysPressedPretty]) {
            evt.preventDefault()
            this.actions[this.keysPressedPretty]()
        }
    }

    private onKeyUp(evt: KeyboardEvent) {
        console.log('key up: ' + evt.code)
        delete this.keysPressed[evt.code]
        this.setKeysPressedPretty()
    }

    private setKeysPressedPretty() {
        const tempPressed: string[] = []
        for (const pressed in this.keysPressed) {
            tempPressed.push(pressed)
        }
        this.keysPressedPretty = tempPressed.join("+")
        console.log(this.keysPressedPretty)
    }

    private onFocusOut() {
        console.log('focus out')
        this.keysPressed = {}
        this.keysPressedPretty = ''
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Georgy Eremeev, 2021-12-25
@veryoriginalnickname

Try pointerout instead of focusout .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question