]> BookStack Code Mirror - bookstack/blob - resources/js/services/code.js
Update code.js
[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     vbscript: 'vbscript',
89     xml: 'xml',
90     yaml: 'yaml',
91     yml: 'yaml',
92 };
93
94 /**
95  * Highlight pre elements on a page
96  */
97 function highlight() {
98     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
99     for (const codeBlock of codeBlocks) {
100         highlightElem(codeBlock);
101     }
102 }
103
104 /**
105  * Highlight all code blocks within the given parent element
106  * @param {HTMLElement} parent
107  */
108 function highlightWithin(parent) {
109     const codeBlocks = parent.querySelectorAll('pre');
110     for (const codeBlock of codeBlocks) {
111         highlightElem(codeBlock);
112     }
113 }
114
115 /**
116  * Add code highlighting to a single element.
117  * @param {HTMLElement} elem
118  */
119 function highlightElem(elem) {
120     const innerCodeElem = elem.querySelector('code[class^=language-]');
121     elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
122     const content = elem.textContent.trimEnd();
123
124     let mode = '';
125     if (innerCodeElem !== null) {
126         const langName = innerCodeElem.className.replace('language-', '');
127         mode = getMode(langName, content);
128     }
129
130     const cm = CodeMirror(function(elt) {
131         elem.parentNode.replaceChild(elt, elem);
132     }, {
133         value: content,
134         mode:  mode,
135         lineNumbers: true,
136         lineWrapping: false,
137         theme: getTheme(),
138         readOnly: true
139     });
140
141     addCopyIcon(cm);
142 }
143
144 /**
145  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
146  * @param cmInstance
147  */
148 function addCopyIcon(cmInstance) {
149     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>`;
150     const copyButton = document.createElement('div');
151     copyButton.classList.add('CodeMirror-copy');
152     copyButton.innerHTML = copyIcon;
153     cmInstance.display.wrapper.appendChild(copyButton);
154
155     const clipboard = new Clipboard(copyButton, {
156         text: function(trigger) {
157             return cmInstance.getValue()
158         }
159     });
160
161     clipboard.on('success', event => {
162         copyButton.classList.add('success');
163         setTimeout(() => {
164             copyButton.classList.remove('success');
165         }, 240);
166     });
167 }
168
169 /**
170  * Search for a codemirror code based off a user suggestion
171  * @param {String} suggestion
172  * @param {String} content
173  * @returns {string}
174  */
175 function getMode(suggestion, content) {
176     suggestion = suggestion.trim().replace(/^\./g, '').toLowerCase();
177
178     const modeMapType = typeof modeMap[suggestion];
179
180     if (modeMapType === 'undefined') {
181         return '';
182     }
183
184     if (modeMapType === 'function') {
185         return modeMap[suggestion](content);
186     }
187
188     return modeMap[suggestion];
189 }
190
191 /**
192  * Ge the theme to use for CodeMirror instances.
193  * @returns {*|string}
194  */
195 function getTheme() {
196     const darkMode = document.documentElement.classList.contains('dark-mode');
197     return window.codeTheme || (darkMode ? 'darcula' : 'default');
198 }
199
200 /**
201  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
202  *  Manages a textarea element to hold code content.
203  * @param {HTMLElement} elem
204  * @returns {{wrap: Element, editor: *}}
205  */
206 function wysiwygView(elem) {
207     const doc = elem.ownerDocument;
208     const codeElem = elem.querySelector('code');
209
210     let lang = (elem.className || '').replace('language-', '');
211     if (lang === '' && codeElem) {
212         lang = (codeElem.className || '').replace('language-', '')
213     }
214
215     elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
216     const content = elem.textContent;
217     const newWrap = doc.createElement('div');
218     const newTextArea = doc.createElement('textarea');
219
220     newWrap.className = 'CodeMirrorContainer';
221     newWrap.setAttribute('data-lang', lang);
222     newWrap.setAttribute('dir', 'ltr');
223     newTextArea.style.display = 'none';
224     elem.parentNode.replaceChild(newWrap, elem);
225
226     newWrap.appendChild(newTextArea);
227     newWrap.contentEditable = false;
228     newTextArea.textContent = content;
229
230     let cm = CodeMirror(function(elt) {
231         newWrap.appendChild(elt);
232     }, {
233         value: content,
234         mode:  getMode(lang, content),
235         lineNumbers: true,
236         lineWrapping: false,
237         theme: getTheme(),
238         readOnly: true
239     });
240     setTimeout(() => {
241         cm.refresh();
242     }, 300);
243     return {wrap: newWrap, editor: cm};
244 }
245
246 /**
247  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
248  * @param {HTMLElement} elem
249  * @param {String} modeSuggestion
250  * @returns {*}
251  */
252 function popupEditor(elem, modeSuggestion) {
253     const content = elem.textContent;
254
255     return CodeMirror(function(elt) {
256         elem.parentNode.insertBefore(elt, elem);
257         elem.style.display = 'none';
258     }, {
259         value: content,
260         mode:  getMode(modeSuggestion, content),
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 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 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 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 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 dependant on the user's system.
322  * @returns {string}
323  */
324 function getMetaKey() {
325     let mac = CodeMirror.keyMap["default"] == CodeMirror.keyMap.macDefault;
326     return mac ? "Cmd" : "Ctrl";
327 }
328
329 export default {
330     highlight: highlight,
331     highlightWithin: highlightWithin,
332     wysiwygView: wysiwygView,
333     popupEditor: popupEditor,
334     setMode: setMode,
335     setContent: setContent,
336     updateLayout: updateLayout,
337     markdownEditor: markdownEditor,
338     getMetaKey: getMetaKey,
339 };