簡單的編輯器閉包

閒暇無聊,簡單的把原來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("http://www.kcpon.com/static/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);