]> BookStack Code Mirror - bookstack/blob - resources/assets/js/pages/page-form.js
Started tinymce code editor components
[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', '', ['FormatBlock', false, 'pre']);
62     editor.addShortcut('meta+shift+E', '', ['FormatBlock', false, 'code']);
63 }
64
65
66 function codePlugin() {
67
68     function elemIsCodeBlock(elem) {
69         return elem.className === 'CodeMirrorContainer';
70     }
71
72     function showPopup(editor) {
73         let selectedNode = editor.selection.getNode();
74         if (!elemIsCodeBlock(selectedNode)) {
75             return;
76         }
77
78         let lang = selectedNode.hasAttribute('data-language') ? selectedNode.getAttribute('data-language') : '';
79         let currentCode = selectedNode.querySelector('textarea').textContent;
80         console.log('SHOW POPUP');
81         // TODO - Show custom editor
82     }
83
84     window.tinymce.PluginManager.add('codeeditor', (editor, url) => {
85
86         let $ = editor.$;
87
88         editor.addButton('codeeditor', {
89             text: 'Code block',
90             icon: false,
91             onclick() {
92                 showPopup(editor);
93             }
94         });
95
96         // Convert
97         editor.on('PreProcess', function (e) {
98             $('div.CodeMirrorContainer', e.node).
99             each((index, elem) => {
100                 let $elem = $(elem);
101                 let code = elem.querySelector('textarea').textContent;
102
103                 // $elem.attr('class', $.trim($elem.attr('class')));
104                 $elem.removeAttr('contentEditable');
105
106                 $elem.empty().append('<pre></pre>').find('pre').first().append($('<code></code>').each((index, elem) => {
107                     // Needs to be textContent since innerText produces BR:s
108                     elem.textContent = code;
109                 }).attr('class', $elem.attr('class')));
110                 console.log($elem[0].outerHTML);
111             });
112         });
113
114         editor.on('SetContent', function () {
115             let codeSamples = $('pre').filter((index, elem) => {
116                 return elem.contentEditable !== "false";
117             });
118
119             if (codeSamples.length) {
120                 editor.undoManager.transact(function () {
121                     codeSamples.each((index, elem) => {
122                         console.log(elem.textContent);
123                         let outerWrap = Code.wysiwygView(elem);
124                         outerWrap.addEventListener('dblclick', () => {
125                             showPopup(editor);
126                         })
127                     });
128                 });
129             }
130         });
131
132     });
133 }
134
135 module.exports = function() {
136     codePlugin();
137     let settings = {
138         selector: '#html-editor',
139         content_css: [
140             window.baseUrl('/css/styles.css'),
141             window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
142         ],
143         branding: false,
144         body_class: 'page-content',
145         browser_spellcheck: true,
146         relative_urls: false,
147         remove_script_host: false,
148         document_base_url: window.baseUrl('/'),
149         statusbar: false,
150         menubar: false,
151         paste_data_images: false,
152         extended_valid_elements: 'pre[*]',
153         automatic_uploads: false,
154         valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]",
155         plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor",
156         imagetools_toolbar: 'imageoptions',
157         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 codeeditor",
158         content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
159         style_formats: [
160             {title: "Header Large", format: "h2"},
161             {title: "Header Medium", format: "h3"},
162             {title: "Header Small", format: "h4"},
163             {title: "Header Tiny", format: "h5"},
164             {title: "Paragraph", format: "p", exact: true, classes: ''},
165             {title: "Blockquote", format: "blockquote"},
166             {title: "Code Block", icon: "code", format: "pre"},
167             {title: "Inline Code", icon: "code", inline: "code"},
168             {title: "Callouts", items: [
169                 {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}},
170                 {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}},
171                 {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}},
172                 {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}}
173             ]}
174         ],
175         style_formats_merge: false,
176         formats: {
177             alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
178             aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
179             alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
180         },
181         file_browser_callback: function (field_name, url, type, win) {
182
183             if (type === 'file') {
184                 window.showEntityLinkSelector(function(entity) {
185                     let originalField = win.document.getElementById(field_name);
186                     originalField.value = entity.link;
187                     $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
188                 });
189             }
190
191             if (type === 'image') {
192                 // Show image manager
193                 window.ImageManager.showExternal(function (image) {
194
195                     // Set popover link input to image url then fire change event
196                     // to ensure the new value sticks
197                     win.document.getElementById(field_name).value = image.url;
198                     if ("createEvent" in document) {
199                         let evt = document.createEvent("HTMLEvents");
200                         evt.initEvent("change", false, true);
201                         win.document.getElementById(field_name).dispatchEvent(evt);
202                     } else {
203                         win.document.getElementById(field_name).fireEvent("onchange");
204                     }
205
206                     // Replace the actively selected content with the linked image
207                     let html = `<a href="${image.url}" target="_blank">`;
208                     html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
209                     html += '</a>';
210                     win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
211                 });
212             }
213
214         },
215         paste_preprocess: function (plugin, args) {
216             let content = args.content;
217             if (content.indexOf('<img src="file://') !== -1) {
218                 args.content = '';
219             }
220         },
221         extraSetups: [],
222         setup: function (editor) {
223
224             // Run additional setup actions
225             // Used by the angular side of things
226             for (let i = 0; i < settings.extraSetups.length; i++) {
227                 settings.extraSetups[i](editor);
228             }
229
230             registerEditorShortcuts(editor);
231
232             let wrap;
233
234             function hasTextContent(node) {
235                 return node && !!( node.textContent || node.innerText );
236             }
237
238             editor.on('dragstart', function () {
239                 let node = editor.selection.getNode();
240
241                 if (node.nodeName !== 'IMG') return;
242                 wrap = editor.dom.getParent(node, '.mceTemp');
243
244                 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
245                     wrap = node.parentNode;
246                 }
247             });
248
249             editor.on('drop', function (event) {
250                 let dom = editor.dom,
251                     rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
252
253                 // Don't allow anything to be dropped in a captioned image.
254                 if (dom.getParent(rng.startContainer, '.mceTemp')) {
255                     event.preventDefault();
256                 } else if (wrap) {
257                     event.preventDefault();
258
259                     editor.undoManager.transact(function () {
260                         editor.selection.setRng(rng);
261                         editor.selection.setNode(wrap);
262                         dom.remove(wrap);
263                     });
264                 }
265
266                 wrap = null;
267             });
268
269             // Custom Image picker button
270             editor.addButton('image-insert', {
271                 title: 'My title',
272                 icon: 'image',
273                 tooltip: 'Insert an image',
274                 onclick: function () {
275                     window.ImageManager.showExternal(function (image) {
276                         let html = `<a href="${image.url}" target="_blank">`;
277                         html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
278                         html += '</a>';
279                         editor.execCommand('mceInsertContent', false, html);
280                     });
281                 }
282             });
283
284             // Paste image-uploads
285             editor.on('paste', function(event) {
286                 editorPaste(event, editor);
287             });
288         }
289     };
290     return settings;
291 };