2024-03-11 17:02:15 +02:00
|
|
|
import CommandService, { CommandContext, CommandDeclaration } from '@joplin/lib/services/CommandService';
|
2024-03-20 12:58:42 +02:00
|
|
|
import { EditorControl } from '@joplin/editor/types';
|
2024-03-11 17:02:15 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
import commandDeclarations, { enabledCondition } from '../commandDeclarations';
|
|
|
|
import Logger from '@joplin/utils/Logger';
|
|
|
|
|
|
|
|
const logger = Logger.create('useEditorCommandHandler');
|
|
|
|
|
|
|
|
const commandRuntime = (declaration: CommandDeclaration, editor: EditorControl) => {
|
|
|
|
return {
|
2024-04-05 13:16:49 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
|
2024-03-11 17:02:15 +02:00
|
|
|
execute: async (_context: CommandContext, ...args: any[]) => {
|
|
|
|
// Many editor CodeMirror commands are missing the editor. prefix.
|
|
|
|
let commandName = declaration.name.replace(/^editor\./, '');
|
|
|
|
|
2024-03-20 12:58:42 +02:00
|
|
|
if (commandName === 'execCommand') {
|
|
|
|
commandName = args[0]?.name;
|
|
|
|
args = args[0]?.args ?? [];
|
|
|
|
|
|
|
|
if (!commandName) {
|
|
|
|
throw new Error('editor.execCommand is missing the name of the command to execute');
|
|
|
|
}
|
2024-03-11 17:02:15 +02:00
|
|
|
}
|
|
|
|
|
2024-03-14 21:04:32 +02:00
|
|
|
if (!(await editor.supportsCommand(commandName))) {
|
2024-03-11 17:02:15 +02:00
|
|
|
logger.warn('Command not supported by editor: ', commandName);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
return await editor.execCommand(commandName, ...args);
|
|
|
|
},
|
|
|
|
enabledCondition: enabledCondition(declaration.name),
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const useEditorCommandHandler = (editorControl: EditorControl) => {
|
|
|
|
useEffect(() => {
|
|
|
|
const commandService = CommandService.instance();
|
|
|
|
for (const declaration of commandDeclarations) {
|
|
|
|
commandService.registerRuntime(declaration.name, commandRuntime(declaration, editorControl));
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
for (const declaration of commandDeclarations) {
|
|
|
|
commandService.unregisterRuntime(declaration.name);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useEditorCommandHandler;
|