comty/packages/app/src/extensions/shortcuts.extension.js
2022-05-06 19:00:29 +02:00

70 lines
1.7 KiB
JavaScript

import { Extension } from "evite"
export default class ShortcutsExtension extends Extension {
constructor(app, main) {
super(app, main)
this.shortcuts = {}
document.addEventListener("keydown", (event) => {
// FIXME: event.key sometimes is not defined
const key = event.key.toLowerCase()
const shortcut = this.shortcuts[key]
if (shortcut) {
if (typeof shortcut.ctrl === "boolean" && event.ctrlKey !== shortcut.ctrl) {
return
}
if (typeof shortcut.shift === "boolean" && event.shiftKey !== shortcut.shift) {
return
}
if (typeof shortcut.alt === "boolean" && event.altKey !== shortcut.alt) {
return
}
if (typeof shortcut.meta === "boolean" && event.metaKey !== shortcut.meta) {
return
}
if (shortcut.preventDefault) {
event.preventDefault()
}
if (typeof shortcut.fn === "function") {
shortcut.fn()
}
}
})
}
register = (keybind = {}, fn) => {
if (typeof keybind === "string") {
keybind = {
key: keybind,
}
}
this.shortcuts[keybind.key] = {
...keybind,
fn,
}
}
remove = (array) => {
if (typeof array === "string") {
array = [array]
}
array.forEach(key => {
delete this.shortcuts[key]
})
}
window = {
ShortcutsController: this
}
}