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