mirror of
https://github.com/zadam/trilium.git
synced 2024-09-30 12:35:59 +08:00
73 lines
1.6 KiB
JavaScript
73 lines
1.6 KiB
JavaScript
|
import server from "./server.js";
|
||
|
import utils from "./utils.js";
|
||
|
|
||
|
class KeyboardAction {
|
||
|
constructor(params) {
|
||
|
/** @property {string} */
|
||
|
this.actionName = params.actionName;
|
||
|
/** @property {string[]} */
|
||
|
this.defaultShortcuts = params.defaultShortcuts;
|
||
|
/** @property {string[]} */
|
||
|
this.effectiveShortcuts = params.effectiveShortcuts;
|
||
|
/** @property {string} */
|
||
|
this.description = params.description;
|
||
|
}
|
||
|
|
||
|
addShortcut(shortcut) {
|
||
|
this.effectiveShortcuts.push(shortcut);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @param {string|string[]} shortcuts
|
||
|
*/
|
||
|
replaceShortcuts(shortcuts) {
|
||
|
this.effectiveShortcuts = Array.isArray(shortcuts) ? shortcuts : [shortcuts];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const keyboardActionRepo = {};
|
||
|
|
||
|
const keyboardActionsLoaded = server.get('keyboard-actions').then(actions => {
|
||
|
for (const action of actions) {
|
||
|
keyboardActionRepo[action.actionName] = new KeyboardAction(action);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
function setActionHandler(actionName, handler) {
|
||
|
keyboardActionsLoaded.then(() => {
|
||
|
const action = keyboardActionRepo[actionName];
|
||
|
|
||
|
if (!action) {
|
||
|
throw new Error(`Cannot find keyboard action '${actionName}'`);
|
||
|
}
|
||
|
|
||
|
action.handler = handler;
|
||
|
|
||
|
for (const shortcut of action.effectiveShortcuts) {
|
||
|
if (shortcut) {
|
||
|
utils.bindGlobalShortcut(shortcut, handler);
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
async function triggerAction(actionName) {
|
||
|
await keyboardActionsLoaded;
|
||
|
|
||
|
const action = keyboardActionRepo[actionName];
|
||
|
|
||
|
if (!action) {
|
||
|
throw new Error(`Cannot find action ${actionName}`);
|
||
|
}
|
||
|
|
||
|
if (!action.handler) {
|
||
|
throw new Error(`Action ${actionName} has no handler`);
|
||
|
}
|
||
|
|
||
|
await action.handler();
|
||
|
}
|
||
|
|
||
|
export default {
|
||
|
setActionHandler,
|
||
|
triggerAction
|
||
|
};
|