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