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