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