]> BookStack Code Mirror - bookstack/blob - resources/assets/js/pages/page-form.js
Updated popup design and started integrating link selector
[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         // Show image manager
100         window.ImageManager.showExternal(function (image) {
101
102             // Set popover link input to image url then fire change event
103             // to ensure the new value sticks
104             win.document.getElementById(field_name).value = image.url;
105             if ("createEvent" in document) {
106                 var evt = document.createEvent("HTMLEvents");
107                 evt.initEvent("change", false, true);
108                 win.document.getElementById(field_name).dispatchEvent(evt);
109             } else {
110                 win.document.getElementById(field_name).fireEvent("onchange");
111             }
112
113             // Replace the actively selected content with the linked image
114             var html = '<a href="' + image.url + '" target="_blank">';
115             html += '<img src="' + image.thumbs.display + '" alt="' + image.name + '">';
116             html += '</a>';
117             win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
118         });
119     },
120     paste_preprocess: function (plugin, args) {
121         var content = args.content;
122         if (content.indexOf('<img src="file://') !== -1) {
123             args.content = '';
124         }
125     },
126     extraSetups: [],
127     setup: function (editor) {
128
129         // Run additional setup actions
130         // Used by the angular side of things
131         for (var i = 0; i < mceOptions.extraSetups.length; i++) {
132             mceOptions.extraSetups[i](editor);
133         }
134
135         registerEditorShortcuts(editor);
136
137         (function () {
138             var wrap;
139
140             function hasTextContent(node) {
141                 return node && !!( node.textContent || node.innerText );
142             }
143
144             editor.on('dragstart', function () {
145                 var node = editor.selection.getNode();
146
147                 if (node.nodeName === 'IMG') {
148                     wrap = editor.dom.getParent(node, '.mceTemp');
149
150                     if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
151                         wrap = node.parentNode;
152                     }
153                 }
154             });
155
156             editor.on('drop', function (event) {
157                 var dom = editor.dom,
158                     rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
159
160                 // Don't allow anything to be dropped in a captioned image.
161                 if (dom.getParent(rng.startContainer, '.mceTemp')) {
162                     event.preventDefault();
163                 } else if (wrap) {
164                     event.preventDefault();
165
166                     editor.undoManager.transact(function () {
167                         editor.selection.setRng(rng);
168                         editor.selection.setNode(wrap);
169                         dom.remove(wrap);
170                     });
171                 }
172
173                 wrap = null;
174             });
175         })();
176
177         // Image picker button
178         editor.addButton('image-insert', {
179             title: 'My title',
180             icon: 'image',
181             tooltip: 'Insert an image',
182             onclick: function () {
183                 window.ImageManager.showExternal(function (image) {
184                     var html = '<a href="' + image.url + '" target="_blank">';
185                     html += '<img src="' + image.thumbs.display + '" alt="' + image.name + '">';
186                     html += '</a>';
187                     editor.execCommand('mceInsertContent', false, html);
188                 });
189             }
190         });
191
192         // Paste image-uploads
193         editor.on('paste', editorPaste);
194     }
195 };