简单的编辑器闭包

闲暇无聊,简单的把原来BBS的的编辑器进行了闭包处理。和原来的功能没有啥区别,仅仅视简单的 UBB支持和ajax 上传。 纯粹算是 字的 N 种写法。

记录下来,以免忘记,其中 editer 的 ID 为 document.FORM.inpost

代码如下:

code/* - esBObj.editer = 编辑器,UBB支持 + 简单 ajax 上传 By 路杨 - */
var editer = esBObj.editer || function(w, d) {  
  var canFormat = 0;
   var config ={   
    ubb: true, /*使用UBB还是HTML*/
    is_binOK:false,
    em_no: 26,
    ua_no: 37
   }; 
   var b ={
  checkFormat : function(){
if (canFormat) return;
      if (document.selection ||  (typeof(document.createElement("textarea")["setSelectionRange"]) != "undefined"))
      canFormat = 1;
},
   getSelected : function getSelected () {
 var e= document.FORM.inpost;
       if (document.selection) {
        e.focus();
        var range = document.selection.createRange();
        return range.text;
    } else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2 && length != undefined) end = length;
        return e.value.substring(start, end);
      }
},
setSelection : function (v) {
var e= document.FORM.inpost;
        if (document.selection) {
        e.focus();
        var range = document.selection.createRange();
        range.text = v;
        } else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2 && length != undefined) end = length;
        e.value = e.value.substring(0, start) + v + e.value.substr(end, length);
        e.selectionStart = start + v.length;
        e.selectionEnd = start + v.length;
        }
     e.focus();
 },
 formatStr: function(v){     
      if (!canFormat) return;
      var str = b.getSelected();
      if (str)  {
      if( config.ubb ) b.setSelection('[' + v + ']' + str + '[/' + v + ']');
      else b.setSelection('<' + v + '>' + str + '</' + v + '>');
      }
     return false;
}
   };

  var e ={
init:function(){
    b.checkFormat();
  e.bin_actions();
}
,bin_actions : function(){
     if ( config.is_binOK) return;
$("body").on("click","a.formatting-icons, span.formatting-icons",  e.ubb)
   .on("click","a.upload-bar, span.upload-bar",  e.insertUpfile)
    .on("click","a.bt.smilie,img.bt.smilie,span.bt.smilie",  e.emot) 
    .on("click","a.addquote,img.addquote,span.addquote",  e.addquote) 
    .on("click","input#upload",  e.do_upload)
    .on("click","a.del-upload,span.del-upload",  e.del_upload)
    .on("click","a.load-upload,span.load-upload",  e.load_upload)
     ; 
   config.is_binOK =true;

    }, /*END _init*/

   del_upload : function() { /*删除所有未发布的上传文件*/ 
 if ( confirm('确定删除所有未被发布的附件临时文件么?') )
 {
$("#imgWait").show(); 
 util.get_esb_jsonp("delup", 'delup_out', { 'js' : 1 } ); 

 }
   },   
   delup_out: function(data) {   
  $("#imgWait").hide(); 
 if (data.status == "true") {
     $("#showupfile").html("");
    alert("你已经上传的,但还尚未发布的附件临时文件已经全部删除。"); 
 }
 else {alert("删除失败!");}        
   },

   load_upload : function() { /*重新加载所有未发布的上传文件到列表*/
  $("#imgWait").show(); 
  util.get_esb_jsonp("load_oldupfile", 'loadupfileout', { 'js' : 1 } ); 
   },   
loadupfileout: function(data) {   
  $("#imgWait").hide(); 
 if (data.status == "true") {
    alert("你已经上传的,但还尚未发布的附件临时文件已经加载到当前页面。"); 
 }
 else {alert("加载失败!");}        
   },

   do_upload : function() { /*上传文件处理*/

$("#imgWait").show();
var formData = new FormData();
formData.append("action", "doupfile");   
formData.append("addme", document.getElementById("file1").files[0]);   
$.ajax({
 url: w.esBConfig.cgi_url +'upfile2.cgi',
//url: "xs.html",
type: "POST",
data: formData,
/**
*必须false才会自动加上正确的Content-Type
*/
contentType: false,
/**
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
*/
processData: false,
dataType : 'json',
success: function (data) {
   console.log(data); 
if (data.status == "true") {
/* alert("上传成功!"); */
e.addit2span(data); 
e.insertUpfile(data.path,'once');   
}
if (data.status == "error") {
alert(data.msg);
}
$("#imgWait").hide();
$("#file1").replaceWith($("#file1").val('').clone(true));
},
error: function () {
alert("上传失败!");
$("#imgWait").hide();

}
});   
},
addit2span : function (data) 
{
   var $Once = '';
   if (data.once != "true" ) data.once="false" ;
   var addit2span =
   '<div id="' + data.id +'" data-name="'+ data.path+'">附件: ' +data.name
   + '[<span class="upload-bar link" data-name="'+ data.path+'" data-type ="' +data.type + '" data-once="' + data.once + '">再次插入帖子</span>]</div>';

   var $el=$("#showupfile").find("div#"+data.id);
   if (!$el.length)$(addit2span).appendTo($("#showupfile"));  
},
ubb:function  () {
var type= $(this).attr("data-ubb");
if ( ! type ) return;
if (type == 'link') return e.insertLink(0);
if (type == 'email') return e.insertLink(1);
if (type == 'decode') return e.Decode();
return b.formatStr(type);   
},

insertLink:function  ( isMail) {
    if (!canFormat) return;
    var str = b.getSelected();
    var link = '';
    if (!isMail) {
    if (str.match(/^https?:/)) {
    link = str;
    } else if (str.match(/^(\w+\.)+\w{2,5}\/?/)) {
    link = 'http://' + str;
    } else if (str.match(/ /)) {
    link = 'http://';
    } else {
    link = 'http://' + str;
    }
    } else {
    if (str.match(/@/)) {
    link = str;
    }
    }
    var my_link = prompt(isMail ? '输入 Email 地址:' : '输入 URL: ', link);
    if (my_link != null) {
    if (str == '') str = my_link;
    if (isMail) my_link = 'mailto:' + my_link;
    if( config.ubb ) b.setSelection( '[url="' + my_link + '"]' + str + '[/url]');
    else b.setSelection( '<a href="' + my_link + '">' + str + '</a>');
    }
    return false;
  },
Decode: function () {
    if (!canFormat) return;
    var str = b.getSelected();
    if (!str) return;
    str = str.replace(new RegExp("&","g"), "&amp;");
    str = str.replace(new RegExp("<","g"), "&lt;");
    str = str.replace(new RegExp(">","g"), "&gt;");
    str = str.replace(new RegExp('"',"g"), "&quot;");
    /* str = str.replace(new RegExp(' ',"g"), "&nbsp;"); */
    b.setSelection(str);
    return false;
  },
  emot:function () {
    if (!canFormat) return; 
   var group= $(this).attr("data-group") || 'em';
   var id= $(this).attr("data-emot");
   if ( ! id ) return;
    /* var str = getSelected(e); */
    b.setSelection(' :'+ group + id + ': ');    
    return false;
  },
/***重新插入上传文件的代码**********************/
  insertUpfile : function (name,once) {
    if (!canFormat) return;
    if( typeof(name) != 'string')  name = $(this).attr("data-name");
    if(!name) return; 
    if( typeof(once) != 'string')  once = $(this).attr("data-once");  /*data-once="true" */
    if (once =='once')  { once ='true';}        
    var str = ' [UploadFile='; 
    if (once =='true')  str = ' [UploadOnce='; 
    b.setSelection(str + name + '] ');  
    return false;
  },

   NewUbbico : function(span) {
    if (!span) span='ubb_span';
    var el = $('#'+span);
    if (el.length == 0) return false;
   el.html( e.getUbbicoHTML() );
    },
getUbbicoHTML: function () {
        util.Load_css("https://static.easunlee.cn/css/formatting-icons.css");
        var str ='';
        str = '<span class="formatting-icons bold" title="粗体" data-ubb="b" ></span>';
        str += '<span class="formatting-icons italic"  title="斜体" data-ubb="i" ></span>';
        str += '<span class="formatting-icons underline"  title="下划线" data-ubb="u"></span>';
        str += '<span class="formatting-icons link"  title="插入链接" data-ubb="link" ></span>';
        str += '<span class="formatting-icons email"  title="插入 Email 链接" data-ubb="email"  ></span>';
        str += '<span class="formatting-icons quote"  title="引用"  data-ubb="quote"></span>';
        str += '<span class="formatting-icons decode"  title="HTML编码" data-ubb="decode"></span>';
        return str;
    },
    NewEmot  :function (span) {
        if (!span) span='emot_span';
        var el = $('#'+span); 
         if (el.length == 0) return false; 
       el.html( e.getEmotHTML() );
    },
      getEmotHTML : function () {
       var str ='';
         var i=1;
         var name =1; 
         for ( i=1;i<( config.em_no +1) ;i++) 
        {  
           name = (i>=10) ?i :'0'+i ; 
           str += '<img class="bt smilie"  src="'+esBConfig.static_url+'emot/em' +name +'.gif" data-emot="'+ name+'" data-group="em" />';
        }
        for ( i=1;i<( config.ua_no +1); i++)
        {  
           name = (i>=10) ?i :'0'+i ; 
           str += '<img class="bt smilie"  src="'+esBConfig.static_url+'emot/ua' +name +'.gif" data-emot="'+ name+'" data-group="ua" />';
        }

        return str;
    },
    addquote : function(no)
    { 
      if (!canFormat) return;   

      if( typeof(no) != 'number')  no = $(this).attr("data-no");
      if ( typeof(no) != 'number' ) return;   
      var membername = $("#membername"+no).text(); 
      var postdate =  $("#postdate"+no).text();   
      var post = $("#post"+no).html(); 
      var regx = /^\<blockquote\>.*\<\/blockquote\>/;     
      post = post.replace(regx, "");  
      var $tmp = $('<span></span>');
      $tmp.html(post);
      $tmp.find("script").remove();

      post =$tmp.text();
      post = $.trim(post);
      var mysub=function(str,n){
    var r=/[^\x00-\xff]/g;
      if(str.replace(r,"aa").length<=n){return str;}
      var m=Math.floor(n/2);
      for(var i=m;i<str.length;i++){
if(str.substr(0,i).replace(r,"aa").length>=n){ return str.substr(0,i)+"\n..."; }
  } 
return str;
}
/*    post =post.substring(0, 200);  */
      post =mysub(post, 200); 
      post = $.trim(post);
      var text = "[quote][b]下面引用由[u]" + membername + "[/u]在 [i]" + postdate + "[/i] 发表的内容:[/b]\n" + post + "\n[/quote]\n";  
      b.setSelection(text);
     }

}; 

   window.esBObj.editer =e;
   return e;
}(window, document);