]> BookStack Code Mirror - bookstack/blob - resources/js/code/views.js
Got md shortcuts working, marked actions for update
[bookstack] / resources / js / code / views.js
1 import {getLanguageExtension} from "./languages"
2 import {Compartment} from "@codemirror/state"
3 import {EditorView} from "@codemirror/view"
4 import {oneDark} from "@codemirror/theme-one-dark"
5
6 const viewLangCompartments = new WeakMap();
7
8 /**
9  * Create a new editor view.
10  *
11  * @param {{parent: Element, doc: String, extensions: Array}} config
12  * @returns {EditorView}
13  */
14 export function createView(config) {
15     const langCompartment = new Compartment();
16     config.extensions.push(langCompartment.of([]));
17     config.extensions.push(getTheme(config.parent));
18
19     const ev = new EditorView(config);
20
21     viewLangCompartments.set(ev, langCompartment);
22
23     return ev;
24 }
25
26 /**
27  * Get the theme extension to use for editor view instance.
28  * @returns {Extension}
29  */
30 function getTheme(viewParentEl) {
31     const darkMode = document.documentElement.classList.contains('dark-mode');
32
33     const eventData = {
34         darkMode: darkMode,
35         theme: null,
36     };
37
38     window.$events.emitPublic(viewParentEl, 'library-cm6::configure-theme', eventData);
39
40     return eventData.theme || (darkMode ? oneDark : []);
41 }
42
43 /**
44  * Set the language mode of an EditorView.
45  *
46  * @param {EditorView} ev
47  * @param {string} modeSuggestion
48  * @param {string} content
49  */
50 export function updateViewLanguage(ev, modeSuggestion, content) {
51     const compartment = viewLangCompartments.get(ev);
52     const language = getLanguageExtension(modeSuggestion, content);
53
54     ev.dispatch({
55         effects: compartment.reconfigure(language ? language : [])
56     })
57 }