3 const Code = require('../code');
6 * Handle pasting images from clipboard.
8 * @param editor - editor instance
10 function editorPaste(e, editor) {
11 if (!e.clipboardData) return;
12 let items = e.clipboardData.items;
14 for (let i = 0; i < items.length; i++) {
15 if (items[i].type.indexOf("image") === -1) return;
17 let file = items[i].getAsFile();
18 let formData = new FormData();
20 let xhr = new XMLHttpRequest();
23 let fileNameMatches = file.name.match(/\.(.+)$/);
24 if (fileNameMatches) {
25 ext = fileNameMatches[1];
29 let id = "image-" + Math.random().toString(16).slice(2);
30 let loadingImage = window.baseUrl('/loading.gif');
31 editor.execCommand('mceInsertContent', false, `<img src="${loadingImage}" id="${id}">`);
33 let remoteFilename = "image-" + Date.now() + "." + ext;
34 formData.append('file', file, remoteFilename);
35 formData.append('_token', document.querySelector('meta[name="token"]').getAttribute('content'));
37 xhr.open('POST', window.baseUrl('/images/gallery/upload'));
38 xhr.onload = function () {
39 if (xhr.status === 200 || xhr.status === 201) {
40 let result = JSON.parse(xhr.responseText);
41 editor.dom.setAttrib(id, 'src', result.thumbs.display);
43 console.log('An error occurred uploading the image', xhr.responseText);
44 editor.dom.remove(id);
52 function registerEditorShortcuts(editor) {
54 for (let i = 1; i < 5; i++) {
55 editor.shortcuts.add('meta+' + i, '', ['FormatBlock', false, 'h' + (i+1)]);
58 // Other block shortcuts
59 editor.shortcuts.add('meta+5', '', ['FormatBlock', false, 'p']);
60 editor.shortcuts.add('meta+d', '', ['FormatBlock', false, 'p']);
61 editor.shortcuts.add('meta+6', '', ['FormatBlock', false, 'blockquote']);
62 editor.shortcuts.add('meta+q', '', ['FormatBlock', false, 'blockquote']);
63 editor.shortcuts.add('meta+7', '', ['codeeditor', false, 'pre']);
64 editor.shortcuts.add('meta+e', '', ['codeeditor', false, 'pre']);
65 editor.shortcuts.add('meta+8', '', ['FormatBlock', false, 'code']);
66 editor.shortcuts.add('meta+shift+E', '', ['FormatBlock', false, 'code']);
67 // Loop through callout styles
68 editor.shortcuts.add('meta+9', '', function() {
69 let selectedNode = editor.selection.getNode();
70 let formats = ['info', 'success', 'warning', 'danger'];
72 if (!selectedNode || selectedNode.className.indexOf('callout') === -1) {
73 editor.formatter.apply('calloutinfo');
77 for (let i = 0; i < formats.length; i++) {
78 if (selectedNode.className.indexOf(formats[i]) === -1) continue;
79 let newFormat = (i === formats.length -1) ? formats[0] : formats[i+1];
80 editor.formatter.apply('callout' + newFormat);
83 editor.formatter.apply('p');
89 * Create and enable our custom code plugin
91 function codePlugin() {
93 function elemIsCodeBlock(elem) {
94 return elem.className === 'CodeMirrorContainer';
97 function showPopup(editor) {
98 let selectedNode = editor.selection.getNode();
100 if (!elemIsCodeBlock(selectedNode)) {
101 let providedCode = editor.selection.getNode().textContent;
102 window.vues['code-editor'].open(providedCode, '', (code, lang) => {
103 let wrap = document.createElement('div');
104 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
105 wrap.querySelector('code').innerText = code;
107 editor.formatter.toggle('pre');
108 let node = editor.selection.getNode();
109 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
110 editor.fire('SetContent');
115 let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
116 let currentCode = selectedNode.querySelector('textarea').textContent;
118 window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
119 let editorElem = selectedNode.querySelector('.CodeMirror');
120 let cmInstance = editorElem.CodeMirror;
122 Code.setContent(cmInstance, code);
123 Code.setMode(cmInstance, lang);
125 let textArea = selectedNode.querySelector('textarea');
126 if (textArea) textArea.textContent = code;
127 selectedNode.setAttribute('data-lang', lang);
131 function codeMirrorContainerToPre($codeMirrorContainer) {
132 let textArea = $codeMirrorContainer[0].querySelector('textarea');
133 let code = textArea.textContent;
134 let lang = $codeMirrorContainer[0].getAttribute('data-lang');
136 $codeMirrorContainer.removeAttr('contentEditable');
137 let $pre = $('<pre></pre>');
138 $pre.append($('<code></code>').each((index, elem) => {
139 // Needs to be textContent since innerText produces BR:s
140 elem.textContent = code;
141 }).attr('class', `language-${lang}`));
142 $codeMirrorContainer.replaceWith($pre);
145 window.tinymce.PluginManager.add('codeeditor', function(editor, url) {
149 editor.addButton('codeeditor', {
155 editor.addCommand('codeeditor', () => {
160 editor.on('PreProcess', function (e) {
161 $('div.CodeMirrorContainer', e.node).
162 each((index, elem) => {
164 codeMirrorContainerToPre($elem);
168 editor.on('dblclick', event => {
169 let selectedNode = editor.selection.getNode();
170 if (!elemIsCodeBlock(selectedNode)) return;
174 editor.on('SetContent', function () {
176 // Recover broken codemirror instances
177 $('.CodeMirrorContainer').filter((index ,elem) => {
178 return typeof elem.querySelector('.CodeMirror').CodeMirror === 'undefined';
179 }).each((index, elem) => {
180 codeMirrorContainerToPre($(elem));
183 let codeSamples = $('body > pre').filter((index, elem) => {
184 return elem.contentEditable !== "false";
187 if (!codeSamples.length) return;
188 editor.undoManager.transact(function () {
189 codeSamples.each((index, elem) => {
190 Code.wysiwygView(elem);
198 function hrPlugin() {
199 window.tinymce.PluginManager.add('customhr', function (editor) {
200 editor.addCommand('InsertHorizontalRule', function () {
201 let hrElem = document.createElement('hr');
202 let cNode = editor.selection.getNode();
203 let parentNode = cNode.parentNode;
204 parentNode.insertBefore(hrElem, cNode);
207 editor.addButton('hr', {
209 tooltip: 'Horizontal line',
210 cmd: 'InsertHorizontalRule'
213 editor.addMenuItem('hr', {
215 text: 'Horizontal line',
216 cmd: 'InsertHorizontalRule',
222 module.exports = function() {
226 selector: '#html-editor',
228 window.baseUrl('/css/styles.css'),
229 window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
232 body_class: 'page-content',
233 browser_spellcheck: true,
234 relative_urls: false,
235 remove_script_host: false,
236 document_base_url: window.baseUrl('/'),
239 paste_data_images: false,
240 extended_valid_elements: 'pre[*]',
241 automatic_uploads: false,
242 valid_children: "-div[p|h1|h2|h3|h4|h5|h6|blockquote],+div[pre]",
243 plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor",
244 imagetools_toolbar: 'imageoptions',
245 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",
246 content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
248 {title: "Header Large", format: "h2"},
249 {title: "Header Medium", format: "h3"},
250 {title: "Header Small", format: "h4"},
251 {title: "Header Tiny", format: "h5"},
252 {title: "Paragraph", format: "p", exact: true, classes: ''},
253 {title: "Blockquote", format: "blockquote"},
254 {title: "Code Block", icon: "code", cmd: 'codeeditor', format: 'codeeditor'},
255 {title: "Inline Code", icon: "code", inline: "code"},
256 {title: "Callouts", items: [
257 {title: "Info", format: 'calloutinfo'},
258 {title: "Success", format: 'calloutsuccess'},
259 {title: "Warning", format: 'calloutwarning'},
260 {title: "Danger", format: 'calloutdanger'}
263 style_formats_merge: false,
265 codeeditor: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div'},
266 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
267 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
268 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
269 calloutsuccess: {block: 'p', exact: true, attributes: {class: 'callout success'}},
270 calloutinfo: {block: 'p', exact: true, attributes: {class: 'callout info'}},
271 calloutwarning: {block: 'p', exact: true, attributes: {class: 'callout warning'}},
272 calloutdanger: {block: 'p', exact: true, attributes: {class: 'callout danger'}}
274 file_browser_callback: function (field_name, url, type, win) {
276 if (type === 'file') {
277 window.showEntityLinkSelector(function(entity) {
278 let originalField = win.document.getElementById(field_name);
279 originalField.value = entity.link;
280 $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
284 if (type === 'image') {
285 // Show image manager
286 window.ImageManager.show(function (image) {
288 // Set popover link input to image url then fire change event
289 // to ensure the new value sticks
290 win.document.getElementById(field_name).value = image.url;
291 if ("createEvent" in document) {
292 let evt = document.createEvent("HTMLEvents");
293 evt.initEvent("change", false, true);
294 win.document.getElementById(field_name).dispatchEvent(evt);
296 win.document.getElementById(field_name).fireEvent("onchange");
299 // Replace the actively selected content with the linked image
300 let html = `<a href="${image.url}" target="_blank">`;
301 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
303 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
308 paste_preprocess: function (plugin, args) {
309 let content = args.content;
310 if (content.indexOf('<img src="file://') !== -1) {
315 setup: function (editor) {
317 // Run additional setup actions
318 // Used by the angular side of things
319 for (let i = 0; i < settings.extraSetups.length; i++) {
320 settings.extraSetups[i](editor);
323 registerEditorShortcuts(editor);
327 function hasTextContent(node) {
328 return node && !!( node.textContent || node.innerText );
331 editor.on('dragstart', function () {
332 let node = editor.selection.getNode();
334 if (node.nodeName !== 'IMG') return;
335 wrap = editor.dom.getParent(node, '.mceTemp');
337 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
338 wrap = node.parentNode;
342 editor.on('drop', function (event) {
343 let dom = editor.dom,
344 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
346 // Don't allow anything to be dropped in a captioned image.
347 if (dom.getParent(rng.startContainer, '.mceTemp')) {
348 event.preventDefault();
350 event.preventDefault();
352 editor.undoManager.transact(function () {
353 editor.selection.setRng(rng);
354 editor.selection.setNode(wrap);
362 // Custom Image picker button
363 editor.addButton('image-insert', {
366 tooltip: 'Insert an image',
367 onclick: function () {
368 window.ImageManager.show(function (image) {
369 let html = `<a href="${image.url}" target="_blank">`;
370 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
372 editor.execCommand('mceInsertContent', false, html);
377 // Paste image-uploads
378 editor.on('paste', function(event) {
379 editorPaste(event, editor);