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