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