]> BookStack Code Mirror - bookstack/blob - resources/assets/js/pages/page-form.js
Merge pull request #3 from OsmosysSoftware/revert-1-issue-181
[bookstack] / resources / assets / js / pages / page-form.js
1 "use strict";
2
3 /**
4  * Handle pasting images from clipboard.
5  * @param e  - event
6  * @param editor - editor instance
7  */
8 function editorPaste(e, editor) {
9     if (!e.clipboardData) return;
10     let items = e.clipboardData.items;
11     if (!items) return;
12     for (let i = 0; i < items.length; i++) {
13         if (items[i].type.indexOf("image") === -1) return;
14
15         let file = items[i].getAsFile();
16         let formData = new FormData();
17         let ext = 'png';
18         let xhr = new XMLHttpRequest();
19
20         if (file.name) {
21             let fileNameMatches = file.name.match(/\.(.+)$/);
22             if (fileNameMatches) {
23                 ext = fileNameMatches[1];
24             }
25         }
26
27         let id = "image-" + Math.random().toString(16).slice(2);
28         let loadingImage = window.baseUrl('/loading.gif');
29         editor.execCommand('mceInsertContent', false, `<img src="${loadingImage}" id="${id}">`);
30
31         let remoteFilename = "image-" + Date.now() + "." + ext;
32         formData.append('file', file, remoteFilename);
33         formData.append('_token', document.querySelector('meta[name="token"]').getAttribute('content'));
34
35         xhr.open('POST', window.baseUrl('/images/gallery/upload'));
36         xhr.onload = function () {
37             if (xhr.status === 200 || xhr.status === 201) {
38                 let result = JSON.parse(xhr.responseText);
39                 editor.dom.setAttrib(id, 'src', result.thumbs.display);
40             } else {
41                 console.log('An error occurred uploading the image', xhr.responseText);
42                 editor.dom.remove(id);
43             }
44         };
45         xhr.send(formData);
46         
47     }
48 }
49
50 function registerEditorShortcuts(editor) {
51     // Headers
52     for (let i = 1; i < 5; i++) {
53         editor.addShortcut('meta+' + i, '', ['FormatBlock', false, 'h' + i]);
54     }
55
56     // Other block shortcuts
57     editor.addShortcut('meta+q', '', ['FormatBlock', false, 'blockquote']);
58     editor.addShortcut('meta+d', '', ['FormatBlock', false, 'p']);
59     editor.addShortcut('meta+e', '', ['FormatBlock', false, 'pre']);
60     editor.addShortcut('meta+shift+E', '', ['FormatBlock', false, 'code']);
61 }
62
63 module.exports = function() {
64     let settings = {
65         selector: '#html-editor',
66         content_css: [
67             window.baseUrl('/css/styles.css'),
68             window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
69         ],
70         body_class: 'page-content',
71         browser_spellcheck: true,
72         relative_urls: false,
73         remove_script_host: false,
74         document_base_url: window.baseUrl('/'),
75         statusbar: false,
76         menubar: false,
77         paste_data_images: false,
78         extended_valid_elements: 'pre[*]',
79         automatic_uploads: false,
80         valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]",
81         plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codesample",
82         imagetools_toolbar: 'imageoptions',
83         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 codesample",
84         content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
85         style_formats: [
86             {title: "Header Large", format: "h2"},
87             {title: "Header Medium", format: "h3"},
88             {title: "Header Small", format: "h4"},
89             {title: "Header Tiny", format: "h5"},
90             {title: "Paragraph", format: "p", exact: true, classes: ''},
91             {title: "Blockquote", format: "blockquote"},
92             {title: "Code Block", icon: "code", format: "pre"},
93             {title: "Inline Code", icon: "code", inline: "code"},
94             {title: "Callouts", items: [
95                 {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}},
96                 {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}},
97                 {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}},
98                 {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}}
99             ]}
100         ],
101         style_formats_merge: false,
102         formats: {
103             alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
104             aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
105             alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
106         },
107         file_browser_callback: function (field_name, url, type, win) {
108
109             if (type === 'file') {
110                 window.showEntityLinkSelector(function(entity) {
111                     let originalField = win.document.getElementById(field_name);
112                     originalField.value = entity.link;
113                     $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
114                 });
115             }
116
117             if (type === 'image') {
118                 // Show image manager
119                 window.ImageManager.showExternal(function (image) {
120
121                     // Set popover link input to image url then fire change event
122                     // to ensure the new value sticks
123                     win.document.getElementById(field_name).value = image.url;
124                     if ("createEvent" in document) {
125                         let evt = document.createEvent("HTMLEvents");
126                         evt.initEvent("change", false, true);
127                         win.document.getElementById(field_name).dispatchEvent(evt);
128                     } else {
129                         win.document.getElementById(field_name).fireEvent("onchange");
130                     }
131
132                     // Replace the actively selected content with the linked image
133                     let html = `<a href="${image.url}" target="_blank">`;
134                     html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
135                     html += '</a>';
136                     win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
137                 });
138             }
139
140         },
141         paste_preprocess: function (plugin, args) {
142             let content = args.content;
143             if (content.indexOf('<img src="file://') !== -1) {
144                 args.content = '';
145             }
146         },
147         extraSetups: [],
148         setup: function (editor) {
149
150             // Run additional setup actions
151             // Used by the angular side of things
152             for (let i = 0; i < settings.extraSetups.length; i++) {
153                 settings.extraSetups[i](editor);
154             }
155
156             registerEditorShortcuts(editor);
157
158             let wrap;
159
160             function hasTextContent(node) {
161                 return node && !!( node.textContent || node.innerText );
162             }
163
164             editor.on('dragstart', function () {
165                 let node = editor.selection.getNode();
166
167                 if (node.nodeName !== 'IMG') return;
168                 wrap = editor.dom.getParent(node, '.mceTemp');
169
170                 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
171                     wrap = node.parentNode;
172                 }
173             });
174
175             editor.on('drop', function (event) {
176                 let dom = editor.dom,
177                     rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
178
179                 // Don't allow anything to be dropped in a captioned image.
180                 if (dom.getParent(rng.startContainer, '.mceTemp')) {
181                     event.preventDefault();
182                 } else if (wrap) {
183                     event.preventDefault();
184
185                     editor.undoManager.transact(function () {
186                         editor.selection.setRng(rng);
187                         editor.selection.setNode(wrap);
188                         dom.remove(wrap);
189                     });
190                 }
191
192                 wrap = null;
193             });
194
195             // Custom Image picker button
196             editor.addButton('image-insert', {
197                 title: 'My title',
198                 icon: 'image',
199                 tooltip: 'Insert an image',
200                 onclick: function () {
201                     window.ImageManager.showExternal(function (image) {
202                         let html = `<a href="${image.url}" target="_blank">`;
203                         html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
204                         html += '</a>';
205                         editor.execCommand('mceInsertContent', false, html);
206                     });
207                 }
208             });
209
210             // Paste image-uploads
211             editor.on('paste', function(event) {
212                 editorPaste(event, editor);
213             });
214         }
215     };
216     return settings;
217 };