]> BookStack Code Mirror - bookstack/blob - resources/assets/js/pages/page-form.js
Finished off main functionality of custom tinymce code editor
[bookstack] / resources / assets / js / pages / page-form.js
1 "use strict";
2
3 const Code = require('../code');
4
5 /**
6  * Handle pasting images from clipboard.
7  * @param e  - event
8  * @param editor - editor instance
9  */
10 function editorPaste(e, editor) {
11     if (!e.clipboardData) return;
12     let items = e.clipboardData.items;
13     if (!items) return;
14     for (let i = 0; i < items.length; i++) {
15         if (items[i].type.indexOf("image") === -1) return;
16
17         let file = items[i].getAsFile();
18         let formData = new FormData();
19         let ext = 'png';
20         let xhr = new XMLHttpRequest();
21
22         if (file.name) {
23             let fileNameMatches = file.name.match(/\.(.+)$/);
24             if (fileNameMatches) {
25                 ext = fileNameMatches[1];
26             }
27         }
28
29         let id = "image-" + Math.random().toString(16).slice(2);
30         let loadingImage = window.baseUrl('/loading.gif');
31         editor.execCommand('mceInsertContent', false, `<img src="${loadingImage}" id="${id}">`);
32
33         let remoteFilename = "image-" + Date.now() + "." + ext;
34         formData.append('file', file, remoteFilename);
35         formData.append('_token', document.querySelector('meta[name="token"]').getAttribute('content'));
36
37         xhr.open('POST', window.baseUrl('/images/gallery/upload'));
38         xhr.onload = function () {
39             if (xhr.status === 200 || xhr.status === 201) {
40                 let result = JSON.parse(xhr.responseText);
41                 editor.dom.setAttrib(id, 'src', result.thumbs.display);
42             } else {
43                 console.log('An error occurred uploading the image', xhr.responseText);
44                 editor.dom.remove(id);
45             }
46         };
47         xhr.send(formData);
48         
49     }
50 }
51
52 function registerEditorShortcuts(editor) {
53     // Headers
54     for (let i = 1; i < 5; i++) {
55         editor.addShortcut('meta+' + i, '', ['FormatBlock', false, 'h' + i]);
56     }
57
58     // Other block shortcuts
59     editor.addShortcut('meta+q', '', ['FormatBlock', false, 'blockquote']);
60     editor.addShortcut('meta+d', '', ['FormatBlock', false, 'p']);
61     editor.addShortcut('meta+e', '', ['codeeditor', false, 'pre']);
62     editor.addShortcut('meta+shift+E', '', ['FormatBlock', false, 'code']);
63 }
64
65
66 /**
67  * Create and enable our custom code plugin
68  */
69 function codePlugin() {
70
71     function elemIsCodeBlock(elem) {
72         return elem.className === 'CodeMirrorContainer';
73     }
74
75     function showPopup(editor) {
76         let selectedNode = editor.selection.getNode();
77
78         if (!elemIsCodeBlock(selectedNode)) {
79             let providedCode = editor.selection.getNode().textContent;
80             window.vues['code-editor'].open(providedCode, '', (code, lang) => {
81                 let wrap = document.createElement('div');
82                 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
83                 wrap.querySelector('code').innerText = code;
84                 editor.formatter.toggle('pre');
85                 let node = editor.selection.getNode();
86                 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
87                 editor.fire('SetContent');
88             });
89             return;
90         }
91
92         let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
93         let currentCode = selectedNode.querySelector('textarea').textContent;
94
95         window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
96             let editorElem = selectedNode.querySelector('.CodeMirror');
97             let cmInstance = editorElem.CodeMirror;
98             if (cmInstance) {
99                 Code.setContent(cmInstance, code);
100                 Code.setMode(cmInstance, lang);
101             }
102             let textArea = selectedNode.querySelector('textarea');
103             if (textArea) textArea.textContent = code;
104             selectedNode.setAttribute('data-lang', lang);
105         });
106     }
107
108     window.tinymce.PluginManager.add('codeeditor', (editor, url) => {
109
110         let $ = editor.$;
111
112         editor.addButton('codeeditor', {
113             text: 'Code block',
114             icon: false,
115             cmd: 'codeeditor'
116         });
117
118         editor.addCommand('codeeditor', () => {
119             showPopup(editor);
120         });
121
122         // Convert
123         editor.on('PreProcess', function (e) {
124             $('div.CodeMirrorContainer', e.node).
125             each((index, elem) => {
126                 let $elem = $(elem);
127                 let textArea = elem.querySelector('textarea');
128                 let code = textArea.textContent;
129                 let lang = elem.getAttribute('data-lang');
130
131                 // $elem.attr('class', $.trim($elem.attr('class')));
132                 $elem.removeAttr('contentEditable');
133                 let $pre = $('<pre></pre>');
134                 $pre.append($('<code></code>').each((index, elem) => {
135                     // Needs to be textContent since innerText produces BR:s
136                     elem.textContent = code;
137                 }).attr('class', `language-${lang}`));
138                 $elem.replaceWith($pre);
139             });
140         });
141
142         editor.on('SetContent', function () {
143             let codeSamples = $('body > pre').filter((index, elem) => {
144                 return elem.contentEditable !== "false";
145             });
146
147             if (codeSamples.length) {
148                 editor.undoManager.transact(function () {
149                     codeSamples.each((index, elem) => {
150                         let editDetails = Code.wysiwygView(elem);
151                         editDetails.wrap.addEventListener('dblclick', () => {
152                             showPopup(editor, editDetails.wrap, editDetails.editor);
153                         });
154                     });
155                 });
156             }
157         });
158
159     });
160 }
161
162 module.exports = function() {
163     codePlugin();
164     let settings = {
165         selector: '#html-editor',
166         content_css: [
167             window.baseUrl('/css/styles.css'),
168             window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
169         ],
170         branding: false,
171         body_class: 'page-content',
172         browser_spellcheck: true,
173         relative_urls: false,
174         remove_script_host: false,
175         document_base_url: window.baseUrl('/'),
176         statusbar: false,
177         menubar: false,
178         paste_data_images: false,
179         extended_valid_elements: 'pre[*]',
180         automatic_uploads: false,
181         valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]",
182         plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor",
183         imagetools_toolbar: 'imageoptions',
184         toolbar: "undo redo | styleselect | bold italic underline strikethrough superscript subscript | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image-insert link hr | removeformat code fullscreen",
185         content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
186         style_formats: [
187             {title: "Header Large", format: "h2"},
188             {title: "Header Medium", format: "h3"},
189             {title: "Header Small", format: "h4"},
190             {title: "Header Tiny", format: "h5"},
191             {title: "Paragraph", format: "p", exact: true, classes: ''},
192             {title: "Blockquote", format: "blockquote"},
193             {title: "Code Block", icon: "code", cmd: 'codeeditor'},
194             {title: "Inline Code", icon: "code", inline: "code"},
195             {title: "Callouts", items: [
196                 {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}},
197                 {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}},
198                 {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}},
199                 {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}}
200             ]},
201         ],
202         style_formats_merge: false,
203         formats: {
204             alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
205             aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
206             alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
207         },
208         file_browser_callback: function (field_name, url, type, win) {
209
210             if (type === 'file') {
211                 window.showEntityLinkSelector(function(entity) {
212                     let originalField = win.document.getElementById(field_name);
213                     originalField.value = entity.link;
214                     $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
215                 });
216             }
217
218             if (type === 'image') {
219                 // Show image manager
220                 window.ImageManager.showExternal(function (image) {
221
222                     // Set popover link input to image url then fire change event
223                     // to ensure the new value sticks
224                     win.document.getElementById(field_name).value = image.url;
225                     if ("createEvent" in document) {
226                         let evt = document.createEvent("HTMLEvents");
227                         evt.initEvent("change", false, true);
228                         win.document.getElementById(field_name).dispatchEvent(evt);
229                     } else {
230                         win.document.getElementById(field_name).fireEvent("onchange");
231                     }
232
233                     // Replace the actively selected content with the linked image
234                     let html = `<a href="${image.url}" target="_blank">`;
235                     html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
236                     html += '</a>';
237                     win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
238                 });
239             }
240
241         },
242         paste_preprocess: function (plugin, args) {
243             let content = args.content;
244             if (content.indexOf('<img src="file://') !== -1) {
245                 args.content = '';
246             }
247         },
248         extraSetups: [],
249         setup: function (editor) {
250
251             // Run additional setup actions
252             // Used by the angular side of things
253             for (let i = 0; i < settings.extraSetups.length; i++) {
254                 settings.extraSetups[i](editor);
255             }
256
257             registerEditorShortcuts(editor);
258
259             let wrap;
260
261             function hasTextContent(node) {
262                 return node && !!( node.textContent || node.innerText );
263             }
264
265             editor.on('dragstart', function () {
266                 let node = editor.selection.getNode();
267
268                 if (node.nodeName !== 'IMG') return;
269                 wrap = editor.dom.getParent(node, '.mceTemp');
270
271                 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
272                     wrap = node.parentNode;
273                 }
274             });
275
276             editor.on('drop', function (event) {
277                 let dom = editor.dom,
278                     rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
279
280                 // Don't allow anything to be dropped in a captioned image.
281                 if (dom.getParent(rng.startContainer, '.mceTemp')) {
282                     event.preventDefault();
283                 } else if (wrap) {
284                     event.preventDefault();
285
286                     editor.undoManager.transact(function () {
287                         editor.selection.setRng(rng);
288                         editor.selection.setNode(wrap);
289                         dom.remove(wrap);
290                     });
291                 }
292
293                 wrap = null;
294             });
295
296             // Custom Image picker button
297             editor.addButton('image-insert', {
298                 title: 'My title',
299                 icon: 'image',
300                 tooltip: 'Insert an image',
301                 onclick: function () {
302                     window.ImageManager.showExternal(function (image) {
303                         let html = `<a href="${image.url}" target="_blank">`;
304                         html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
305                         html += '</a>';
306                         editor.execCommand('mceInsertContent', false, html);
307                     });
308                 }
309             });
310
311             // Paste image-uploads
312             editor.on('paste', function(event) {
313                 editorPaste(event, editor);
314             });
315         }
316     };
317     return settings;
318 };