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