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.addShortcut('meta+' + i, '', ['FormatBlock', false, 'h' + i]);
58 // Other block shortcuts
59 editor.addShortcut('meta+q', '', ['FormatBlock', false, 'blockquote']);
60 editor.addShortcut('meta+d', '', ['FormatBlock', false, 'p']);
61 editor.addShortcut('meta+e', '', ['codeeditor', false, 'pre']);
62 editor.addShortcut('meta+shift+E', '', ['FormatBlock', false, 'code']);
67 * Create and enable our custom code plugin
69 function codePlugin() {
71 function elemIsCodeBlock(elem) {
72 return elem.className === 'CodeMirrorContainer';
75 function showPopup(editor) {
76 let selectedNode = editor.selection.getNode();
78 if (!elemIsCodeBlock(selectedNode)) {
79 let providedCode = editor.selection.getNode().textContent;
80 window.vues['code-editor'].open(providedCode, '', (code, lang) => {
81 let wrap = document.createElement('div');
82 wrap.innerHTML = `<pre><code class="language-${lang}"></code></pre>`;
83 wrap.querySelector('code').innerText = code;
84 editor.formatter.toggle('pre');
85 let node = editor.selection.getNode();
86 editor.dom.setHTML(node, wrap.querySelector('pre').innerHTML);
87 editor.fire('SetContent');
92 let lang = selectedNode.hasAttribute('data-lang') ? selectedNode.getAttribute('data-lang') : '';
93 let currentCode = selectedNode.querySelector('textarea').textContent;
95 window.vues['code-editor'].open(currentCode, lang, (code, lang) => {
96 let editorElem = selectedNode.querySelector('.CodeMirror');
97 let cmInstance = editorElem.CodeMirror;
99 Code.setContent(cmInstance, code);
100 Code.setMode(cmInstance, lang);
102 let textArea = selectedNode.querySelector('textarea');
103 if (textArea) textArea.textContent = code;
104 selectedNode.setAttribute('data-lang', lang);
108 window.tinymce.PluginManager.add('codeeditor', (editor, url) => {
112 editor.addButton('codeeditor', {
118 editor.addCommand('codeeditor', () => {
123 editor.on('PreProcess', function (e) {
124 $('div.CodeMirrorContainer', e.node).
125 each((index, elem) => {
127 let textArea = elem.querySelector('textarea');
128 let code = textArea.textContent;
129 let lang = elem.getAttribute('data-lang');
131 // $elem.attr('class', $.trim($elem.attr('class')));
132 $elem.removeAttr('contentEditable');
133 let $pre = $('<pre></pre>');
134 $pre.append($('<code></code>').each((index, elem) => {
135 // Needs to be textContent since innerText produces BR:s
136 elem.textContent = code;
137 }).attr('class', `language-${lang}`));
138 $elem.replaceWith($pre);
142 editor.on('SetContent', function () {
143 let codeSamples = $('body > pre').filter((index, elem) => {
144 return elem.contentEditable !== "false";
147 if (codeSamples.length) {
148 editor.undoManager.transact(function () {
149 codeSamples.each((index, elem) => {
150 let editDetails = Code.wysiwygView(elem);
151 editDetails.wrap.addEventListener('dblclick', () => {
152 showPopup(editor, editDetails.wrap, editDetails.editor);
162 module.exports = function() {
165 selector: '#html-editor',
167 window.baseUrl('/css/styles.css'),
168 window.baseUrl('/libs/material-design-iconic-font/css/material-design-iconic-font.min.css')
171 body_class: 'page-content',
172 browser_spellcheck: true,
173 relative_urls: false,
174 remove_script_host: false,
175 document_base_url: window.baseUrl('/'),
178 paste_data_images: false,
179 extended_valid_elements: 'pre[*]',
180 automatic_uploads: false,
181 valid_children: "-div[p|pre|h1|h2|h3|h4|h5|h6|blockquote]",
182 plugins: "image table textcolor paste link autolink fullscreen imagetools code customhr autosave lists codeeditor",
183 imagetools_toolbar: 'imageoptions',
184 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",
185 content_style: "body {padding-left: 15px !important; padding-right: 15px !important; margin:0!important; margin-left:auto!important;margin-right:auto!important;}",
187 {title: "Header Large", format: "h2"},
188 {title: "Header Medium", format: "h3"},
189 {title: "Header Small", format: "h4"},
190 {title: "Header Tiny", format: "h5"},
191 {title: "Paragraph", format: "p", exact: true, classes: ''},
192 {title: "Blockquote", format: "blockquote"},
193 {title: "Code Block", icon: "code", cmd: 'codeeditor'},
194 {title: "Inline Code", icon: "code", inline: "code"},
195 {title: "Callouts", items: [
196 {title: "Success", block: 'p', exact: true, attributes : {'class' : 'callout success'}},
197 {title: "Info", block: 'p', exact: true, attributes : {'class' : 'callout info'}},
198 {title: "Warning", block: 'p', exact: true, attributes : {'class' : 'callout warning'}},
199 {title: "Danger", block: 'p', exact: true, attributes : {'class' : 'callout danger'}}
202 style_formats_merge: false,
204 alignleft: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-left'},
205 aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-center'},
206 alignright: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'align-right'},
208 file_browser_callback: function (field_name, url, type, win) {
210 if (type === 'file') {
211 window.showEntityLinkSelector(function(entity) {
212 let originalField = win.document.getElementById(field_name);
213 originalField.value = entity.link;
214 $(originalField).closest('.mce-form').find('input').eq(2).val(entity.name);
218 if (type === 'image') {
219 // Show image manager
220 window.ImageManager.showExternal(function (image) {
222 // Set popover link input to image url then fire change event
223 // to ensure the new value sticks
224 win.document.getElementById(field_name).value = image.url;
225 if ("createEvent" in document) {
226 let evt = document.createEvent("HTMLEvents");
227 evt.initEvent("change", false, true);
228 win.document.getElementById(field_name).dispatchEvent(evt);
230 win.document.getElementById(field_name).fireEvent("onchange");
233 // Replace the actively selected content with the linked image
234 let html = `<a href="${image.url}" target="_blank">`;
235 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
237 win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, html);
242 paste_preprocess: function (plugin, args) {
243 let content = args.content;
244 if (content.indexOf('<img src="file://') !== -1) {
249 setup: function (editor) {
251 // Run additional setup actions
252 // Used by the angular side of things
253 for (let i = 0; i < settings.extraSetups.length; i++) {
254 settings.extraSetups[i](editor);
257 registerEditorShortcuts(editor);
261 function hasTextContent(node) {
262 return node && !!( node.textContent || node.innerText );
265 editor.on('dragstart', function () {
266 let node = editor.selection.getNode();
268 if (node.nodeName !== 'IMG') return;
269 wrap = editor.dom.getParent(node, '.mceTemp');
271 if (!wrap && node.parentNode.nodeName === 'A' && !hasTextContent(node.parentNode)) {
272 wrap = node.parentNode;
276 editor.on('drop', function (event) {
277 let dom = editor.dom,
278 rng = tinymce.dom.RangeUtils.getCaretRangeFromPoint(event.clientX, event.clientY, editor.getDoc());
280 // Don't allow anything to be dropped in a captioned image.
281 if (dom.getParent(rng.startContainer, '.mceTemp')) {
282 event.preventDefault();
284 event.preventDefault();
286 editor.undoManager.transact(function () {
287 editor.selection.setRng(rng);
288 editor.selection.setNode(wrap);
296 // Custom Image picker button
297 editor.addButton('image-insert', {
300 tooltip: 'Insert an image',
301 onclick: function () {
302 window.ImageManager.showExternal(function (image) {
303 let html = `<a href="${image.url}" target="_blank">`;
304 html += `<img src="${image.thumbs.display}" alt="${image.name}">`;
306 editor.execCommand('mceInsertContent', false, html);
311 // Paste image-uploads
312 editor.on('paste', function(event) {
313 editorPaste(event, editor);