2 const Code = require('../code');
5 * Handle pasting images from clipboard.
6 * @param {ClipboardEvent} event
9 function editorPaste(event, editor) {
10 if (!event.clipboardData || !event.clipboardData.items) return;
11 let items = event.clipboardData.items;
13 for (let i = 0; i < items.length; i++) {
14 if (items[i].type.indexOf("image") === -1) continue;
15 event.preventDefault();
17 let id = "image-" + Math.random().toString(16).slice(2);
18 let loadingImage = window.baseUrl('/loading.gif');
19 let file = items[i].getAsFile();
21 editor.insertContent(`<p><img src="${loadingImage}" id="${id}"></p>`);
22 uploadImageFile(file).then(resp => {
23 editor.dom.setAttrib(id, 'src', resp.thumbs.display);
25 editor.dom.remove(id);
26 window.$events.emit('error', trans('errors.image_upload_error'));
34 * Upload an image file to the server
37 function uploadImageFile(file) {
38 if (file === null || file.type.indexOf('image') !== 0) return Promise.reject(`Not an image file`);
42 let fileNameMatches = file.name.match(/\.(.+)$/);
43 if (fileNameMatches.length > 1) ext = fileNameMatches[1];
46 let remoteFilename = "image-" + Date.now() + "." + ext;
47 let formData = new FormData();
48 formData.append('file', file, remoteFilename);
50 return window.$http.post('/images/gallery/upload', formData).then(resp => (resp.data));
53 function registerEditorShortcuts(editor) {
55 for (let i = 1; i < 5; i++) {
56 editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
59 // Other block shortcuts
60 editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
61 editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
62 editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
63 editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
64 editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
65 editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
66 editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
67 editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
69 // Save draft shortcut
70 editor.shortcuts.add('meta+S', '', () => {
71 window.$events.emit('editor-save-draft');
75 editor.shortcuts.add('meta+13', '', () => {
76 window.$events.emit('editor-save-page');
79 // Loop through callout styles
80 editor.shortcuts.add('meta+9', '', function() {
81 let selectedNode = editor.selection.getNode();
82 let formats = ['info', 'success', 'warning', 'danger'];
84 if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
85 editor.formatter.apply('calloutinfo');
89 for (let i = 0; i < formats.length; i++) {
90 if (selectedNode.className.indexOf(formats[i]) === -1) continue;
91 let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
92 editor.formatter.apply('callout' + newFormat);
95 editor.formatter.apply('p');
101 * Load custom HTML head content from the settings into the editor.
104 function loadCustomHeadContent(editor) {
105 window.$http.get(window.baseUrl('/custom-head-content')).then(resp => {
106 if (!resp.data) return;
107 let head = editor.getDoc().querySelector('head');
108 head.innerHTML += resp.data;
113 * Create and enable our custom code plugin
115 function codePlugin() {
117 function elemIsCodeBlock(elem) {
118 return elem.className === 'CodeMirrorContainer';
121 function showPopup(editor) {
122 let selectedNode = editor.selection.getNode();
124 if (!elemIsCodeBlock(selectedNode)) {
125 let providedCode = editor.selection.getNode().textContent;
126 window.vues['code-editor'].open(providedCode, '', (code, lang) => {
127 let wrap = document.createElement('div');
128 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
129 wrap.querySelector('code').innerText = code;
131 editor.formatter.toggle('pre');
132 let node = editor.selection.getNode();
133 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
134 editor.fire('SetContent');
139 let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
140 let currentCode = selectedNode.querySelector('textarea').textContent;
142 window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
143 let editorElem = selectedNode.querySelector('.CodeMirror');
144 let cmInstance = editorElem.CodeMirror;
146 Code.setContent(cmInstance, code);
147 Code.setMode(cmInstance, lang);
149 let textArea = selectedNode.querySelector('textarea');
150 if (textArea) textArea.textContent = code;
151 selectedNode.setAttribute('data-lang', lang);
155 function codeMirrorContainerToPre($codeMirrorContainer) {
156 let textArea = $codeMirrorContainer[0].querySelector('textarea');
157 let code = textArea.textContent;
158 let lang = $codeMirrorContainer[0].getAttribute('data-lang');
160 $codeMirrorContainer.removeAttr('contentEditable');
161 let $pre = $('<pre></pre>');
162 $pre.append($('<code></code>').each((index, elem) => {
163 // Needs to be textContent since innerText produces BR:s
164 elem.textContent = code;
165 }).attr('class', `language-${lang}`));
166 $codeMirrorContainer.replaceWith($pre);
169 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
173 editor.addButton('codeeditor', {
179 editor.addCommand('codeeditor', () => {
184 editor.on('PreProcess', function (e) {
185 $('div.CodeMirrorContainer', e.node).
186 each((index, elem) => {
188 codeMirrorContainerToPre($elem);
192 editor.on('dblclick', event => {
193 let selectedNode = editor.selection.getNode();
194 if (!elemIsCodeBlock(selectedNode)) return;
198 editor.on('SetContent', function () {
200 // Recover broken codemirror instances
201 $('.CodeMirrorContainer').filter((index ,elem) => {
202 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
203 }).each((index, elem) => {
204 codeMirrorContainerToPre($(elem));
207 let codeSamples = $('body > pre').filter((index, elem) => {
208 return elem.contentEditable !== "false";
211 if (!codeSamples.length) return;
212 editor.undoManager.transact(function () {
213 codeSamples.each((index, elem) => {
214 Code.wysiwygView(elem);
223 window.tinymce.PluginManager.add('customhr', function (editor) {
224 editor.addCommand('InsertHorizontalRule', function () {
225 let hrElem = document.createElement('hr');
226 let cNode = editor.selection.getNode();
227 let parentNode = cNode.parentNode;
228 parentNode.insertBefore(hrElem, cNode);
231 editor.addButton('hr', {
233 tooltip: 'Horizontal line',
234 cmd: 'InsertHorizontalRule'
237 editor.addMenuItem('hr', {
239 text: 'Horizontal line',
240 cmd: 'InsertHorizontalRule',
248 selector: '#html-editor',
250 window.baseUrl('/css/styles.css'),
251 window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
254 body_class: 'page-content',
255 browser_spellcheck: true,
256 relative_urls: false,
257 remove_script_host: false,
258 document_base_url: window.baseUrl('/'),
261 paste_data_images: false,
262 extended_valid_elements: 'pre[*]',
263 automatic_uploads: false,
264 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre]",
265 plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor",
266 imagetools_toolbar: 'imageoptions',
267 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",
268 content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
270 {title: "Header Large", format: "h2"},
271 {title: "Header Medium", format: "h3"},
272 {title: "Header Small", format: "h4"},
273 {title: "Header Tiny", format: "h5"},
274 {title: "Paragraph", format: "p", exact: true, classes: ''},
275 {title: "Blockquote", format: "blockquote"},
276 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
277 {title: "Inline Code", icon: "code", inline: "code"},
278 {title: "Callouts", items: [
279 {title: "Info", format: 'calloutinfo'},
280 {title: "Success", format: 'calloutsuccess'},
281 {title: "Warning", format: 'calloutwarning'},
282 {title: "Danger", format: 'calloutdanger'}
285 style_formats_merge: false,
287 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
288 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
289 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
290 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
291 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
292 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
293 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
294 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
296 file_browser_callback: function (field_name, url, type, win) {
298 if (type === 'file') {
299 window.EntitySelectorPopup.show(function(entity) {
300 let originalField = win.document.getElementById(field_name);
301 originalField.value = entity.link;
302 $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
306 if (type === 'image') {
307 // Show image manager
308 window.ImageManager.show(function (image) {
310 // Set popover link input to image url then fire change event
311 // to ensure the new value sticks
312 win.document.getElementById(field_name).value = image.url;
313 if ("createEvent" in document) {
314 let evt = document.createEvent("HTMLEvents");
315 evt.initEvent("change", false, true);
316 win.document.getElementById(field_name).dispatchEvent(evt);
318 win.document.getElementById(field_name).fireEvent("onchange");
321 // Replace the actively selected content with the linked image
322 let html = `<a href="${image.url}" target="_blank">`;
323 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
325 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
330 paste_preprocess: function (plugin, args) {
331 let content = args.content;
332 if (content.indexOf('<img src="file://') !== -1) {
336 init_instance_callback: function(editor) {
337 loadCustomHeadContent(editor);
339 setup: function (editor) {
341 editor.on('init ExecCommand change input NodeChange ObjectResized', editorChange);
343 function editorChange() {
344 let content = editor.getContent();
345 window.$events.emit('editor-html-change', content);
348 window.$events.listen('editor-html-update', html => {
349 editor.setContent(html);
350 editor.selection.select(editor.getBody(), true);
351 editor.selection.collapse(false);
355 registerEditorShortcuts(editor);
359 function hasTextContent(node) {
360 return node && !!( node.textContent || node.innerText );
363 editor.on('dragstart', function () {
364 let node = editor.selection.getNode();
366 if (node.nodeName !== 'IMG') return;
367 wrap = editor.dom.getParent(node, '.mceTemp');
369 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
370 wrap = node.parentNode;
374 editor.on('drop', function (event) {
375 let dom = editor.dom,
376 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
378 // Don't allow anything to be dropped in a captioned image.
379 if (dom.getParent(rng.startContainer, '.mceTemp')) {
380 event.preventDefault();
382 event.preventDefault();
384 editor.undoManager.transact(function () {
385 editor.selection.setRng(rng);
386 editor.selection.setNode(wrap);
394 // Custom Image picker button
395 editor.addButton('image-insert', {
398 tooltip: 'Insert an image',
399 onclick: function () {
400 window.ImageManager.show(function (image) {
401 let html = `<a href="${image.url}" target="_blank">`;
402 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
404 editor.execCommand('mceInsertContent', false, html);
409 // Paste image-uploads
410 editor.on('paste', event => { editorPaste(event, editor) });