Advertisement
petruchito

tinymce-rails-imageupload: skip modal dialog [plugin.js]

Mar 2nd, 2015
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.   tinymce.PluginManager.requireLangPack('uploadimage');
  3.  
  4.   tinymce.create('tinymce.plugins.UploadImage', {
  5.     UploadImage: function(ed, url) {
  6.       var form,
  7.           iframe,
  8.           win,
  9.           throbber,
  10.           editor = ed;
  11.  
  12.       function Dialog() {
  13.         if (document.getElementsByName("file")[0].value) {
  14.           insertImage();
  15.         } else ed.windowManager.close;
  16.       }
  17.  
  18.       function showDialog() {
  19.             if(win) {win.close()};
  20.  
  21.         win = editor.windowManager.open({
  22.           title: ed.translate('Insert an image from your computer'),
  23.           width:  500 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
  24.           height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
  25.           body: [
  26.             {type: 'iframe',  url: 'javascript:void(0)', style: 'display: none'},
  27.             {type: 'textbox', name: 'file', label: ed.translate('Choose an image'), subtype: 'file', onchange: Dialog},
  28.             {type: 'textbox', name: 'alt',  label: ed.translate('Image description')},
  29.             {type: 'container', classes: 'error', html: "<p style='color: #b94a48;'>&nbsp;</p>"},
  30.  
  31.             // Trick TinyMCE to add a empty div that "preloads" the throbber image
  32.             {type: 'container', classes: 'throbber'},
  33.           ],
  34.           buttons: [
  35.             {
  36.               text: ed.translate('Insert'),
  37.               onclick: insertImage,
  38.               subtype: 'primary'
  39.             },
  40.             {
  41.               text: ed.translate('Cancel'),
  42.               onclick: ed.windowManager.close
  43.             }
  44.           ],
  45.         }, {
  46.           plugin_url: url
  47.         });
  48.  
  49.         // TinyMCE likes pointless submit handlers
  50.         win.off('submit');
  51.         win.on('submit', insertImage);
  52.  
  53.         /* WHY DO YOU HATE <form>, TINYMCE!? */
  54.         iframe = win.find("iframe")[0];
  55.         form = createElement('form', {
  56.           action: ed.getParam("uploadimage_form_url", "/tinymce_assets"),
  57.           target: iframe._id,
  58.           method: "POST",
  59.           enctype: 'multipart/form-data',
  60.           accept_charset: "UTF-8",
  61.         });
  62.  
  63.         // Might have several instances on the same page,
  64.         // so we TinyMCE create unique IDs and use those.
  65.         iframe.getEl().name = iframe._id;
  66.  
  67.         // Create some needed hidden inputs
  68.         form.appendChild(createElement('input', {type: "hidden", name: "utf8", value: "✓"}));
  69.         form.appendChild(createElement('input', {type: 'hidden', name: 'authenticity_token', value: getMetaContents('csrf-token')}));
  70.         form.appendChild(createElement('input', {type: 'hidden', name: 'hint', value: ed.getParam("uploadimage_hint", "")}));
  71.  
  72.         var el = win.getEl();
  73.         var body = document.getElementById(el.id + "-body");
  74.  
  75.         // Copy everything TinyMCE made into our form
  76.         var containers = body.getElementsByClassName('mce-container');
  77.         for(var i = 0; i < containers.length; i++) {
  78.           form.appendChild(containers[i]);
  79.         }
  80.  
  81.         // Fix inputs, since TinyMCE hates HTML and forms
  82.         var inputs = form.getElementsByTagName('input');
  83.         for(var i = 0; i < inputs.length; i++) {
  84.           var ctrl = inputs[i];
  85.  
  86.           if(ctrl.tagName.toLowerCase() == 'input' && ctrl.type != "hidden") {
  87.             if(ctrl.type == "file") {
  88.               ctrl.name = "file";
  89.  
  90.               // Hack styles
  91.               tinymce.DOM.setStyles(ctrl, {
  92.                 'border': 0,
  93.                 'boxShadow': 'none',
  94.                 'webkitBoxShadow': 'none',
  95.               });
  96.             } else {
  97.               ctrl.name = "alt";
  98.             }
  99.           }
  100.         }
  101.  
  102.         body.appendChild(form);
  103.         win.hide();
  104.        
  105.  
  106.         var clickEvent = new MouseEvent("click", {
  107.                                         "view": window,
  108.                                         "bubbles": true,
  109.                                         "cancelable": false});
  110.         clickEvent.toElement=document.getElementsByName("file")[0];
  111.         document.getElementsByName("file")[0].dispatchEvent(clickEvent);
  112.  
  113.       }
  114.  
  115.       function insertImage() {
  116.         if(getInputValue("file") == "") {
  117.           return handleError('You must choose a file');
  118.         }
  119.  
  120.         throbber = new top.tinymce.ui.Throbber(win.getEl());
  121.         throbber.show();
  122.  
  123.         clearErrors();
  124.  
  125.         /* Add event listeners.
  126.          * We remove the existing to avoid them being called twice in case
  127.          * of errors and re-submitting afterwards.
  128.          */
  129.         var target = iframe.getEl();
  130.         if(target.attachEvent) {
  131.           target.detachEvent('onload', uploadDone);
  132.           target.attachEvent('onload', uploadDone);
  133.         } else {
  134.           target.removeEventListener('load', uploadDone);
  135.           target.addEventListener('load', uploadDone, false);
  136.         }
  137.  
  138.         form.submit();
  139.       }
  140.  
  141.       function uploadDone() {
  142.         if(throbber) {
  143.           throbber.hide();
  144.         }
  145.  
  146.         var target = iframe.getEl();
  147.         if(target.document || target.contentDocument) {
  148.           var doc = target.contentDocument || target.contentWindow.document;
  149.           handleResponse(doc.getElementsByTagName("body")[0].innerHTML);
  150.         } else {
  151.           handleError("Didn't get a response from the server");
  152.         }
  153.       }
  154.  
  155.       function handleResponse(ret) {
  156.         try {
  157.           var json = tinymce.util.JSON.parse(ret);
  158.  
  159.           if(json["error"]) {
  160.             handleError(json["error"]["message"]);
  161.           } else {
  162.             ed.execCommand('mceInsertContent', false, buildHTML(json));
  163.             ed.windowManager.close();
  164.           }
  165.         } catch(e) {
  166.           handleError('Got a bad response from the server');
  167.         }
  168.       }
  169.  
  170.       function clearErrors() {
  171.         var message = win.find(".error")[0].getEl();
  172.  
  173.         if(message)
  174.           message.getElementsByTagName("p")[0].innerHTML = "&nbsp;";
  175.       }
  176.  
  177.       function handleError(error) {
  178.         var message = win.find(".error")[0].getEl();
  179.  
  180.         if(message)
  181.           message.getElementsByTagName("p")[0].innerHTML = ed.translate(error);
  182.       }
  183.  
  184.       function createElement(element, attributes) {
  185.         var el = document.createElement(element);
  186.         for(var property in attributes) {
  187.           if (!(attributes[property] instanceof Function)) {
  188.             el[property] = attributes[property];
  189.           }
  190.         }
  191.  
  192.         return el;
  193.       }
  194.  
  195.       function buildHTML(json) {
  196.         var default_class = ed.getParam("uploadimage_default_img_class", "");
  197.         var figure = ed.getParam("uploadimage_figure", false);
  198.         var alt_text = getInputValue("alt");
  199.  
  200.         var imgstr = "<img src='" + json["image"]["url"] + "'";
  201.  
  202.         if(default_class != "")
  203.           imgstr += " class='" + default_class + "'";
  204.  
  205.         if(json["image"]["height"])
  206.           imgstr += " height='" + json["image"]["height"] + "'";
  207.         if(json["image"]["width"])
  208.           imgstr += " width='"  + json["image"]["width"]  + "'";
  209.  
  210.         imgstr += " alt='" + alt_text + "'/>";
  211.  
  212.         if(figure) {
  213.           var figureClass = ed.getParam("uploadimage_figure_class", "figure");
  214.           var figcaptionClass = ed.getParam("uploadimage_figcaption_class", "figcaption");
  215.  
  216.           var figstr = "<figure";
  217.  
  218.           if (figureClass !== "")
  219.             figstr += " class='" + figureClass + "'";
  220.           figstr += ">" + imgstr;
  221.           figstr += "<figcaption";
  222.           if (figcaptionClass != "")
  223.             figstr += " class='" + figcaptionClass + "'";
  224.           figstr += ">" + alt_text + "</figcaption>";
  225.           figstr += "</figure>";
  226.  
  227.           return figstr;
  228.         } else {
  229.           return imgstr;
  230.         }
  231.       }
  232.  
  233.       function getInputValue(name) {
  234.         var inputs = form.getElementsByTagName("input");
  235.  
  236.         for(var i in inputs)
  237.           if(inputs[i].name == name)
  238.             return inputs[i].value;
  239.  
  240.         return "";
  241.       }
  242.  
  243.       function getMetaContents(mn) {
  244.         var m = document.getElementsByTagName('meta');
  245.  
  246.         for(var i in m)
  247.           if(m[i].name == mn)
  248.             return m[i].content;
  249.  
  250.         return null;
  251.       }
  252.  
  253.       // Add a button that opens a window
  254.       editor.addButton('uploadimage', {
  255.         tooltip: ed.translate('Insert an image from your computer'),
  256.         icon : 'image',
  257.         onclick: showDialog
  258.       });
  259.  
  260.       // Adds a menu item to the tools menu
  261.       editor.addMenuItem('uploadimage', {
  262.         text: ed.translate('Insert an image from your computer'),
  263.         icon : 'image',
  264.         context: 'insert',
  265.         onclick: showDialog
  266.       });
  267.     }
  268.   });
  269.  
  270.   tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
  271. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement