]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/plugin-codeeditor.js
Added pre-render sizes to wysiwyg code blocks
[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             const linkElem = document.createElement('link');
43             linkElem.setAttribute('rel', 'stylesheet');
44             linkElem.setAttribute('href', window.baseUrl('/dist/styles.css'));
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(linkElem, 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().replace(/<br\s*[\/]?>/gi ,'\n').replace(/\ufeff/g, '');
90             return tempEl.textContent;
91         }
92
93         connectedCallback() {
94             const connectedTime = Date.now();
95             if (this.cm) {
96                 return;
97             }
98
99             this.cleanChildContent();
100             const content = this.getContent();
101             const lines = content.split('\n').length;
102             const height = (lines * 19.2) + 18 + 24;
103             this.style.height = `${height}px`;
104
105             const container = this.shadowRoot.querySelector('.CodeMirrorContainer');
106             const renderCodeMirror = (Code) => {
107                 this.cm = Code.wysiwygView(container, content, this.getLanguage());
108                 Code.updateLayout(this.cm);
109                 setTimeout(() => {
110                     this.style.height = null;
111                 }, 1);
112             };
113
114             window.importVersioned('code').then((Code) => {
115                 const timeout = (Date.now() - connectedTime < 20) ? 20 : 0;
116                 setTimeout(() => renderCodeMirror(Code), timeout);
117             });
118         }
119
120         cleanChildContent() {
121             const pre = this.querySelector('pre');
122             if (!pre) return;
123
124             for (const preChild of pre.childNodes) {
125                 if (preChild.nodeName === '#text' && preChild.textContent === '') {
126                     preChild.remove();
127                 }
128             }
129         }
130     }
131
132     win.customElements.define('code-block', CodeBlockElement);
133 }
134
135
136 /**
137  * @param {Editor} editor
138  * @param {String} url
139  */
140 function register(editor, url) {
141
142     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>')
143
144     editor.ui.registry.addButton('codeeditor', {
145         tooltip: 'Insert code block',
146         icon: 'codeblock',
147         onAction() {
148             editor.execCommand('codeeditor');
149         }
150     });
151
152     editor.addCommand('codeeditor', () => {
153         const selectedNode = editor.selection.getNode();
154         const doc = selectedNode.ownerDocument;
155         if (elemIsCodeBlock(selectedNode)) {
156             showPopupForCodeBlock(editor, selectedNode);
157         } else {
158             const textContent = editor.selection.getContent({format: 'text'});
159             showPopup(editor, textContent, '', (newCode, newLang) => {
160                 const pre = doc.createElement('pre');
161                 const code = doc.createElement('code');
162                 code.classList.add(`language-${newLang}`);
163                 code.innerText = newCode;
164                 pre.append(code);
165
166                 editor.insertContent(pre.outerHTML);
167             });
168         }
169     });
170
171     editor.on('dblclick', event => {
172         let selectedNode = editor.selection.getNode();
173         if (elemIsCodeBlock(selectedNode)) {
174             showPopupForCodeBlock(editor, selectedNode);
175         }
176     });
177
178     editor.on('PreInit', () => {
179         editor.parser.addNodeFilter('pre', function(elms) {
180             for (const el of elms) {
181                 const wrapper = new tinymce.html.Node.create('code-block', {
182                     contenteditable: 'false',
183                 });
184
185                 const spans = el.getAll('span');
186                 for (const span of spans) {
187                     span.unwrap();
188                 }
189                 el.attr('style', null);
190                 el.wrap(wrapper);
191             }
192         });
193
194         editor.parser.addNodeFilter('code-block', function(elms) {
195             for (const el of elms) {
196                 el.attr('contenteditable', 'false');
197             }
198         });
199
200         editor.serializer.addNodeFilter('code-block', function(elms) {
201             for (const el of elms) {
202                 el.unwrap();
203             }
204         });
205     });
206
207     editor.on('PreInit', () => {
208         defineCodeBlockCustomElement(editor);
209     });
210 }
211
212 /**
213  * @param {WysiwygConfigOptions} options
214  * @return {register}
215  */
216 export function getPlugin(options) {
217     return register;
218 }