]> BookStack Code Mirror - bookstack/blob - resources/js/code.mjs
Merge pull request #3512 from BookStackApp/code_manager_updates
[bookstack] / resources / js / code.mjs
1 import CodeMirror from "codemirror";
2 import Clipboard from "clipboard/dist/clipboard.min";
3
4 // Modes
5 import 'codemirror/mode/css/css';
6 import 'codemirror/mode/clike/clike';
7 import 'codemirror/mode/diff/diff';
8 import 'codemirror/mode/fortran/fortran';
9 import 'codemirror/mode/go/go';
10 import 'codemirror/mode/haskell/haskell';
11 import 'codemirror/mode/htmlmixed/htmlmixed';
12 import 'codemirror/mode/javascript/javascript';
13 import 'codemirror/mode/julia/julia';
14 import 'codemirror/mode/lua/lua';
15 import 'codemirror/mode/markdown/markdown';
16 import 'codemirror/mode/mllike/mllike';
17 import 'codemirror/mode/nginx/nginx';
18 import 'codemirror/mode/perl/perl';
19 import 'codemirror/mode/pascal/pascal';
20 import 'codemirror/mode/php/php';
21 import 'codemirror/mode/powershell/powershell';
22 import 'codemirror/mode/properties/properties';
23 import 'codemirror/mode/python/python';
24 import 'codemirror/mode/ruby/ruby';
25 import 'codemirror/mode/rust/rust';
26 import 'codemirror/mode/shell/shell';
27 import 'codemirror/mode/sql/sql';
28 import 'codemirror/mode/stex/stex';
29 import 'codemirror/mode/toml/toml';
30 import 'codemirror/mode/vb/vb';
31 import 'codemirror/mode/vbscript/vbscript';
32 import 'codemirror/mode/xml/xml';
33 import 'codemirror/mode/yaml/yaml';
34
35 // Addons
36 import 'codemirror/addon/scroll/scrollpastend';
37
38 // Mapping of possible languages or formats from user input to their codemirror modes.
39 // Value can be a mode string or a function that will receive the code content & return the mode string.
40 // The function option is used in the event the exact mode could be dynamic depending on the code.
41 const modeMap = {
42     css: 'css',
43     c: 'text/x-csrc',
44     java: 'text/x-java',
45     scala: 'text/x-scala',
46     kotlin: 'text/x-kotlin',
47     'c++': 'text/x-c++src',
48     'c#': 'text/x-csharp',
49     csharp: 'text/x-csharp',
50     diff: 'diff',
51     for: 'fortran',
52     fortran: 'fortran',
53     'f#': 'text/x-fsharp',
54     fsharp: 'text/x-fsharp',
55     go: 'go',
56     haskell: 'haskell',
57     hs: 'haskell',
58     html: 'htmlmixed',
59     ini: 'properties',
60     javascript: 'text/javascript',
61     json: 'application/json',
62     js: 'text/javascript',
63     jl: 'text/x-julia',
64     julia: 'text/x-julia',
65     latex: 'text/x-stex',
66     lua: 'lua',
67     md: 'markdown',
68     mdown: 'markdown',
69     markdown: 'markdown',
70     ml: 'mllike',
71     nginx: 'nginx',
72     perl: 'perl',
73     pl: 'perl',
74     powershell: 'powershell',
75     properties: 'properties',
76     ocaml: 'text/x-ocaml',
77     pascal: 'text/x-pascal',
78     pas: 'text/x-pascal',
79     php: (content) => {
80         return content.includes('<?php') ? 'php' : 'text/x-php';
81     },
82     py: 'python',
83     python: 'python',
84     ruby: 'ruby',
85     rust: 'rust',
86     rb: 'ruby',
87     rs: 'rust',
88     shell: 'shell',
89     sh: 'shell',
90     stext: 'text/x-stex',
91     bash: 'shell',
92     toml: 'toml',
93     ts: 'text/typescript',
94     typescript: 'text/typescript',
95     sql: 'text/x-sql',
96     vbs: 'vbscript',
97     vbscript: 'vbscript',
98     'vb.net': 'text/x-vb',
99     vbnet: 'text/x-vb',
100     xml: 'xml',
101     yaml: 'yaml',
102     yml: 'yaml',
103 };
104
105 /**
106  * Highlight pre elements on a page
107  */
108 export function highlight() {
109     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
110     for (const codeBlock of codeBlocks) {
111         highlightElem(codeBlock);
112     }
113 }
114
115 /**
116  * Highlight all code blocks within the given parent element
117  * @param {HTMLElement} parent
118  */
119 export function highlightWithin(parent) {
120     const codeBlocks = parent.querySelectorAll('pre');
121     for (const codeBlock of codeBlocks) {
122         highlightElem(codeBlock);
123     }
124 }
125
126 /**
127  * Add code highlighting to a single element.
128  * @param {HTMLElement} elem
129  */
130 function highlightElem(elem) {
131     const innerCodeElem = elem.querySelector('code[class^=language-]');
132     elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
133     const content = elem.textContent.trimEnd();
134
135     let mode = '';
136     if (innerCodeElem !== null) {
137         const langName = innerCodeElem.className.replace('language-', '');
138         mode = getMode(langName, content);
139     }
140
141     const cm = CodeMirror(function(elt) {
142         elem.parentNode.replaceChild(elt, elem);
143     }, {
144         value: content,
145         mode:  mode,
146         lineNumbers: true,
147         lineWrapping: false,
148         theme: getTheme(),
149         readOnly: true
150     });
151
152     addCopyIcon(cm);
153 }
154
155 /**
156  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
157  * @param cmInstance
158  */
159 function addCopyIcon(cmInstance) {
160     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>`;
161     const copyButton = document.createElement('div');
162     copyButton.classList.add('CodeMirror-copy');
163     copyButton.innerHTML = copyIcon;
164     cmInstance.display.wrapper.appendChild(copyButton);
165
166     const clipboard = new Clipboard(copyButton, {
167         text: function(trigger) {
168             return cmInstance.getValue()
169         }
170     });
171
172     clipboard.on('success', event => {
173         copyButton.classList.add('success');
174         setTimeout(() => {
175             copyButton.classList.remove('success');
176         }, 240);
177     });
178 }
179
180 /**
181  * Search for a codemirror code based off a user suggestion
182  * @param {String} suggestion
183  * @param {String} content
184  * @returns {string}
185  */
186 function getMode(suggestion, content) {
187     suggestion = suggestion.trim().replace(/^\./g, '').toLowerCase();
188
189     const modeMapType = typeof modeMap[suggestion];
190
191     if (modeMapType === 'undefined') {
192         return '';
193     }
194
195     if (modeMapType === 'function') {
196         return modeMap[suggestion](content);
197     }
198
199     return modeMap[suggestion];
200 }
201
202 /**
203  * Ge the theme to use for CodeMirror instances.
204  * @returns {*|string}
205  */
206 function getTheme() {
207     const darkMode = document.documentElement.classList.contains('dark-mode');
208     return window.codeTheme || (darkMode ? 'darcula' : 'default');
209 }
210
211 /**
212  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
213  *  Manages a textarea element to hold code content.
214  * @param {HTMLElement} cmContainer
215  * @param {String} content
216  * @param {String} language
217  * @returns {{wrap: Element, editor: *}}
218  */
219 export function wysiwygView(cmContainer, content, language) {
220     return CodeMirror(cmContainer, {
221         value: content,
222         mode: getMode(language, content),
223         lineNumbers: true,
224         lineWrapping: false,
225         theme: getTheme(),
226         readOnly: true
227     });
228 }
229
230
231 /**
232  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
233  * @param {HTMLElement} elem
234  * @param {String} modeSuggestion
235  * @returns {*}
236  */
237 export function popupEditor(elem, modeSuggestion) {
238     const content = elem.textContent;
239
240     return CodeMirror(function(elt) {
241         elem.parentNode.insertBefore(elt, elem);
242         elem.style.display = 'none';
243     }, {
244         value: content,
245         mode:  getMode(modeSuggestion, content),
246         lineNumbers: true,
247         lineWrapping: false,
248         theme: getTheme()
249     });
250 }
251
252 /**
253  * Create an inline editor to replace the given textarea.
254  * @param {HTMLTextAreaElement} textArea
255  * @param {String} mode
256  * @returns {CodeMirror3}
257  */
258 export function inlineEditor(textArea, mode) {
259     return CodeMirror.fromTextArea(textArea, {
260         mode: getMode(mode, textArea.value),
261         lineNumbers: true,
262         lineWrapping: false,
263         theme: getTheme(),
264     });
265 }
266
267 /**
268  * Set the mode of a codemirror instance.
269  * @param cmInstance
270  * @param modeSuggestion
271  */
272 export function setMode(cmInstance, modeSuggestion, content) {
273       cmInstance.setOption('mode', getMode(modeSuggestion, content));
274 }
275
276 /**
277  * Set the content of a cm instance.
278  * @param cmInstance
279  * @param codeContent
280  */
281 export function setContent(cmInstance, codeContent) {
282     cmInstance.setValue(codeContent);
283     setTimeout(() => {
284         updateLayout(cmInstance);
285     }, 10);
286 }
287
288 /**
289  * Update the layout (codemirror refresh) of a cm instance.
290  * @param cmInstance
291  */
292 export function updateLayout(cmInstance) {
293     cmInstance.refresh();
294 }
295
296 /**
297  * Get a CodeMirror instance to use for the markdown editor.
298  * @param {HTMLElement} elem
299  * @returns {*}
300  */
301 export function markdownEditor(elem) {
302     const content = elem.textContent;
303     const config = {
304         value: content,
305         mode: "markdown",
306         lineNumbers: true,
307         lineWrapping: true,
308         theme: getTheme(),
309         scrollPastEnd: true,
310     };
311
312     window.$events.emitPublic(elem, 'editor-markdown-cm::pre-init', {config});
313
314     return CodeMirror(function (elt) {
315         elem.parentNode.insertBefore(elt, elem);
316         elem.style.display = 'none';
317     }, config);
318 }
319
320 /**
321  * Get the 'meta' key dependent on the user's system.
322  * @returns {string}
323  */
324 export function getMetaKey() {
325     let mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
326     return mac ? "Cmd" : "Ctrl";
327 }