]> BookStack Code Mirror - bookstack/blob - resources/assets/js/pages/page-form.js
Fixed image tests after amends to url system
[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 var mceOptions = module.exports = {
64     selector: '#html-editor',
65     content_css: [
66         window.baseUrl('/css/styles.css'),
67         window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
68     ],
69     body_class: 'page-content',
70     relative_urls: false,
71     remove_script_host: false,
72     document_base_url: window.baseUrl('/'),
73     statusbar: false,
74     menubar: false,
75     paste_data_images: false,
76     extended_valid_elements: 'pre[*]',
77     automatic_uploads: false,
78     valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]",
79     plugins: "image table textcolor paste link fullscreen imagetools code customhr autosave lists",
80     imagetools_toolbar: 'imageoptions',
81     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",
82     content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
83     style_formats: [
84         {title: "Header 1", format: "h1"},
85         {title: "Header 2", format: "h2"},
86         {title: "Header 3", format: "h3"},
87         {title: "Paragraph", format: "p", exact: true, classes: ''},
88         {title: "Blockquote", format: "blockquote"},
89         {title: "Code Block", icon: "code", format: "pre"},
90         {title: "Inline Code", icon: "code", inline: "code"},
91         {title: "Callouts", items: [
92             {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}},
93             {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}},
94             {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}},
95             {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}}
96         ]}
97     ],
98     style_formats_merge: false,
99     formats: {
100         alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
101         aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
102         alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
103     },
104     file_browser_callback: function (field_name, url, type, win) {
105
106         if (type === 'file') {
107             window.showEntityLinkSelector(function(entity) {
108                 let originalField = win.document.getElementById(field_name);
109                 originalField.value = entity.link;
110                 $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
111             });
112         }
113
114         if (type === 'image') {
115             // Show image manager
116             window.ImageManager.showExternal(function (image) {
117
118                 // Set popover link input to image url then fire change event
119                 // to ensure the new value sticks
120                 win.document.getElementById(field_name).value = image.url;
121                 if ("createEvent" in document) {
122                     let evt = document.createEvent("HTMLEvents");
123                     evt.initEvent("change", false, true);
124                     win.document.getElementById(field_name).dispatchEvent(evt);
125                 } else {
126                     win.document.getElementById(field_name).fireEvent("onchange");
127                 }
128
129                 // Replace the actively selected content with the linked image
130                 let html = `<a href="${image.url}" target="_blank">`;
131                 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
132                 html += '</a>';
133                 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
134             });
135         }
136
137     },
138     paste_preprocess: function (plugin, args) {
139         let content = args.content;
140         if (content.indexOf('<img src="file://') !== -1) {
141             args.content = '';
142         }
143     },
144     extraSetups: [],
145     setup: function (editor) {
146
147         // Run additional setup actions
148         // Used by the angular side of things
149         for (let i = 0; i < mceOptions.extraSetups.length; i++) {
150             mceOptions.extraSetups[i](editor);
151         }
152
153         registerEditorShortcuts(editor);
154
155         (function () {
156             var wrap;
157
158             function hasTextContent(node) {
159                 return node && !!( node.textContent || node.innerText );
160             }
161
162             editor.on('dragstart', function () {
163                 var node = editor.selection.getNode();
164
165                 if (node.nodeName !== 'IMG') return;
166                 wrap = editor.dom.getParent(node, '.mceTemp');
167
168                 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
169                     wrap = node.parentNode;
170                 }
171             });
172
173             editor.on('drop', function (event) {
174                 var dom = editor.dom,
175                     rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
176
177                 // Don't allow anything to be dropped in a captioned image.
178                 if (dom.getParent(rng.startContainer, '.mceTemp')) {
179                     event.preventDefault();
180                 } else if (wrap) {
181                     event.preventDefault();
182
183                     editor.undoManager.transact(function () {
184                         editor.selection.setRng(rng);
185                         editor.selection.setNode(wrap);
186                         dom.remove(wrap);
187                     });
188                 }
189
190                 wrap = null;
191             });
192         })();
193
194         // Custom Image picker button
195         editor.addButton('image-insert', {
196             title: 'My title',
197             icon: 'image',
198             tooltip: 'Insert an image',
199             onclick: function () {
200                 window.ImageManager.showExternal(function (image) {
201                     let html = `<a href="${image.url}" target="_blank">`;
202                     html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
203                     html += '</a>';
204                     editor.execCommand('mceInsertContent', false, html);
205                 });
206             }
207         });
208
209         // Paste image-uploads
210         editor.on('paste', function(event) {
211             editorPaste(event, editor);
212         });
213     }
214 };