]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
Merge pull request #4907 from BookStackApp/licensing_update
[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 direction = innerCodeElem.getAttribute('dir') || elem.getAttribute('dir') || '';
59     if (direction) {
60         wrapper.setAttribute('dir', direction);
61     }
62
63     const ev = createView('content-code-block', {
64         parent: wrapper,
65         doc: content,
66         extensions: viewerExtensions(wrapper),
67     });
68
69     const editor = new SimpleEditorInterface(ev);
70     editor.setMode(langName, content);
71
72     elem.remove();
73     addCopyIcon(ev);
74 }
75
76 /**
77  * Highlight all code blocks within the given parent element
78  * @param {HTMLElement} parent
79  */
80 export function highlightWithin(parent) {
81     const codeBlocks = parent.querySelectorAll('pre');
82     for (const codeBlock of codeBlocks) {
83         highlightElem(codeBlock);
84     }
85 }
86
87 /**
88  * Highlight pre elements on a page
89  */
90 export function highlight() {
91     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
92     for (const codeBlock of codeBlocks) {
93         highlightElem(codeBlock);
94     }
95 }
96
97 /**
98  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
99  * Manages a textarea element to hold code content.
100  * @param {HTMLElement} cmContainer
101  * @param {ShadowRoot} shadowRoot
102  * @param {String} content
103  * @param {String} language
104  * @returns {SimpleEditorInterface}
105  */
106 export function wysiwygView(cmContainer, shadowRoot, content, language) {
107     const ev = createView('content-code-block', {
108         parent: cmContainer,
109         doc: content,
110         extensions: viewerExtensions(cmContainer),
111         root: shadowRoot,
112     });
113
114     const editor = new SimpleEditorInterface(ev);
115     editor.setMode(language, content);
116
117     return editor;
118 }
119
120 /**
121  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
122  * @param {HTMLElement} elem
123  * @param {String} modeSuggestion
124  * @returns {SimpleEditorInterface}
125  */
126 export function popupEditor(elem, modeSuggestion) {
127     const content = elem.textContent;
128     const config = {
129         parent: elem.parentElement,
130         doc: content,
131         extensions: [
132             ...editorExtensions(elem.parentElement),
133         ],
134     };
135
136     // Create editor, hide original input
137     const editor = new SimpleEditorInterface(createView('code-editor', config));
138     editor.setMode(modeSuggestion, content);
139     elem.style.display = 'none';
140
141     return editor;
142 }
143
144 /**
145  * Create an inline editor to replace the given textarea.
146  * @param {HTMLTextAreaElement} textArea
147  * @param {String} mode
148  * @returns {SimpleEditorInterface}
149  */
150 export function inlineEditor(textArea, mode) {
151     const content = textArea.value;
152     const config = {
153         parent: textArea.parentElement,
154         doc: content,
155         extensions: [
156             ...editorExtensions(textArea.parentElement),
157             EditorView.updateListener.of(v => {
158                 if (v.docChanged) {
159                     textArea.value = v.state.doc.toString();
160                 }
161             }),
162         ],
163     };
164
165     // Create editor view, hide original input
166     const ev = createView('code-input', config);
167     const editor = new SimpleEditorInterface(ev);
168     editor.setMode(mode, content);
169     textArea.style.display = 'none';
170
171     return editor;
172 }
173
174 /**
175  * Get a CodeMirror instance to use for the markdown editor.
176  * @param {HTMLElement} elem
177  * @param {function} onChange
178  * @param {object} domEventHandlers
179  * @param {Array} keyBindings
180  * @returns {EditorView}
181  */
182 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
183     const content = elem.textContent;
184     const config = {
185         parent: elem.parentElement,
186         doc: content,
187         extensions: [
188             keymap.of(keyBindings),
189             ...editorExtensions(elem.parentElement),
190             EditorView.updateListener.of(v => {
191                 onChange(v);
192             }),
193             EditorView.domEventHandlers(domEventHandlers),
194         ],
195     };
196
197     // Emit a pre-event public event to allow tweaking of the configure before view creation.
198     window.$events.emitPublic(elem, 'editor-markdown-cm6::pre-init', {editorViewConfig: config});
199
200     // Create editor view, hide original input
201     const ev = createView('markdown-editor', config);
202     (new SimpleEditorInterface(ev)).setMode('markdown', '');
203     elem.style.display = 'none';
204
205     return ev;
206 }