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