| 1 | /*global tinymce:true */ |
| 2 | |
| 3 | tinymce.PluginManager.add('wpcode', function(editor) { |
| 4 | function showDialog() { |
| 5 | var e = tinymce.activeEditor.selection.getNode(); |
| 6 | if ( e.nodeName == 'CODE' ) { |
| 7 | editor.execCommand('mceRemoveNode', false, editor.dom.getParent(e, 'CODE')); |
| 8 | editor.nodeChanged(); |
| 9 | } else if (editor.selection.isCollapsed() || e.nodeName == 'PRE') { |
| 10 | tinymce.activeEditor.selection.select(editor.dom.getParent(e, 'PRE')); |
| 11 | editor.windowManager.open({ |
| 12 | title: "Source code", |
| 13 | body: { |
| 14 | type: 'textbox', |
| 15 | name: 'wpcode', |
| 16 | multiline: true, |
| 17 | minWidth: editor.getParam("code_dialog_width", 600), |
| 18 | minHeight: editor.getParam("code_dialog_height", Math.min(tinymce.DOM.getViewPort().h - 200, 500)), |
| 19 | value: tinymce.activeEditor.selection.getContent({format: 'text'}), |
| 20 | spellcheck: false, |
| 21 | style: 'direction: ltr; text-align: left' |
| 22 | }, |
| 23 | onSubmit: function(e) { |
| 24 | // We get a lovely "Wrong document" error in IE 11 if we |
| 25 | // don't move the focus to the editor before creating an undo |
| 26 | // transation since it tries to make a bookmark for the current selection |
| 27 | editor.focus(); |
| 28 | |
| 29 | editor.undoManager.transact(function() { |
| 30 | editor.insertContent('<pre>' + escapeHtml(e.data.wpcode) + '</pre>'); |
| 31 | }); |
| 32 | |
| 33 | editor.selection.setCursorLocation(); |
| 34 | editor.nodeChanged(); |
| 35 | } |
| 36 | }); |
| 37 | } else { |
| 38 | editor.undoManager.transact(function() { |
| 39 | tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create( |
| 40 | 'code', |
| 41 | {}, |
| 42 | editor.selection.getContent() |
| 43 | )); |
| 44 | }); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | function escapeHtml(str) { |
| 49 | var div = document.createElement('div'); |
| 50 | div.appendChild(document.createTextNode(str)); |
| 51 | return div.innerHTML; |
| 52 | }; |
| 53 | |
| 54 | editor.addCommand("mceCodeEditor", showDialog); |
| 55 | |
| 56 | editor.addButton('wpcode', { |
| 57 | icon: 'code', |
| 58 | tooltip: 'Source code', |
| 59 | onclick: showDialog, |
| 60 | onPostRender: function(){ |
| 61 | var ctrl = this; |
| 62 | editor.on("NodeChange", function(e) { |
| 63 | ctrl.active(e.element.nodeName == 'CODE' || e.element.nodeName == 'PRE'); |
| 64 | }); |
| 65 | } |
| 66 | }); |
| 67 | |
| 68 | editor.addMenuItem('wpcode', { |
| 69 | icon: 'code', |
| 70 | text: 'Source code', |
| 71 | context: 'tools', |
| 72 | onclick: showDialog |
| 73 | }); |
| 74 | }); |
| 75 | |