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