]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
32c25d401f8ee497e775d25ab5e02b56959f6459
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from "@codemirror/view";
2
3 import {copyTextToClipboard} from "../services/clipboard.js"
4 import {viewerExtensions, editorExtensions} from "./setups.js";
5 import {createView} from "./views.js";
6 import {SimpleEditorInterface} from "./simple-editor-interface.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: viewerExtensions(wrapper),
50     });
51
52     const editor = new SimpleEditorInterface(ev);
53     editor.setMode(langName, content);
54
55     elem.remove();
56     addCopyIcon(ev);
57 }
58
59 /**
60  * Add a button to a CodeMirror instance which copies the contents to the clipboard upon click.
61  * @param {EditorView} editorView
62  */
63 function addCopyIcon(editorView) {
64     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>`;
65     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>`;
66     const copyButton = document.createElement('button');
67     copyButton.setAttribute('type', 'button')
68     copyButton.classList.add('cm-copy-button');
69     copyButton.innerHTML = copyIcon;
70     editorView.dom.appendChild(copyButton);
71
72     const notifyTime = 620;
73     const transitionTime = 60;
74     copyButton.addEventListener('click', event => {
75         copyTextToClipboard(editorView.state.doc.toString());
76         copyButton.classList.add('success');
77
78         setTimeout(() => {
79             copyButton.innerHTML = checkIcon;
80         }, transitionTime / 2);
81
82         setTimeout(() => {
83             copyButton.classList.remove('success');
84         }, notifyTime);
85
86         setTimeout(() => {
87             copyButton.innerHTML = copyIcon;
88         }, notifyTime + (transitionTime / 2));
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({
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 /**
117  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
118  * @param {HTMLElement} elem
119  * @param {String} modeSuggestion
120  * @returns {SimpleEditorInterface}
121  */
122 export function popupEditor(elem, modeSuggestion) {
123     const content = elem.textContent;
124     const config = {
125         parent: elem.parentElement,
126         doc: content,
127         extensions: [
128             ...editorExtensions(elem.parentElement),
129             EditorView.updateListener.of((v) => {
130                 if (v.docChanged) {
131                     // textArea.value = v.state.doc.toString();
132                 }
133             }),
134         ],
135     };
136
137     // Create editor, hide original input
138     const editor = new SimpleEditorInterface(createView(config));
139     editor.setMode(modeSuggestion, content);
140     elem.style.display = 'none';
141
142     return editor;
143 }
144
145 /**
146  * Create an inline editor to replace the given textarea.
147  * @param {HTMLTextAreaElement} textArea
148  * @param {String} mode
149  * @returns {SimpleEditorInterface}
150  */
151 export function inlineEditor(textArea, mode) {
152     const content = textArea.value;
153     const config = {
154         parent: textArea.parentElement,
155         doc: content,
156         extensions: [
157             ...editorExtensions(textArea.parentElement),
158             EditorView.updateListener.of((v) => {
159                 if (v.docChanged) {
160                     textArea.value = v.state.doc.toString();
161                 }
162             }),
163         ],
164     };
165
166     // Create editor view, hide original input
167     const ev = createView(config);
168     const editor = new SimpleEditorInterface(ev);
169     editor.setMode(mode, content);
170     textArea.style.display = 'none';
171
172     return editor;
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 {EditorView}
182  */
183 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
184     const content = elem.textContent;
185     const config = {
186         parent: elem.parentElement,
187         doc: content,
188         extensions: [
189             keymap.of(keyBindings),
190             ...editorExtensions(elem.parentElement),
191             EditorView.updateListener.of((v) => {
192                 onChange(v);
193             }),
194             EditorView.domEventHandlers(domEventHandlers),
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-cm6::pre-init', {editorViewConfig: config});
200
201     // Create editor view, hide original input
202     const ev = createView(config);
203     (new SimpleEditorInterface(ev)).setMode('markdown', '');
204     elem.style.display = 'none';
205
206     return ev;
207 }