]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
JS Events: Added CM pre/post init events
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from '@codemirror/view';
2
3 import {copyTextToClipboard} from '../services/clipboard';
4 import {viewerExtensions, editorExtensions} from './setups';
5 import {createView} from './views';
6 import {SimpleEditorInterface} from './simple-editor-interface';
7
8 /**
9  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
10  * @param {EditorView} editorView
11  */
12 function addCopyIcon(editorView) {
13     const copyIcon = '<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><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>';
14     const checkIcon = '<svg viewBox="0 0 24 24" width="16" height="16" xmlns="http://www.w3.org/2000/svg"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
15     const copyButton = document.createElement('button');
16     copyButton.setAttribute('type', 'button');
17     copyButton.classList.add('cm-copy-button');
18     copyButton.innerHTML = copyIcon;
19     editorView.dom.appendChild(copyButton);
20
21     const notifyTime = 620;
22     const transitionTime = 60;
23     copyButton.addEventListener('click', () => {
24         copyTextToClipboard(editorView.state.doc.toString());
25         copyButton.classList.add('success');
26
27         setTimeout(() => {
28             copyButton.innerHTML = checkIcon;
29         }, transitionTime / 2);
30
31         setTimeout(() => {
32             copyButton.classList.remove('success');
33         }, notifyTime);
34
35         setTimeout(() => {
36             copyButton.innerHTML = copyIcon;
37         }, notifyTime + (transitionTime / 2));
38     });
39 }
40
41 /**
42  * Add code highlighting to a single element.
43  * @param {HTMLElement} elem
44  */
45 function highlightElem(elem) {
46     const innerCodeElem = elem.querySelector('code[class^=language-]');
47     elem.innerHTML = elem.innerHTML.replace(/<br\s*\/?>/gi, '\n');
48     const content = elem.textContent.trimEnd();
49
50     let langName = '';
51     if (innerCodeElem !== null) {
52         langName = innerCodeElem.className.replace('language-', '');
53     }
54
55     const wrapper = document.createElement('div');
56     elem.parentNode.insertBefore(wrapper, elem);
57
58     const ev = createView('content-code-block', {
59         parent: wrapper,
60         doc: content,
61         extensions: viewerExtensions(wrapper),
62     });
63
64     const editor = new SimpleEditorInterface(ev);
65     editor.setMode(langName, content);
66
67     elem.remove();
68     addCopyIcon(ev);
69 }
70
71 /**
72  * Highlight all code blocks within the given parent element
73  * @param {HTMLElement} parent
74  */
75 export function highlightWithin(parent) {
76     const codeBlocks = parent.querySelectorAll('pre');
77     for (const codeBlock of codeBlocks) {
78         highlightElem(codeBlock);
79     }
80 }
81
82 /**
83  * Highlight pre elements on a page
84  */
85 export function highlight() {
86     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
87     for (const codeBlock of codeBlocks) {
88         highlightElem(codeBlock);
89     }
90 }
91
92 /**
93  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
94  * Manages a textarea element to hold code content.
95  * @param {HTMLElement} cmContainer
96  * @param {ShadowRoot} shadowRoot
97  * @param {String} content
98  * @param {String} language
99  * @returns {SimpleEditorInterface}
100  */
101 export function wysiwygView(cmContainer, shadowRoot, content, language) {
102     const ev = createView('content-code-block', {
103         parent: cmContainer,
104         doc: content,
105         extensions: viewerExtensions(cmContainer),
106         root: shadowRoot,
107     });
108
109     const editor = new SimpleEditorInterface(ev);
110     editor.setMode(language, content);
111
112     return editor;
113 }
114
115 /**
116  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
117  * @param {HTMLElement} elem
118  * @param {String} modeSuggestion
119  * @returns {SimpleEditorInterface}
120  */
121 export function popupEditor(elem, modeSuggestion) {
122     const content = elem.textContent;
123     const config = {
124         parent: elem.parentElement,
125         doc: content,
126         extensions: [
127             ...editorExtensions(elem.parentElement),
128         ],
129     };
130
131     // Create editor, hide original input
132     const editor = new SimpleEditorInterface(createView('code-editor', config));
133     editor.setMode(modeSuggestion, content);
134     elem.style.display = 'none';
135
136     return editor;
137 }
138
139 /**
140  * Create an inline editor to replace the given textarea.
141  * @param {HTMLTextAreaElement} textArea
142  * @param {String} mode
143  * @returns {SimpleEditorInterface}
144  */
145 export function inlineEditor(textArea, mode) {
146     const content = textArea.value;
147     const config = {
148         parent: textArea.parentElement,
149         doc: content,
150         extensions: [
151             ...editorExtensions(textArea.parentElement),
152             EditorView.updateListener.of(v => {
153                 if (v.docChanged) {
154                     textArea.value = v.state.doc.toString();
155                 }
156             }),
157         ],
158     };
159
160     // Create editor view, hide original input
161     const ev = createView('code-input', config);
162     const editor = new SimpleEditorInterface(ev);
163     editor.setMode(mode, content);
164     textArea.style.display = 'none';
165
166     return editor;
167 }
168
169 /**
170  * Get a CodeMirror instance to use for the markdown editor.
171  * @param {HTMLElement} elem
172  * @param {function} onChange
173  * @param {object} domEventHandlers
174  * @param {Array} keyBindings
175  * @returns {EditorView}
176  */
177 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
178     const content = elem.textContent;
179     const config = {
180         parent: elem.parentElement,
181         doc: content,
182         extensions: [
183             keymap.of(keyBindings),
184             ...editorExtensions(elem.parentElement),
185             EditorView.updateListener.of(v => {
186                 onChange(v);
187             }),
188             EditorView.domEventHandlers(domEventHandlers),
189         ],
190     };
191
192     // Emit a pre-event public event to allow tweaking of the configure before view creation.
193     window.$events.emitPublic(elem, 'editor-markdown-cm6::pre-init', {editorViewConfig: config});
194
195     // Create editor view, hide original input
196     const ev = createView('markdown-editor', config);
197     (new SimpleEditorInterface(ev)).setMode('markdown', '');
198     elem.style.display = 'none';
199
200     return ev;
201 }