]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
Updated cm6 theme handling to allow extension via API
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from "@codemirror/view";
2 import {copyTextToClipboard} from "../services/clipboard.js"
3
4 // Modes
5 import {viewer, editor} from "./setups.js";
6 import {createView, updateViewLanguage} from "./views.js";
7
8 /**
9  * Highlight pre elements on a page
10  */
11 export function highlight() {
12     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
13     for (const codeBlock of codeBlocks) {
14         highlightElem(codeBlock);
15     }
16 }
17
18 /**
19  * Highlight all code blocks within the given parent element
20  * @param {HTMLElement} parent
21  */
22 export function highlightWithin(parent) {
23     const codeBlocks = parent.querySelectorAll('pre');
24     for (const codeBlock of codeBlocks) {
25         highlightElem(codeBlock);
26     }
27 }
28
29 /**
30  * Add code highlighting to a single element.
31  * @param {HTMLElement} elem
32  */
33 function highlightElem(elem) {
34     const innerCodeElem = elem.querySelector('code[class^=language-]');
35     elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
36     const content = elem.textContent.trimEnd();
37
38     let langName = '';
39     if (innerCodeElem !== null) {
40         langName = innerCodeElem.className.replace('language-', '');
41     }
42
43     const wrapper = document.createElement('div');
44     elem.parentNode.insertBefore(wrapper, elem);
45
46     const ev = createView({
47         parent: wrapper,
48         doc: content,
49         extensions: viewer(),
50     });
51     setMode(ev, langName, content);
52     window.cm = ev;
53
54     elem.remove();
55
56     addCopyIcon(ev);
57 }
58
59 /**
60  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
61  * @param {EditorView} editorView
62  */
63 function addCopyIcon(editorView) {
64     const copyIcon = `<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>`;
65     const copyButton = document.createElement('button');
66     copyButton.setAttribute('type', 'button')
67     copyButton.classList.add('cm-copy-button');
68     copyButton.innerHTML = copyIcon;
69     editorView.dom.appendChild(copyButton);
70
71     copyButton.addEventListener('click', event => {
72         copyTextToClipboard(editorView.state.doc.toString());
73         copyButton.classList.add('success');
74         setTimeout(() => {
75             copyButton.classList.remove('success');
76         }, 240);
77     });
78 }
79
80 /**
81  * Ge the theme to use for CodeMirror instances.
82  * @returns {*|string}
83  */
84 function getTheme() {
85     // TODO - Remove
86     const darkMode = document.documentElement.classList.contains('dark-mode');
87     return window.codeTheme || (darkMode ? 'darcula' : 'default');
88 }
89
90 /**
91  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
92  *  Manages a textarea element to hold code content.
93  * @param {HTMLElement} cmContainer
94  * @param {String} content
95  * @param {String} language
96  * @returns {{wrap: Element, editor: *}}
97  */
98 export function wysiwygView(cmContainer, content, language) {
99     return CodeMirror(cmContainer, {
100         value: content,
101         mode: getMode(language, content),
102         lineNumbers: true,
103         lineWrapping: false,
104         theme: getTheme(),
105         readOnly: true
106     });
107 }
108
109
110 /**
111  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
112  * @param {HTMLElement} elem
113  * @param {String} modeSuggestion
114  * @returns {*}
115  */
116 export function popupEditor(elem, modeSuggestion) {
117     const content = elem.textContent;
118
119     return CodeMirror(function(elt) {
120         elem.parentNode.insertBefore(elt, elem);
121         elem.style.display = 'none';
122     }, {
123         value: content,
124         mode:  getMode(modeSuggestion, content),
125         lineNumbers: true,
126         lineWrapping: false,
127         theme: getTheme()
128     });
129 }
130
131 /**
132  * Create an inline editor to replace the given textarea.
133  * @param {HTMLTextAreaElement} textArea
134  * @param {String} mode
135  * @returns {CodeMirror3}
136  */
137 export function inlineEditor(textArea, mode) {
138     return CodeMirror.fromTextArea(textArea, {
139         mode: getMode(mode, textArea.value),
140         lineNumbers: true,
141         lineWrapping: false,
142         theme: getTheme(),
143     });
144 }
145
146 /**
147  * Set the language mode of a codemirror EditorView.
148  *
149  * @param {EditorView} ev
150  * @param {string} modeSuggestion
151  * @param {string} content
152  */
153 export function setMode(ev, modeSuggestion, content) {
154     updateViewLanguage(ev, modeSuggestion, content);
155 }
156
157 /**
158  * Set the content of a cm instance.
159  * @param cmInstance
160  * @param codeContent
161  */
162 export function setContent(cmInstance, codeContent) {
163     cmInstance.setValue(codeContent);
164     setTimeout(() => {
165         updateLayout(cmInstance);
166     }, 10);
167 }
168
169 /**
170  * Update the layout (codemirror refresh) of a cm instance.
171  * @param cmInstance
172  */
173 export function updateLayout(cmInstance) {
174     cmInstance.refresh();
175 }
176
177 /**
178  * Get a CodeMirror instance to use for the markdown editor.
179  * @param {HTMLElement} elem
180  * @param {function} onChange
181  * @param {object} domEventHandlers
182  * @param {Array} keyBindings
183  * @returns {*}
184  */
185 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
186     const content = elem.textContent;
187     const config = {
188         parent: elem.parentNode,
189         doc: content,
190         extensions: [
191             ...editor('markdown'),
192             EditorView.updateListener.of((v) => {
193                 onChange(v);
194             }),
195             EditorView.domEventHandlers(domEventHandlers),
196             keymap.of(keyBindings),
197         ],
198     };
199
200     // Emit a pre-event public event to allow tweaking of the configure before view creation.
201     window.$events.emitPublic(elem, 'editor-markdown-cm::pre-init', {cmEditorViewConfig: config});
202
203     // Create editor view, hide original input
204     const ev = createView(config);
205     setMode(ev, 'markdown', '');
206     elem.style.display = 'none';
207
208     return ev;
209 }