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