delta-component
Version:
embeddable react component
77 lines (60 loc) • 1.82 kB
JavaScript
const log = require('../../../../common/logger').log;
class KeyToBindRequiredErr extends Error {
}
class AlreadyBoundErr extends Error {
}
const alreadyBoundKeys = {};
let help = [];
function man() {
log.info('Help: \n' + help.map(item => `ctrl + alt + ${item.key} => ${item.desc}`).join('\n'));
}
man.description = 'Помощь';
let _helpMounted = false;
function _bind(window, keyToBind, func) {
window.addEventListener('keypress', (event) => {
if(event.ctrlKey && event.altKey) {
if (event.code === 'Key' + keyToBind) {
log.info(`Вы тестируете и вызвали ${func.name} (${func.description})`);
func();
}
}
});
help.push({
key: keyToBind,
desc: func.description,
});
}
function bindDebugFunctions(window, ...functions) {
if(!_helpMounted) {
_bind(window, 'H', man);
_helpMounted = true;
}
for(const func of functions) {
if(func.keyToBind) {
const keyCode = func.keyToBind;
if(keyCode in alreadyBoundKeys) {
log.info(`"${keyCode}" is already given to ${alreadyBoundKeys[keyCode]}`);
throw new AlreadyBoundErr()
} else {
_bind(window, keyCode, func)
alreadyBoundKeys[keyCode] = func;
}
} else {
log.info(`Set keyToBind to ${func.name}`);
throw new KeyToBindRequiredErr();
}
}
}
function bindFromObject(window, obj) {
let funcs = [];
for(const name of Object.keys(obj)) {
funcs.push(obj[name]);
}
bindDebugFunctions(window, ...funcs);
}
module.exports = {
bindDebugFunctions,
bindFromObject,
KeyToBindRequiredErr, AlreadyBoundErr,
};
;