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