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