]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/shortcuts.ts
MD Editor: Updated actions to use input interface
[bookstack] / resources / js / markdown / shortcuts.ts
1 import {MarkdownEditor} from "./index.mjs";
2 import {KeyBinding} from "@codemirror/view";
3
4 /**
5  * Provide shortcuts for the editor instance.
6  */
7 function provide(editor: MarkdownEditor): Record<string, () => void> {
8     const shortcuts: Record<string, () => void> = {};
9
10     // Insert Image shortcut
11     shortcuts['Shift-Mod-i'] = () => editor.actions.insertImage();
12
13     // Save draft
14     shortcuts['Mod-s'] = () => window.$events.emit('editor-save-draft');
15
16     // Save page
17     shortcuts['Mod-Enter'] = () => window.$events.emit('editor-save-page');
18
19     // Show link selector
20     shortcuts['Shift-Mod-k'] = () => editor.actions.showLinkSelector();
21
22     // Insert Link
23     shortcuts['Mod-k'] = () => editor.actions.insertLink();
24
25     // FormatShortcuts
26     shortcuts['Mod-1'] = () => editor.actions.replaceLineStart('##');
27     shortcuts['Mod-2'] = () => editor.actions.replaceLineStart('###');
28     shortcuts['Mod-3'] = () => editor.actions.replaceLineStart('####');
29     shortcuts['Mod-4'] = () => editor.actions.replaceLineStart('#####');
30     shortcuts['Mod-5'] = () => editor.actions.replaceLineStart('');
31     shortcuts['Mod-d'] = () => editor.actions.replaceLineStart('');
32     shortcuts['Mod-6'] = () => editor.actions.replaceLineStart('>');
33     shortcuts['Mod-q'] = () => editor.actions.replaceLineStart('>');
34     shortcuts['Mod-7'] = () => editor.actions.wrapSelection('\n```\n', '\n```');
35     shortcuts['Mod-8'] = () => editor.actions.wrapSelection('`', '`');
36     shortcuts['Shift-Mod-e'] = () => editor.actions.wrapSelection('`', '`');
37     shortcuts['Mod-9'] = () => editor.actions.cycleCalloutTypeAtSelection();
38     shortcuts['Mod-p'] = () => editor.actions.replaceLineStart('-');
39     shortcuts['Mod-o'] = () => editor.actions.replaceLineStartForOrderedList();
40
41     return shortcuts;
42 }
43
44 /**
45  * Get the editor shortcuts in CodeMirror keybinding format.
46  */
47 export function provideKeyBindings(editor: MarkdownEditor): KeyBinding[] {
48     const shortcuts = provide(editor);
49     const keyBindings = [];
50
51     const wrapAction = (action: ()=>void) => () => {
52         action();
53         return true;
54     };
55
56     for (const [shortcut, action] of Object.entries(shortcuts)) {
57         keyBindings.push({key: shortcut, run: wrapAction(action), preventDefault: true});
58     }
59
60     return keyBindings;
61 }