]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/plugin-codeeditor.js
Started refactor and alignment of component system
[bookstack] / resources / js / wysiwyg / plugin-codeeditor.js
1 function elemIsCodeBlock(elem) {
2     return elem.tagName.toLowerCase() === 'code-block';
3 }
4
5 /**
6  * @param {Editor} editor
7  * @param {String} code
8  * @param {String} language
9  * @param {function(string, string)} callback (Receives (code: string,language: string)
10  */
11 function showPopup(editor, code, language, callback) {
12     window.$components.first('code-editor').open(code, language, (newCode, newLang) => {
13         callback(newCode, newLang)
14         editor.focus()
15     });
16 }
17
18 /**
19  * @param {Editor} editor
20  * @param {CodeBlockElement} codeBlock
21  */
22 function showPopupForCodeBlock(editor, codeBlock) {
23     showPopup(editor, codeBlock.getContent(), codeBlock.getLanguage(), (newCode, newLang) => {
24         codeBlock.setContent(newCode, newLang);
25     });
26 }
27
28 /**
29  * Define our custom code-block HTML element that we use.
30  * Needs to be delayed since it needs to be defined within the context of the
31  * child editor window and document, hence its definition within a callback.
32  * @param {Editor} editor
33  */
34 function defineCodeBlockCustomElement(editor) {
35     const doc = editor.getDoc();
36     const win = doc.defaultView;
37
38     class CodeBlockElement extends win.HTMLElement {
39         constructor() {
40             super();
41             this.attachShadow({mode: 'open'});
42
43             const stylesToCopy = document.querySelectorAll('link[rel="stylesheet"]:not([media="print"])');
44             const copiedStyles = Array.from(stylesToCopy).map(styleEl => styleEl.cloneNode(false));
45
46             const cmContainer = document.createElement('div');
47             cmContainer.style.pointerEvents = 'none';
48             cmContainer.contentEditable = 'false';
49             cmContainer.classList.add('CodeMirrorContainer');
50
51             this.shadowRoot.append(...copiedStyles, cmContainer);
52         }
53
54         getLanguage() {
55             const getLanguageFromClassList = (classes) => {
56                 const langClasses = classes.split(' ').filter(cssClass => cssClass.startsWith('language-'));
57                 return (langClasses[0] || '').replace('language-', '');
58             };
59
60             const code = this.querySelector('code');
61             const pre = this.querySelector('pre');
62             return getLanguageFromClassList(pre.className) || (code && getLanguageFromClassList(code.className)) || '';
63         }
64
65         setContent(content, language) {
66             if (this.cm) {
67                 importVersioned('code').then(Code => {
68                     Code.setContent(this.cm, content);
69                     Code.setMode(this.cm, language, content);
70                 });
71             }
72
73             let pre = this.querySelector('pre');
74             if (!pre) {
75                 pre = doc.createElement('pre');
76                 this.append(pre);
77             }
78             pre.innerHTML = '';
79
80             const code = doc.createElement('code');
81             pre.append(code);
82             code.innerText = content;
83             code.className = `language-${language}`;
84         }
85
86         getContent() {
87             const code = this.querySelector('code') || this.querySelector('pre');
88             const tempEl = document.createElement('pre');
89             tempEl.innerHTML = code.innerHTML.replace(/\ufeff/g, '');
90
91             const brs = tempEl.querySelectorAll('br');
92             for (const br of brs) {
93                 br.replaceWith('\n');
94             }
95
96             return tempEl.textContent;
97         }
98
99         connectedCallback() {
100             const connectedTime = Date.now();
101             if (this.cm) {
102                 return;
103             }
104
105             this.cleanChildContent();
106             const content = this.getContent();
107             const lines = content.split('\n').length;
108             const height = (lines * 19.2) + 18 + 24;
109             this.style.height = `${height}px`;
110
111             const container = this.shadowRoot.querySelector('.CodeMirrorContainer');
112             const renderCodeMirror = (Code) => {
113                 this.cm = Code.wysiwygView(container, content, this.getLanguage());
114                 setTimeout(() => Code.updateLayout(this.cm), 10);
115                 setTimeout(() => this.style.height = null, 12);
116             };
117
118             window.importVersioned('code').then((Code) => {
119                 const timeout = (Date.now() - connectedTime < 20) ? 20 : 0;
120                 setTimeout(() => renderCodeMirror(Code), timeout);
121             });
122         }
123
124         cleanChildContent() {
125             const pre = this.querySelector('pre');
126             if (!pre) return;
127
128             for (const preChild of pre.childNodes) {
129                 if (preChild.nodeName === '#text' && preChild.textContent === '') {
130                     preChild.remove();
131                 }
132             }
133         }
134     }
135
136     win.customElements.define('code-block', CodeBlockElement);
137 }
138
139
140 /**
141  * @param {Editor} editor
142  * @param {String} url
143  */
144 function register(editor, url) {
145
146     editor.ui.registry.addIcon('codeblock', '<svg width="24" height="24"><path d="M4 3h16c.6 0 1 .4 1 1v16c0 .6-.4 1-1 1H4a1 1 0 0 1-1-1V4c0-.6.4-1 1-1Zm1 2v14h14V5Z"/><path d="M11.103 15.423c.277.277.277.738 0 .922a.692.692 0 0 1-1.106 0l-4.057-3.78a.738.738 0 0 1 0-1.107l4.057-3.872c.276-.277.83-.277 1.106 0a.724.724 0 0 1 0 1.014L7.6 12.012ZM12.897 8.577c-.245-.312-.2-.675.08-.955.28-.281.727-.27 1.027.033l4.057 3.78a.738.738 0 0 1 0 1.107l-4.057 3.872c-.277.277-.83.277-1.107 0a.724.724 0 0 1 0-1.014l3.504-3.412z"/></svg>')
147
148     editor.ui.registry.addButton('codeeditor', {
149         tooltip: 'Insert code block',
150         icon: 'codeblock',
151         onAction() {
152             editor.execCommand('codeeditor');
153         }
154     });
155
156     editor.ui.registry.addButton('editcodeeditor', {
157         tooltip: 'Edit code block',
158         icon: 'edit-block',
159         onAction() {
160             editor.execCommand('codeeditor');
161         }
162     });
163
164     editor.addCommand('codeeditor', () => {
165         const selectedNode = editor.selection.getNode();
166         const doc = selectedNode.ownerDocument;
167         if (elemIsCodeBlock(selectedNode)) {
168             showPopupForCodeBlock(editor, selectedNode);
169         } else {
170             const textContent = editor.selection.getContent({format: 'text'});
171             showPopup(editor, textContent, '', (newCode, newLang) => {
172                 const pre = doc.createElement('pre');
173                 const code = doc.createElement('code');
174                 code.classList.add(`language-${newLang}`);
175                 code.innerText = newCode;
176                 pre.append(code);
177
178                 editor.insertContent(pre.outerHTML);
179             });
180         }
181     });
182
183     editor.on('dblclick', event => {
184         let selectedNode = editor.selection.getNode();
185         if (elemIsCodeBlock(selectedNode)) {
186             showPopupForCodeBlock(editor, selectedNode);
187         }
188     });
189
190     editor.on('PreInit', () => {
191         editor.parser.addNodeFilter('pre', function(elms) {
192             for (const el of elms) {
193                 const wrapper = tinymce.html.Node.create('code-block', {
194                     contenteditable: 'false',
195                 });
196
197                 const spans = el.getAll('span');
198                 for (const span of spans) {
199                     span.unwrap();
200                 }
201                 el.attr('style', null);
202                 el.wrap(wrapper);
203             }
204         });
205
206         editor.parser.addNodeFilter('code-block', function(elms) {
207             for (const el of elms) {
208                 el.attr('contenteditable', 'false');
209             }
210         });
211
212         editor.serializer.addNodeFilter('code-block', function(elms) {
213             for (const el of elms) {
214                 el.unwrap();
215             }
216         });
217     });
218
219     editor.ui.registry.addContextToolbar('codeeditor', {
220         predicate: function (node) {
221             return node.nodeName.toLowerCase() === 'code-block';
222         },
223         items: 'editcodeeditor',
224         position: 'node',
225         scope: 'node'
226     });
227
228     editor.on('PreInit', () => {
229         defineCodeBlockCustomElement(editor);
230     });
231 }
232
233 /**
234  * @param {WysiwygConfigOptions} options
235  * @return {register}
236  */
237 export function getPlugin(options) {
238     return register;
239 }