]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
3fe4a6d86bd5107a30ee44388607243a5c9e738b
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from "@codemirror/view"
2 import Clipboard from "clipboard/dist/clipboard.min";
3
4 // Modes
5 import {viewer, editor} from "./setups.js";
6 import {createView, updateViewLanguage} from "./views.js";
7
8 /**
9  * Highlight pre elements on a page
10  */
11 export function highlight() {
12     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
13     for (const codeBlock of codeBlocks) {
14         highlightElem(codeBlock);
15     }
16 }
17
18 /**
19  * Highlight all code blocks within the given parent element
20  * @param {HTMLElement} parent
21  */
22 export function highlightWithin(parent) {
23     const codeBlocks = parent.querySelectorAll('pre');
24     for (const codeBlock of codeBlocks) {
25         highlightElem(codeBlock);
26     }
27 }
28
29 /**
30  * Add code highlighting to a single element.
31  * @param {HTMLElement} elem
32  */
33 function highlightElem(elem) {
34     const innerCodeElem = elem.querySelector('code[class^=language-]');
35     elem.innerHTML = elem.innerHTML.replace(/<br\s*[\/]?>/gi ,'\n');
36     const content = elem.textContent.trimEnd();
37
38     let langName = '';
39     if (innerCodeElem !== null) {
40         langName = innerCodeElem.className.replace('language-', '');
41     }
42
43     const wrapper = document.createElement('div');
44     elem.parentNode.insertBefore(wrapper, elem);
45
46     const ev = createView({
47         parent: wrapper,
48         doc: content,
49         extensions: viewer(),
50     });
51     setMode(ev, langName, content);
52
53     elem.remove();
54
55     addCopyIcon(ev);
56 }
57
58 /**
59  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
60  * @param cmInstance
61  */
62 function addCopyIcon(cmInstance) {
63     // TODO
64     // 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>`;
65     // const copyButton = document.createElement('div');
66     // copyButton.classList.add('CodeMirror-copy');
67     // copyButton.innerHTML = copyIcon;
68     // cmInstance.display.wrapper.appendChild(copyButton);
69     //
70     // const clipboard = new Clipboard(copyButton, {
71     //     text: function(trigger) {
72     //         return cmInstance.getValue()
73     //     }
74     // });
75     //
76     // clipboard.on('success', event => {
77     //     copyButton.classList.add('success');
78     //     setTimeout(() => {
79     //         copyButton.classList.remove('success');
80     //     }, 240);
81     // });
82 }
83
84 /**
85  * Ge the theme to use for CodeMirror instances.
86  * @returns {*|string}
87  */
88 function getTheme() {
89     const darkMode = document.documentElement.classList.contains('dark-mode');
90     return window.codeTheme || (darkMode ? 'darcula' : 'default');
91 }
92
93 /**
94  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
95  *  Manages a textarea element to hold code content.
96  * @param {HTMLElement} cmContainer
97  * @param {String} content
98  * @param {String} language
99  * @returns {{wrap: Element, editor: *}}
100  */
101 export function wysiwygView(cmContainer, content, language) {
102     return CodeMirror(cmContainer, {
103         value: content,
104         mode: getMode(language, content),
105         lineNumbers: true,
106         lineWrapping: false,
107         theme: getTheme(),
108         readOnly: true
109     });
110 }
111
112
113 /**
114  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
115  * @param {HTMLElement} elem
116  * @param {String} modeSuggestion
117  * @returns {*}
118  */
119 export function popupEditor(elem, modeSuggestion) {
120     const content = elem.textContent;
121
122     return CodeMirror(function(elt) {
123         elem.parentNode.insertBefore(elt, elem);
124         elem.style.display = 'none';
125     }, {
126         value: content,
127         mode:  getMode(modeSuggestion, content),
128         lineNumbers: true,
129         lineWrapping: false,
130         theme: getTheme()
131     });
132 }
133
134 /**
135  * Create an inline editor to replace the given textarea.
136  * @param {HTMLTextAreaElement} textArea
137  * @param {String} mode
138  * @returns {CodeMirror3}
139  */
140 export function inlineEditor(textArea, mode) {
141     return CodeMirror.fromTextArea(textArea, {
142         mode: getMode(mode, textArea.value),
143         lineNumbers: true,
144         lineWrapping: false,
145         theme: getTheme(),
146     });
147 }
148
149 /**
150  * Set the language mode of a codemirror EditorView.
151  *
152  * @param {EditorView} ev
153  * @param {string} modeSuggestion
154  * @param {string} content
155  */
156 export function setMode(ev, modeSuggestion, content) {
157     updateViewLanguage(ev, modeSuggestion, content);
158 }
159
160 /**
161  * Set the content of a cm instance.
162  * @param cmInstance
163  * @param codeContent
164  */
165 export function setContent(cmInstance, codeContent) {
166     cmInstance.setValue(codeContent);
167     setTimeout(() => {
168         updateLayout(cmInstance);
169     }, 10);
170 }
171
172 /**
173  * Update the layout (codemirror refresh) of a cm instance.
174  * @param cmInstance
175  */
176 export function updateLayout(cmInstance) {
177     cmInstance.refresh();
178 }
179
180 /**
181  * Get a CodeMirror instance to use for the markdown editor.
182  * @param {HTMLElement} elem
183  * @param {function} onChange
184  * @param {object} domEventHandlers
185  * @param {Array} keyBindings
186  * @returns {*}
187  */
188 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
189     const content = elem.textContent;
190
191     // TODO - Change to pass something else that's useful, probably extension array?
192     // window.$events.emitPublic(elem, 'editor-markdown-cm::pre-init', {config});
193
194     const ev = createView({
195         parent: elem.parentNode,
196         doc: content,
197         extensions: [
198             ...editor('markdown'),
199             EditorView.updateListener.of((v) => {
200                 onChange(v);
201             }),
202             EditorView.domEventHandlers(domEventHandlers),
203             keymap.of(keyBindings),
204         ],
205     });
206
207     elem.style.display = 'none';
208
209     return ev;
210 }