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