]> BookStack Code Mirror - bookstack/blob - resources/js/code/index.mjs
Merge pull request #5627 from BookStackApp/lexical_20250525
[bookstack] / resources / js / code / index.mjs
1 import {EditorView, keymap} from '@codemirror/view';
2
3 import {copyTextToClipboard} from '../services/clipboard.ts';
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  * @param {HTMLElement} codeElem
43  * @returns {String}
44  */
45 function getDirectionFromCodeBlock(codeElem) {
46     let dir = '';
47     const innerCodeElem = codeElem.querySelector('code');
48
49     if (innerCodeElem && innerCodeElem.hasAttribute('dir')) {
50         dir = innerCodeElem.getAttribute('dir');
51     } else if (codeElem.hasAttribute('dir')) {
52         dir = codeElem.getAttribute('dir');
53     }
54
55     return dir;
56 }
57
58 /**
59  * Add code highlighting to a single element.
60  * @param {HTMLElement} elem
61  */
62 function highlightElem(elem) {
63     const innerCodeElem = elem.querySelector('code[class^=language-]');
64     elem.innerHTML = elem.innerHTML.replace(/<br\s*\/?>/gi, '\n');
65     const content = elem.textContent.trimEnd();
66
67     let langName = '';
68     if (innerCodeElem !== null) {
69         langName = innerCodeElem.className.replace('language-', '');
70     }
71
72     const wrapper = document.createElement('div');
73     elem.parentNode.insertBefore(wrapper, elem);
74
75     const direction = getDirectionFromCodeBlock(elem);
76     if (direction) {
77         wrapper.setAttribute('dir', direction);
78     }
79
80     const ev = createView('content-code-block', {
81         parent: wrapper,
82         doc: content,
83         extensions: viewerExtensions(wrapper),
84     });
85
86     const editor = new SimpleEditorInterface(ev);
87     editor.setMode(langName, content);
88
89     elem.remove();
90     addCopyIcon(ev);
91 }
92
93 /**
94  * Highlight all code blocks within the given parent element
95  * @param {HTMLElement} parent
96  */
97 export function highlightWithin(parent) {
98     const codeBlocks = parent.querySelectorAll('pre');
99     for (const codeBlock of codeBlocks) {
100         highlightElem(codeBlock);
101     }
102 }
103
104 /**
105  * Highlight pre elements on a page
106  */
107 export function highlight() {
108     const codeBlocks = document.querySelectorAll('.page-content pre, .comment-box .content pre');
109     for (const codeBlock of codeBlocks) {
110         highlightElem(codeBlock);
111     }
112 }
113
114 /**
115  * Create a CodeMirror instance for showing inside the WYSIWYG editor.
116  * Manages a textarea element to hold code content.
117  * @param {HTMLElement} cmContainer
118  * @param {ShadowRoot} shadowRoot
119  * @param {String} content
120  * @param {String} language
121  * @returns {SimpleEditorInterface}
122  */
123 export function wysiwygView(cmContainer, shadowRoot, content, language) {
124     const ev = createView('content-code-block', {
125         parent: cmContainer,
126         doc: content,
127         extensions: viewerExtensions(cmContainer),
128         root: shadowRoot,
129     });
130
131     const editor = new SimpleEditorInterface(ev);
132     editor.setMode(language, content);
133
134     return editor;
135 }
136
137 /**
138  * Create a CodeMirror instance to show in the WYSIWYG pop-up editor
139  * @param {HTMLElement} elem
140  * @param {String} modeSuggestion
141  * @returns {SimpleEditorInterface}
142  */
143 export function popupEditor(elem, modeSuggestion) {
144     const content = elem.textContent;
145     const config = {
146         parent: elem.parentElement,
147         doc: content,
148         extensions: [
149             ...editorExtensions(elem.parentElement),
150         ],
151     };
152
153     // Create editor, hide original input
154     const editor = new SimpleEditorInterface(createView('code-editor', config));
155     editor.setMode(modeSuggestion, content);
156     elem.style.display = 'none';
157
158     return editor;
159 }
160
161 /**
162  * Create an inline editor to replace the given textarea.
163  * @param {HTMLTextAreaElement} textArea
164  * @param {String} mode
165  * @returns {SimpleEditorInterface}
166  */
167 export function inlineEditor(textArea, mode) {
168     const content = textArea.value;
169     const config = {
170         parent: textArea.parentElement,
171         doc: content,
172         extensions: [
173             ...editorExtensions(textArea.parentElement),
174             EditorView.updateListener.of(v => {
175                 if (v.docChanged) {
176                     textArea.value = v.state.doc.toString();
177                 }
178             }),
179         ],
180     };
181
182     // Create editor view, hide original input
183     const ev = createView('code-input', config);
184     const editor = new SimpleEditorInterface(ev);
185     editor.setMode(mode, content);
186     textArea.style.display = 'none';
187
188     return editor;
189 }
190
191 /**
192  * Get a CodeMirror instance to use for the markdown editor.
193  * @param {HTMLElement} elem
194  * @param {function} onChange
195  * @param {object} domEventHandlers
196  * @param {Array} keyBindings
197  * @returns {EditorView}
198  */
199 export function markdownEditor(elem, onChange, domEventHandlers, keyBindings) {
200     const content = elem.textContent;
201     const config = {
202         parent: elem.parentElement,
203         doc: content,
204         extensions: [
205             keymap.of(keyBindings),
206             ...editorExtensions(elem.parentElement),
207             EditorView.updateListener.of(v => {
208                 onChange(v);
209             }),
210             EditorView.domEventHandlers(domEventHandlers),
211         ],
212     };
213
214     // Emit a pre-event public event to allow tweaking of the configure before view creation.
215     window.$events.emitPublic(elem, 'editor-markdown-cm6::pre-init', {editorViewConfig: config});
216
217     // Create editor view, hide original input
218     const ev = createView('markdown-editor', config);
219     (new SimpleEditorInterface(ev)).setMode('markdown', '');
220     elem.style.display = 'none';
221
222     return ev;
223 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.