]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
Addressed existing cm6 todos
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from "@codemirror/view";
2 import {copyTextToClipboard} from "../services/clipboard.js"
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 {EditorView} editorView
61  */
62 function addCopyIcon(editorView) {
63     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>`;
64     const copyButton = document.createElement('button');
65     copyButton.setAttribute('type', 'button')
66     copyButton.classList.add('cm-copy-button');
67     copyButton.innerHTML = copyIcon;
68     editorView.dom.appendChild(copyButton);
69
70     copyButton.addEventListener('click', event => {
71         copyTextToClipboard(editorView.state.doc.toString());
72         copyButton.classList.add('success');
73         setTimeout(() => {
74             copyButton.classList.remove('success');
75         }, 240);
76     });
77 }
78
79 /**
80  * Ge the theme to use for CodeMirror instances.
81  * @returns {*|string}
82  */
83 function getTheme() {
84     const darkMode = document.documentElement.classList.contains('dark-mode');
85     return window.codeTheme || (darkMode ? 'darcula' : 'default');
86 }
87
88 /**
89  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
90  *  Manages a textarea element to hold code content.
91  * @param {HTMLElement} cmContainer
92  * @param {String} content
93  * @param {String} language
94  * @returns {{wrap: Element, editor: *}}
95  */
96 export function wysiwygView(cmContainer, content, language) {
97     return CodeMirror(cmContainer, {
98         value: content,
99         mode: getMode(language, content),
100         lineNumbers: true,
101         lineWrapping: false,
102         theme: getTheme(),
103         readOnly: true
104     });
105 }
106
107
108 /**
109  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
110  * @param {HTMLElement} elem
111  * @param {String} modeSuggestion
112  * @returns {*}
113  */
114 export function popupEditor(elem, modeSuggestion) {
115     const content = elem.textContent;
116
117     return CodeMirror(function(elt) {
118         elem.parentNode.insertBefore(elt, elem);
119         elem.style.display = 'none';
120     }, {
121         value: content,
122         mode:  getMode(modeSuggestion, content),
123         lineNumbers: true,
124         lineWrapping: false,
125         theme: getTheme()
126     });
127 }
128
129 /**
130  * Create an inline editor to replace the given textarea.
131  * @param {HTMLTextAreaElement} textArea
132  * @param {String} mode
133  * @returns {CodeMirror3}
134  */
135 export function inlineEditor(textArea, mode) {
136     return CodeMirror.fromTextArea(textArea, {
137         mode: getMode(mode, textArea.value),
138         lineNumbers: true,
139         lineWrapping: false,
140         theme: getTheme(),
141     });
142 }
143
144 /**
145  * Set the language mode of a codemirror EditorView.
146  *
147  * @param {EditorView} ev
148  * @param {string} modeSuggestion
149  * @param {string} content
150  */
151 export function setMode(ev, modeSuggestion, content) {
152     updateViewLanguage(ev, modeSuggestion, content);
153 }
154
155 /**
156  * Set the content of a cm instance.
157  * @param cmInstance
158  * @param codeContent
159  */
160 export function setContent(cmInstance, codeContent) {
161     cmInstance.setValue(codeContent);
162     setTimeout(() => {
163         updateLayout(cmInstance);
164     }, 10);
165 }
166
167 /**
168  * Update the layout (codemirror refresh) of a cm instance.
169  * @param cmInstance
170  */
171 export function updateLayout(cmInstance) {
172     cmInstance.refresh();
173 }
174
175 /**
176  * Get a CodeMirror instance to use for the markdown editor.
177  * @param {HTMLElement} elem
178  * @param {function} onChange
179  * @param {object} domEventHandlers
180  * @param {Array} keyBindings
181  * @returns {*}
182  */
183 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
184     const content = elem.textContent;
185     const config = {
186         parent: elem.parentNode,
187         doc: content,
188         extensions: [
189             ...editor('markdown'),
190             EditorView.updateListener.of((v) => {
191                 onChange(v);
192             }),
193             EditorView.domEventHandlers(domEventHandlers),
194             keymap.of(keyBindings),
195         ],
196     };
197
198     // Emit a pre-event public event to allow tweaking of the configure before view creation.
199     window.$events.emitPublic(elem, 'editor-markdown-cm::pre-init', {cmEditorViewConfig: config});
200
201     // Create editor view, hide original input
202     const ev = createView(config);
203     elem.style.display = 'none';
204
205     return ev;
206 }