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