code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * @classDescription shortcut * @author AjaxUI Lab - mixed */ function Shortcut(sKey,sId){ var sKey = sKey.replace(/\s+/g,""); var store = Shortcut.Store; var action = Shortcut.Action; if(typeof sId === "undefined"&&sKey.constructor == String){ store.set("document",sKey,document); return action.init(store.get("document"),sKey); }else if(sId.constructor == String&&sKey.constructor == String){ store.set(sId,sKey,jindo.$(sId)); return action.init(store.get(sId),sKey); }else if(sId.constructor != String&&sKey.constructor == String){ var fakeId = "nonID"+new Date().getTime(); fakeId = Shortcut.Store.searchId(fakeId,sId); store.set(fakeId,sKey,sId); return action.init(store.get(fakeId),sKey); } alert(sId+"는 반드시 string이거나 없어야 됩니다."); }; Shortcut.Store = { anthorKeyHash:{}, datas:{}, currentId:"", currentKey:"", searchId:function(sId,oElement){ jindo.$H(this.datas).forEach(function(oValue,sKey){ if(oElement == oValue.element){ sId = sKey; jindo.$H.Break(); } }); return sId; }, set:function(sId,sKey,oElement){ this.currentId = sId; this.currentKey = sKey; var idData = this.get(sId); this.datas[sId] = idData?idData.createKey(sKey):new Shortcut.Data(sId,sKey,oElement); }, get:function(sId,sKey){ if(sKey){ return this.datas[sId].keys[sKey]; }else{ return this.datas[sId]; } }, reset:function(sId){ var data = this.datas[sId]; Shortcut.Helper.bind(data.func,data.element,"detach"); delete this.datas[sId]; }, allReset: function(){ jindo.$H(this.datas).forEach(jindo.$Fn(function(value,key) { this.reset(key); },this).bind()); } }; Shortcut.Data = jindo.$Class({ $init:function(sId,sKey,oElement){ this.id = sId; this.element = oElement; this.func = jindo.$Fn(this.fire,this).bind(); Shortcut.Helper.bind(this.func,oElement,"attach"); this.keys = {}; this.keyStemp = {}; this.createKey(sKey); }, createKey:function(sKey){ this.keyStemp[Shortcut.Helper.keyInterpretor(sKey)] = sKey; this.keys[sKey] = {}; var data = this.keys[sKey]; data.key = sKey; data.events = []; data.commonExceptions = []; // data.keyAnalysis = Shortcut.Helper.keyInterpretor(sKey); data.stopDefalutBehavior = true; return this; }, getKeyStamp : function(eEvent){ var sKey = eEvent.keyCode || eEvent.charCode; var returnVal = ""; returnVal += eEvent.altKey?"1":"0"; returnVal += eEvent.ctrlKey?"1":"0"; returnVal += eEvent.metaKey?"1":"0"; returnVal += eEvent.shiftKey?"1":"0"; returnVal += sKey; return returnVal; }, fire:function(eEvent){ eEvent = eEvent||window.eEvent; var oMatchKeyData = this.keyStemp[this.getKeyStamp(eEvent)]; if(oMatchKeyData){ this.excute(new jindo.$Event(eEvent),oMatchKeyData); } }, excute:function(weEvent,sRawKey){ var isExcute = true; var staticFun = Shortcut.Helper; var data = this.keys[sRawKey]; if(staticFun.notCommonException(weEvent,data.commonExceptions)){ jindo.$A(data.events).forEach(function(v){ if(data.stopDefalutBehavior){ var leng = v.exceptions.length; if(leng){ for(var i=0;i<leng;i++){ if(!v.exception[i](weEvent)){ isExcute = false; break; } } if(isExcute){ v.event(weEvent); if(jindo.$Agent().navigator().ie){ var e = weEvent._event; e.keyCode = ""; e.charCode = ""; } weEvent.stop(); }else{ jindo.$A.Break(); } }else{ v.event(weEvent); if(jindo.$Agent().navigator().ie){ var e = weEvent._event; e.keyCode = ""; e.charCode = ""; } weEvent.stop(); } } }); } }, addEvent:function(fpEvent,sRawKey){ var events = this.keys[sRawKey].events; if(!Shortcut.Helper.hasEvent(fpEvent,events)){ events.push({ event:fpEvent, exceptions:[] }); }; }, addException:function(fpException,sRawKey){ var commonExceptions = this.keys[sRawKey].commonExceptions; if(!Shortcut.Helper.hasException(fpException,commonExceptions)){ commonExceptions.push(fpException); }; }, removeException:function(fpException,sRawKey){ var commonExceptions = this.keys[sRawKey].commonExceptions; commonExceptions = jindo.$A(commonExceptions).filter(function(exception){ return exception!=fpException; }).$value(); }, removeEvent:function(fpEvent,sRawKey){ var events = this.keys[sRawKey].events; events = jindo.$A(events).filter(function(event) { return event!=fpEvent; }).$value(); this.unRegister(sRawKey); }, unRegister:function(sRawKey){ var aEvents = this.keys[sRawKey].events; if(aEvents.length) delete this.keys[sRawKey]; var hasNotKey = true; for(var i in this.keys){ hasNotKey =false; break; } if(hasNotKey){ Shortcut.Helper.bind(this.func,this.element,"detach"); delete Shortcut.Store.datas[this.id]; } }, startDefalutBehavior: function(sRawKey){ this._setDefalutBehavior(sRawKey,false); }, stopDefalutBehavior: function(sRawKey){ this._setDefalutBehavior(sRawKey,true); }, _setDefalutBehavior: function(sRawKey,bType){ this.keys[sRawKey].stopDefalutBehavior = bType; } }); Shortcut.Helper = { keyInterpretor:function(sKey){ var keyArray = sKey.split("+"); var wKeyArray = jindo.$A(keyArray); var returnVal = ""; returnVal += wKeyArray.has("alt")?"1":"0"; returnVal += wKeyArray.has("ctrl")?"1":"0"; returnVal += wKeyArray.has("meta")?"1":"0"; returnVal += wKeyArray.has("shift")?"1":"0"; var wKeyArray = wKeyArray.filter(function(v){ return !(v=="alt"||v=="ctrl"||v=="meta"||v=="shift") }); var key = wKeyArray.$value()[0]; if(key){ var sKey = Shortcut.Store.anthorKeyHash[key.toUpperCase()]||key.toUpperCase().charCodeAt(0); returnVal += sKey; } return returnVal; }, notCommonException:function(e,exceptions){ var leng = exceptions.length; for(var i=0;i<leng ;i++){ if(!exceptions[i](e)) return false; } return true; }, hasEvent:function(fpEvent,aEvents){ var nLength = aEvents.length; for(var i=0; i<nLength; ++i){ if(aEvents.event==fpEvent){ return true; } }; return false; }, hasException:function(fpException,commonExceptions){ var nLength = commonExceptions.length; for(var i=0; i<nLength; ++i){ if(commonExceptions[i]==fpException){ return true; } }; return false; }, bind:function(wfFunc,oElement,sType){ if(sType=="attach"){ domAttach(oElement,"keydown",wfFunc); }else{ domDetach(oElement,"keydown",wfFunc); } } }; (function domAttach (){ if(document.addEventListener){ window.domAttach = function(dom,ev,fn){ dom.addEventListener(ev, fn, false); } }else{ window.domAttach = function(dom,ev,fn){ dom.attachEvent("on"+ev, fn); } } })(); (function domDetach (){ if(document.removeEventListener){ window.domDetach = function(dom,ev,fn){ dom.removeEventListener(ev, fn, false); } }else{ window.domDetach = function(dom,ev,fn){ dom.detachEvent("on"+ev, fn); } } })(); Shortcut.Action ={ init:function(oData,sRawKey){ this.dataInstance = oData; this.rawKey = sRawKey; return this; }, addEvent:function(fpEvent){ this.dataInstance.addEvent(fpEvent,this.rawKey); return this; }, removeEvent:function(fpEvent){ this.dataInstance.removeEvent(fpEvent,this.rawKey); return this; }, addException : function(fpException){ this.dataInstance.addException(fpException,this.rawKey); return this; }, removeException : function(fpException){ this.dataInstance.removeException(fpException,this.rawKey); return this; }, // addCommonException : function(fpException){ // return this; // }, // removeCommonEexception : function(fpException){ // return this; // }, startDefalutBehavior: function(){ this.dataInstance.startDefalutBehavior(this.rawKey); return this; }, stopDefalutBehavior: function(){ this.dataInstance.stopDefalutBehavior(this.rawKey); return this; }, resetElement: function(){ Shortcut.Store.reset(this.dataInstance.id); return this; }, resetAll: function(){ Shortcut.Store.allReset(); return this; } }; (function (){ Shortcut.Store.anthorKeyHash = { BACKSPACE : 8, TAB : 9, ENTER : 13, ESC : 27, SPACE : 32, PAGEUP : 33, PAGEDOWN : 34, END : 35, HOME : 36, LEFT : 37, UP : 38, RIGHT : 39, DOWN : 40, DEL : 46, COMMA : 188,//(,) PERIOD : 190,//(.) SLASH : 191//(/), }; var hash = Shortcut.Store.anthorKeyHash; for(var i=1 ; i < 13 ; i++){ Shortcut.Store.anthorKeyHash["F"+i] = i+111; } var agent = jindo.$Agent().navigator(); if(agent.ie||agent.safari||agent.chrome){ hash.HYPHEN = 189;//(-) hash.EQUAL = 187;//(=) }else{ hash.HYPHEN = 109; hash.EQUAL = 61; } })(); var shortcut = Shortcut;
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the hotkey feature * @name hp_Hotkey.js */ nhn.husky.Hotkey = jindo.$Class({ name : "Hotkey", $init : function(){ this.oShortcut = shortcut; }, $ON_ADD_HOTKEY : function(sHotkey, sCMD, aArgs, elTarget){ if(!aArgs){aArgs = [];} var func = jindo.$Fn(this.oApp.exec, this.oApp).bind(sCMD, aArgs); this.oShortcut(sHotkey, elTarget).addEvent(func); } }); //}
JavaScript
/** * @use 간단 포토 업로드용으로 제작되었습니다. * @author cielo * @See nhn.husky.SE2M_Configuration * @ 팝업 마크업은 SimplePhotoUpload.html과 SimplePhotoUpload_html5.html이 있습니다. */ nhn.husky.SE2M_AttachQuickPhoto = jindo.$Class({ name : "SE2M_AttachQuickPhoto", $init : function(){}, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["photo_attach", "click", "ATTACHPHOTO_OPEN_WINDOW"]); }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!this.oPopupMgr){ return; } // Popup Manager에서 사용할 param this.htPopupOption = { oApp : this.oApp, sName : this.name, bScroll : false, sProperties : "", sUrl : "" }; this.oPopupMgr = nhn.husky.PopUpManager.getInstance(this.oApp); }, /** * 포토 웹탑 오픈 */ $ON_ATTACHPHOTO_OPEN_WINDOW : function(){ this.htPopupOption.sUrl = this.makePopupURL(); this.htPopupOption.sProperties = "left=0,top=0,width=383,height=339,scrollbars=no,location=no,status=0,resizable=no"; this.oPopupWindow = this.oPopupMgr.openWindow(this.htPopupOption); // 처음 로딩하고 IE에서 커서가 전혀 없는 경우 // 복수 업로드시에 순서가 바뀜 this.oApp.exec('FOCUS'); return (!!this.oPopupWindow ? true : false); }, /** * 서비스별로 팝업에 parameter를 추가하여 URL을 생성하는 함수 * nhn.husky.SE2M_AttachQuickPhoto.prototype.makePopupURL로 덮어써서 사용하시면 됨. */ makePopupURL : function(){ var sPopupUrl = "/sEditor/popup/quick_photo/Photo_Quick_UploadPopup.html"; return sPopupUrl; }, /** * 팝업에서 호출되는 메세지. */ $ON_SET_PHOTO : function(aPhotoData){ var sContents, aPhotoInfo, htData; if( !aPhotoData ){ return; } try{ sContents = ""; for(var i = 0; i <aPhotoData.length; i++){ htData = aPhotoData[i]; if(!htData.sAlign){ htData.sAlign = ""; } aPhotoInfo = { sName : htData.sFileName || "", sOriginalImageURL : htData.sFileURL, bNewLine : htData.bNewLine || false }; sContents += this._getPhotoTag(aPhotoInfo); } this.oApp.exec("PASTE_HTML", [sContents]); // 위즐 첨부 파일 부분 확인 }catch(e){ // upload시 error발생에 대해서 skip함 return false; } }, /** * @use 일반 포토 tag 생성 */ _getPhotoTag : function(htPhotoInfo){ // id와 class는 썸네일과 연관이 많습니다. 수정시 썸네일 영역도 Test var sTag = '<img src="{=sOriginalImageURL}" title="{=sName}" >'; if(htPhotoInfo.bNewLine){ sTag += '<br style="clear:both;">'; } sTag = jindo.$Template(sTag).process(htPhotoInfo); return sTag; } });
JavaScript
/*[ * SE_FIT_IFRAME * * 스마트에디터 사이즈에 맞게 iframe사이즈를 조절한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 에디터를 싸고 있는 iframe 사이즈 조절을 담당하는 플러그인 */ nhn.husky.SE_OuterIFrameControl = $Class({ name : "SE_OuterIFrameControl", oResizeGrip : null, $init : function(oAppContainer){ // page up, page down, home, end, left, up, right, down this.aHeightChangeKeyMap = [-100, 100, 500, -500, -1, -10, 1, 10]; this._assignHTMLObjects(oAppContainer); //키보드 이벤트 this.$FnKeyDown = $Fn(this._keydown, this); if(this.oResizeGrip){ this.$FnKeyDown.attach(this.oResizeGrip, "keydown"); } //마우스 이벤트 if(!!jindo.$Agent().navigator().ie){ this.$FnMouseDown = $Fn(this._mousedown, this); this.$FnMouseMove = $Fn(this._mousemove, this); this.$FnMouseMove_Parent = $Fn(this._mousemove_parent, this); this.$FnMouseUp = $Fn(this._mouseup, this); if(this.oResizeGrip){ this.$FnMouseDown.attach(this.oResizeGrip, "mousedown"); } } }, _assignHTMLObjects : function(oAppContainer){ oAppContainer = $(oAppContainer) || document; this.oResizeGrip = cssquery.getSingle(".husky_seditor_editingArea_verticalResizer", oAppContainer); this.elIFrame = window.frameElement; this.welIFrame = $Element(this.elIFrame); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("SE_FIT_IFRAME", []); }, $ON_MSG_EDITING_AREA_SIZE_CHANGED : function(){ this.oApp.exec("SE_FIT_IFRAME", []); }, $ON_SE_FIT_IFRAME : function(){ this.elIFrame.style.height = document.body.offsetHeight+"px"; }, $AFTER_RESIZE_EDITING_AREA_BY : function(ipWidthChange, ipHeightChange){ this.oApp.exec("SE_FIT_IFRAME", []); }, _keydown : function(oEvent){ var oKeyInfo = oEvent.key(); // 33, 34: page up/down, 35,36: end/home, 37,38,39,40: left, up, right, down if(oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40){ this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", []); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, this.aHeightChangeKeyMap[oKeyInfo.keyCode-33]]); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", []); oEvent.stop(); } }, _mousedown : function(oEvent){ this.iStartHeight = oEvent.pos().clientY; this.iStartHeightOffset = oEvent.pos().layerY; this.$FnMouseMove.attach(document, "mousemove"); this.$FnMouseMove_Parent.attach(parent.document, "mousemove"); this.$FnMouseUp.attach(document, "mouseup"); this.$FnMouseUp.attach(parent.document, "mouseup"); this.iStartHeight = oEvent.pos().clientY; this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _mousemove : function(oEvent){ var iHeightChange = oEvent.pos().clientY - this.iStartHeight; this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mousemove_parent : function(oEvent){ var iHeightChange = oEvent.pos().pageY - (this.welIFrame.offset().top + this.iStartHeight); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mouseup : function(oEvent){ this.$FnMouseMove.detach(document, "mousemove"); this.$FnMouseMove_Parent.detach(parent.document, "mousemove"); this.$FnMouseUp.detach(document, "mouseup"); this.$FnMouseUp.detach(parent.document, "mouseup"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); } });
JavaScript
if(typeof window.nhn=='undefined'){window.nhn = {};} /** * @fileOverview This file contains a message mapping(Korean), which is used to map the message code to the actual message * @name husky_SE2B_Lang_ko_KR.js * @ unescape */ var oMessageMap = { 'SE_EditingAreaManager.onExit' : '내용이 변경되었습니다.', 'SE_Color.invalidColorCode' : '색상 코드를 올바르게 입력해 주세요. \n\n 예) #000000, #FF0000, #FFFFFF, #ffffff, ffffff', 'SE_Hyperlink.invalidURL' : '입력하신 URL이 올바르지 않습니다.', 'SE_FindReplace.keywordMissing' : '찾으실 단어를 입력해 주세요.', 'SE_FindReplace.keywordNotFound' : '찾으실 단어가 없습니다.', 'SE_FindReplace.replaceAllResultP1' : '일치하는 내용이 총 ', 'SE_FindReplace.replaceAllResultP2' : '건 바뀌었습니다.', 'SE_FindReplace.notSupportedBrowser' : '현재 사용하고 계신 브라우저에서는 사용하실수 없는 기능입니다.\n\n이용에 불편을 드려 죄송합니다.', 'SE_FindReplace.replaceKeywordNotFound' : '바뀔 단어가 없습니다', 'SE_LineHeight.invalidLineHeight' : '잘못된 값입니다.', 'SE_Footnote.defaultText' : '각주내용을 입력해 주세요', 'SE.failedToLoadFlash' : '플래시가 차단되어 있어 해당 기능을 사용할 수 없습니다.', 'SE2M_EditingModeChanger.confirmTextMode' : '텍스트 모드로 전환하면 작성된 내용은 유지되나, \n\n글꼴 등의 편집효과와 이미지 등의 첨부내용이 모두 사라지게 됩니다.\n\n전환하시겠습니까?', 'SE2M_FontNameWithLayerUI.sSampleText' : '가나다라' };
JavaScript
/** * @name nhn.husky.SE2B_Customize_ToolBar * @description 메일 전용 커스터마이즈 툴바로 더보기 레이어 관리만을 담당하고 있음. * @class * @author HyeKyoung,NHN AjaxUI Lab, CMD Division * @version 0.1.0 * @since */ nhn.husky.SE2B_Customize_ToolBar = jindo.$Class(/** @lends nhn.husky.SE2B_Customize_ToolBar */{ name : "SE2B_Customize_ToolBar", /** * @constructs * @param {Object} oAppContainer 에디터를 구성하는 컨테이너 */ $init : function(oAppContainer) { this._assignHTMLElements(oAppContainer); }, $BEFORE_MSG_APP_READY : function(){ this._addEventMoreButton(); }, /** * @private * @description DOM엘리먼트를 수집하는 메소드 * @param {Object} oAppContainer 툴바 포함 에디터를 감싸고 있는 div 엘리먼트 */ _assignHTMLElements : function(oAppContainer) { this.oAppContainer = oAppContainer; this.elTextToolBarArea = jindo.$$.getSingle("div.se2_tool"); this.elTextMoreButton = jindo.$$.getSingle("button.se2_text_tool_more", this.elTextToolBarArea); this.elTextMoreButtonParent = this.elTextMoreButton.parentNode; this.welTextMoreButtonParent = jindo.$Element(this.elTextMoreButtonParent); this.elMoreLayer = jindo.$$.getSingle("div.se2_sub_text_tool"); }, _addEventMoreButton : function (){ this.oApp.registerBrowserEvent(this.elTextMoreButton, "click", "EVENT_CLICK_EXPAND_VIEW"); this.oApp.registerBrowserEvent(this.elMoreLayer, "click", "EVENT_CLICK_EXPAND_VIEW"); }, $ON_EVENT_CLICK_EXPAND_VIEW : function(weEvent){ this.oApp.exec("TOGGLE_EXPAND_VIEW", [this.elTextMoreButton]); weEvent.stop(); }, $ON_TOGGLE_EXPAND_VIEW : function(){ if(!this.welTextMoreButtonParent.hasClass("active")){ this.oApp.exec("SHOW_EXPAND_VIEW"); } else { this.oApp.exec("HIDE_EXPAND_VIEW"); } }, $ON_CHANGE_EDITING_MODE : function(sMode){ if(sMode != "WYSIWYG"){ this.elTextMoreButton.disabled =true; this.welTextMoreButtonParent.removeClass("active"); this.oApp.exec("HIDE_EXPAND_VIEW"); }else{ this.elTextMoreButton.disabled =false; } }, $AFTER_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_EXPAND_VIEW"); }, $AFTER_SHOW_DIALOG_LAYER : function(){ this.oApp.exec("HIDE_EXPAND_VIEW"); }, $ON_SHOW_EXPAND_VIEW : function(){ this.welTextMoreButtonParent.addClass("active"); this.elMoreLayer.style.display = "block"; }, $ON_HIDE_EXPAND_VIEW : function(){ this.welTextMoreButtonParent.removeClass("active"); this.elMoreLayer.style.display = "none"; }, /** * CHANGE_EDITING_MODE모드 이후에 호출되어야 함. * WYSIWYG 모드가 활성화되기 전에 호출이 되면 APPLY_FONTCOLOR에서 에러 발생. */ $ON_RESET_TOOLBAR : function(){ if(this.oApp.getEditingMode() !== "WYSIWYG"){ return; } //스펠체크 닫기 this.oApp.exec("END_SPELLCHECK"); //열린 팝업을 닫기 위해서 this.oApp.exec("DISABLE_ALL_UI"); this.oApp.exec("ENABLE_ALL_UI"); //글자색과 글자 배경색을 제외한 세팅 this.oApp.exec("RESET_STYLE_STATUS"); this.oApp.exec("CHECK_STYLE_CHANGE"); //최근 사용한 글자색 셋팅. this.oApp.exec("APPLY_FONTCOLOR", ["#000000"]); //더보기 영역 닫기. this.oApp.exec("HIDE_EXPAND_VIEW"); } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of loading css files dynamically * @name hp_SE2B_CSSLoader.js */ nhn.husky.SE2B_CSSLoader = jindo.$Class({ name : "SE2B_CSSLoader", bCssLoaded : false, // load & continue with the message right away. aInstantLoadTrigger : ["OPEN_QE_LAYER", "SHOW_ACTIVE_LAYER", "SHOW_DIALOG_LAYER"], // if a rendering bug occurs in IE, give some delay before continue processing the message. aDelayedLoadTrigger : ["MSG_SE_OBJECT_EDIT_REQUESTED", "OBJECT_MODIFY", "MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED", "TOGGLE_TOOLBAR_ACTIVE_LAYER", "SHOW_TOOLBAR_ACTIVE_LAYER"], $init : function(){ this.htOptions = nhn.husky.SE2M_Configuration.SE2B_CSSLoader; // only IE's slow if(!jindo.$Agent().navigator().ie){ this.loadSE2CSS(); }else{ for(var i=0, nLen = this.aInstantLoadTrigger.length; i<nLen; i++){ this["$BEFORE_"+this.aInstantLoadTrigger[i]] = jindo.$Fn(function(){ this.loadSE2CSS(); }, this).bind(); } for(var i=0, nLen = this.aDelayedLoadTrigger.length; i<nLen; i++){ var sMsg = this.aDelayedLoadTrigger[i]; this["$BEFORE_"+this.aDelayedLoadTrigger[i]] = jindo.$Fn(function(sMsg){ var aArgs = jindo.$A(arguments).$value(); aArgs = aArgs.splice(1, aArgs.length-1); return this.loadSE2CSS(sMsg, aArgs); }, this).bind(sMsg); } } }, /* $BEFORE_REEDIT_ITEM_ACTION : function(){ return this.loadSE2CSS("REEDIT_ITEM_ACTION", arguments); }, $BEFORE_OBJECT_MODIFY : function(){ return this.loadSE2CSS("OBJECT_MODIFY", arguments); }, $BEFORE_MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED : function(){ return this.loadSE2CSS("MSG_SE_DUMMY_OBJECT_EDIT_REQUESTED", arguments); }, $BEFORE_TOGGLE_DBATTACHMENT_LAYER : function(){ return this.loadSE2CSS("TOGGLE_DBATTACHMENT_LAYER", arguments); }, $BEFORE_SHOW_WRITE_REVIEW_DESIGN_SELECT_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_OPEN_QE_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_TOGGLE_TOOLBAR_ACTIVE_LAYER : function(){ return this.loadSE2CSS("TOGGLE_TOOLBAR_ACTIVE_LAYER", arguments); }, $BEFORE_SHOW_TOOLBAR_ACTIVE_LAYER : function(){ return this.loadSE2CSS("SHOW_TOOLBAR_ACTIVE_LAYER", arguments); }, $BEFORE_SHOW_ACTIVE_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_SHOW_DIALOG_LAYER : function(){ this.loadSE2CSS(); }, $BEFORE_TOGGLE_ITEM_LAYER : function(){ return this.loadSE2CSS("TOGGLE_ITEM_LAYER", arguments); }, */ // if a rendering bug occurs in IE, pass sMsg and oArgs to give some delay before the message is processed. loadSE2CSS : function(sMsg, oArgs){ if(this.bCssLoaded){return true;} this.bCssLoaded = true; var fnCallback = null; if(sMsg){ fnCallback = jindo.$Fn(this.oApp.exec, this.oApp).bind(sMsg, oArgs); } //nhn.husky.SE2M_Utils.loadCSS("css/smart_editor2.css"); nhn.husky.SE2M_Utils.loadCSS(this.htOptions.sCSSBaseURI+"/smart_editor2_items.css", fnCallback); return false; } }); //}
JavaScript
// Sample plugin. Use CTRL+T to toggle the toolbar nhn.husky.SE_ToolbarToggler = $Class({ name : "SE_ToolbarToggler", bUseToolbar : true, $init : function(oAppContainer, bUseToolbar){ this._assignHTMLObjects(oAppContainer, bUseToolbar); }, _assignHTMLObjects : function(oAppContainer, bUseToolbar){ oAppContainer = $(oAppContainer) || document; this.toolbarArea = cssquery.getSingle(".se2_tool", oAppContainer); //설정이 없거나, 사용하겠다고 표시한 경우 block 처리 if( typeof(bUseToolbar) == 'undefined' || bUseToolbar === true){ this.toolbarArea.style.display = "block"; }else{ this.toolbarArea.style.display = "none"; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_HOTKEY", ["ctrl+t", "SE_TOGGLE_TOOLBAR", []]); }, $ON_SE_TOGGLE_TOOLBAR : function(){ this.toolbarArea.style.display = (this.toolbarArea.style.display == "none")?"block":"none"; this.oApp.exec("MSG_EDITING_AREA_SIZE_CHANGED", []); } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that maps a message code to the actual message * @name hp_MessageManager.js */ nhn.husky.MessageManager = jindo.$Class({ name : "MessageManager", oMessageMap : null, sLocale : "ko_KR", $init : function(oMessageMap, sLocale){ switch(sLocale) { case "ja_JP" : this.oMessageMap = oMessageMap_ja_JP; break; case "en_US" : this.oMessageMap = oMessageMap_en_US; break; case "zh_CN" : this.oMessageMap = oMessageMap_zh_CN; break; default : // Korean this.oMessageMap = oMessageMap; break; } }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["$MSG", jindo.$Fn(this.getMessage, this).bind()]); }, getMessage : function(sMsg){ if(this.oMessageMap[sMsg]){return unescape(this.oMessageMap[sMsg]);} return sMsg; } }); //}
JavaScript
//{ /** * @fileOverview This file contains * @name hp_LazyLoader.js */ nhn.husky.LazyLoader = jindo.$Class({ name : "LazyLoader", // sMsg : KEY // contains htLoadingInfo : {} htMsgInfo : null, // contains objects // sURL : HTML to be loaded // elTarget : where to append the HTML // sSuccessCallback : message name // sFailureCallback : message name // nLoadingStatus : // 0 : loading not started // 1 : loading started // 2 : loading ended aLoadingInfo : null, // aToDo : [{aMsgs: ["EXECCOMMAND"], sURL: "http://127.0.0.1/html_snippet.txt", elTarget: elPlaceHolder}, ...] $init : function(aToDo){ this.htMsgInfo = {}; this.aLoadingInfo = []; this.aToDo = aToDo; }, $ON_MSG_APP_READY : function(){ for(var i=0; i<this.aToDo.length; i++){ var htToDoDetail = this.aToDo[i]; this._createBeforeHandlersAndSaveURLInfo(htToDoDetail.oMsgs, htToDoDetail.sURL, htToDoDetail.elTarget, htToDoDetail.htOptions); } }, $LOCAL_BEFORE_ALL : function(sMsgHandler, aParams){ var sMsg = sMsgHandler.replace("$BEFORE_", ""); var htCurMsgInfo = this.htMsgInfo[sMsg]; // ignore current message if(htCurMsgInfo.nLoadingStatus == 1){return true;} // the HTML was loaded before(probably by another message), remove the loading handler and re-send the message if(htCurMsgInfo.nLoadingStatus == 2){ this[sMsgHandler] = function(){ this._removeHandler(sMsgHandler); this.oApp.delayedExec(sMsg, aParams, 0); return false; }; return true; } htCurMsgInfo.bLoadingStatus = 1; (new jindo.$Ajax(htCurMsgInfo.sURL, { onload : jindo.$Fn(this._onload, this).bind(sMsg, aParams) })).request(); return true; }, _onload : function(sMsg, aParams, oResponse){ if(oResponse._response.readyState == 4) { this.htMsgInfo[sMsg].elTarget.innerHTML = oResponse.text(); this.htMsgInfo[sMsg].nLoadingStatus = 2; this._removeHandler("$BEFORE_"+sMsg); this.oApp.exec("sMsg", aParams); }else{ this.oApp.exec(this.htMsgInfo[sMsg].sFailureCallback, []); } }, _removeHandler : function(sMsgHandler){ delete this[sMsgHandler]; this.oApp.createMessageMap(sMsgHandler); }, _createBeforeHandlersAndSaveURLInfo : function(oMsgs, sURL, elTarget, htOptions){ htOptions = htOptions || {}; var htNewInfo = { sURL : sURL, elTarget : elTarget, sSuccessCallback : htOptions.sSuccessCallback, sFailureCallback : htOptions.sFailureCallback, nLoadingStatus : 0 }; this.aLoadingInfo[this.aLoadingInfo.legnth] = htNewInfo; // extract msgs if plugin is given if(!(oMsgs instanceof Array)){ var oPlugin = oMsgs; oMsgs = []; var htMsgAdded = {}; for(var sFunctionName in oPlugin){ if(sFunctionName.match(/^\$(BEFORE|ON|AFTER)_(.+)$/)){ var sMsg = RegExp.$2; if(sMsg == "MSG_APP_READY"){continue;} if(!htMsgAdded[sMsg]){ oMsgs[oMsgs.length] = RegExp.$2; htMsgAdded[sMsg] = true; } } } } for(var i=0; i<oMsgs.length; i++){ // create HTML loading handler var sTmpMsg = "$BEFORE_"+oMsgs[i]; this[sTmpMsg] = function(){return false;}; this.oApp.createMessageMap(sTmpMsg); // add loading info this.htMsgInfo[oMsgs[i]] = htNewInfo; } } }); //}
JavaScript
/*[ * ATTACH_HOVER_EVENTS * * 주어진 HTML엘리먼트에 Hover 이벤트 발생시 특정 클래스가 할당 되도록 설정 * * aElms array Hover 이벤트를 걸 HTML Element 목록 * sHoverClass string Hover 시에 할당 할 클래스 * ---------------------------------------------------------------------------]*/ /** * @pluginDesc Husky Framework에서 자주 사용되는 유틸성 메시지를 처리하는 플러그인 */ nhn.husky.Utils = jindo.$Class({ name : "Utils", $init : function(){ var oAgentInfo = jindo.$Agent(); var oNavigatorInfo = oAgentInfo.navigator(); if(oNavigatorInfo.ie && oNavigatorInfo.version == 6){ try{ document.execCommand('BackgroundImageCache', false, true); }catch(e){} } }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["htBrowser", jindo.$Agent().navigator()]); }, $ON_ATTACH_HOVER_EVENTS : function(aElms, htOptions){ htOptions = htOptions || []; var sHoverClass = htOptions.sHoverClass || "hover"; var fnElmToSrc = htOptions.fnElmToSrc || function(el){return el}; var fnElmToTarget = htOptions.fnElmToTarget || function(el){return el}; if(!aElms) return; var wfAddClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).addClass(sHoverClass); }, this); var wfRemoveClass = jindo.$Fn(function(wev){ jindo.$Element(fnElmToTarget(wev.currentElement)).removeClass(sHoverClass); }, this); for(var i=0, len = aElms.length; i<len; i++){ var elSource = fnElmToSrc(aElms[i]); wfAddClass.attach(elSource, "mouseover"); wfRemoveClass.attach(elSource, "mouseout"); wfAddClass.attach(elSource, "focus"); wfRemoveClass.attach(elSource, "blur"); } } });
JavaScript
nhn.husky.SE2M_ImgSizeRatioKeeper = jindo.$Class({ name : "SE2M_ImgSizeRatioKeeper", $LOCAL_BEFORE_FIRST : function(){ this.wfnResizeEnd = jindo.$Fn(this._onResizeEnd, this); }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(){ this._detachResizeEnd(); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wev){ this._detachResizeEnd(); if(!wev.element || wev.element.tagName != "IMG"){return;} this.oApp.exec("SET_RESIZE_TARGET_IMG", [wev.element]); }, $ON_SET_RESIZE_TARGET_IMG : function(elImg){ if(elImg == this.elImg){return;} this._detachResizeEnd(); this._attachResizeEnd(elImg); }, _attachResizeEnd : function(elImg){ this.elImg = elImg; this.wfnResizeEnd.attach(this.elImg, "resizeend"); this.elBorderSize = (elImg.border || 0); this.nWidth = this.elImg.clientWidth ; this.nHeight = this.elImg.clientHeight ; }, _detachResizeEnd : function(){ if(!this.elImg){return;} this.wfnResizeEnd.detach(this.elImg, "resizeend"); this.elImg = null; }, _onResizeEnd : function(wev){ if(wev.element != this.elImg){return;} var nRatio, nAfterWidth, nAfterheight, nWidthDiff, nHeightDiff, nborder; nborder = this.elImg.border || 0; nAfterWidth = this.elImg.clientWidth - (nborder*2); nAfterheight = this.elImg.clientHeight - (nborder*2); nWidthDiff = nAfterWidth - this.nWidth; //미세한 차이에 크기 변화는 무시. if( -1 <= nWidthDiff && nWidthDiff <= 1){ nRatio = this.nWidth/this.nHeight; nAfterWidth = nRatio * nAfterheight; }else{ nRatio = this.nHeight/this.nWidth; nAfterheight = nRatio * nAfterWidth; } this.elImg.style.width = nAfterWidth + "px"; this.elImg.style.height = nAfterheight + "px"; this.elImg.setAttribute("width", nAfterWidth ); this.elImg.setAttribute("height", nAfterheight); // [SMARTEDITORSUS-299] 마우스 Drag로 이미지 크기 리사이즈 시, 삽입할 때의 저장 사이즈(rwidth/rheight)도 변경해 줌 this.elImg.style.rwidth = this.elImg.style.width; this.elImg.style.rheight = this.elImg.style.height; this.elImg.setAttribute("rwidth", this.elImg.getAttribute("width")); this.elImg.setAttribute("rheight", this.elImg.getAttribute("height")); // 아래의 부분은 추후 hp_SE2M_ImgSizeAdjustUtil.js 를 생성하여 분리한다. var bAdjustpossible = this._isAdjustPossible(this.elImg.offsetWidth); if(!bAdjustpossible){ this.elImg.style.width = this.nWidth; this.elImg.style.height = this.nHeight; this.elImg.style.rwidth = this.elImg.style.width; this.elImg.style.rheight = this.elImg.style.height; this.elImg.setAttribute("width", this.nWidth); this.elImg.setAttribute("height", this.nHeight); this.elImg.setAttribute("rwidth", this.elImg.getAttribute("width")); this.elImg.setAttribute("rheight", this.elImg.getAttribute("height")); } this.oApp.delayedExec("SET_RESIZE_TARGET_IMG", [this.elImg], 0); }, _isAdjustPossible : function(width){ var bPossible = true; // 가로폭 적용하는 경우에만 에디터 본문 안에 보이는 이미지 사이즈를 조절함 var bRulerUse = (this.oApp.htOptions['SE2M_EditingAreaRuler']) ? this.oApp.htOptions['SE2M_EditingAreaRuler'].bUse : false; if(bRulerUse){ var welWysiwygBody = jindo.$Element(this.oApp.getWYSIWYGDocument().body); if(welWysiwygBody){ var nEditorWidth = welWysiwygBody.width(); if(width > nEditorWidth){ bPossible = false; alert(this.oApp.$MSG("SE2M_ImgSizeRatioKeeper.exceedMaxWidth").replace("#EditorWidth#", nEditorWidth)); } } } return bPossible; } });
JavaScript
/*[ * SHOW_DIALOG_LAYER * * 다이얼로그 레이어를 화면에 보여준다. * * oLayer HTMLElement 다이얼로그 레이어로 사용 할 HTML 엘리먼트 * ---------------------------------------------------------------------------]*/ /*[ * HIDE_DIALOG_LAYER * * 다이얼로그 레이어를 화면에 숨긴다. * * oLayer HTMLElement 숨길 다이얼로그 레이어에 해당 하는 HTML 엘리먼트 * ---------------------------------------------------------------------------]*/ /*[ * HIDE_LAST_DIALOG_LAYER * * 마지막으로 화면에 표시한 다이얼로그 레이어를 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /*[ * HIDE_ALL_DIALOG_LAYER * * 표시 중인 모든 다이얼로그 레이어를 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 드래그가 가능한 레이어를 컨트롤 하는 플러그인 */ nhn.husky.DialogLayerManager = jindo.$Class({ name : "DialogLayerManager", aMadeDraggable : null, aOpenedLayers : null, $init : function(){ this.aMadeDraggable = []; this.aDraggableLayer = []; this.aOpenedLayers = []; }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); }, //@lazyload_js SHOW_DIALOG_LAYER,TOGGLE_DIALOG_LAYER:N_DraggableLayer.js[ $ON_SHOW_DIALOG_LAYER : function(elLayer, htOptions){ elLayer = jindo.$(elLayer); htOptions = htOptions || {}; if(!elLayer){return;} if(jindo.$A(this.aOpenedLayers).has(elLayer)){return;} this.oApp.exec("POSITION_DIALOG_LAYER", [elLayer]); this.aOpenedLayers[this.aOpenedLayers.length] = elLayer; var oDraggableLayer; var nIdx = jindo.$A(this.aMadeDraggable).indexOf(elLayer); if(nIdx == -1){ oDraggableLayer = new nhn.DraggableLayer(elLayer, htOptions); this.aMadeDraggable[this.aMadeDraggable.length] = elLayer; this.aDraggableLayer[this.aDraggableLayer.length] = oDraggableLayer; }else{ if(htOptions){ oDraggableLayer = this.aDraggableLayer[nIdx]; oDraggableLayer.setOptions(htOptions); } elLayer.style.display = "block"; } if(htOptions.sOnShowMsg){ this.oApp.exec(htOptions.sOnShowMsg, htOptions.sOnShowParam); } }, $ON_HIDE_LAST_DIALOG_LAYER : function(){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.aOpenedLayers[this.aOpenedLayers.length-1]]); }, $ON_HIDE_ALL_DIALOG_LAYER : function(){ for(var i=this.aOpenedLayers.length-1; i>=0; i--){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.aOpenedLayers[i]]); } }, $ON_HIDE_DIALOG_LAYER : function(elLayer){ elLayer = jindo.$(elLayer); if(elLayer){elLayer.style.display = "none";} this.aOpenedLayers = jindo.$A(this.aOpenedLayers).refuse(elLayer).$value(); if(!!this.oNavigator.msafari){ this.oApp.getWYSIWYGWindow().focus(); } }, $ON_TOGGLE_DIALOG_LAYER : function(elLayer, htOptions){ if(jindo.$A(this.aOpenedLayers).indexOf(elLayer)){ this.oApp.exec("SHOW_DIALOG_LAYER", [elLayer, htOptions]); }else{ this.oApp.exec("HIDE_DIALOG_LAYER", [elLayer]); } }, $ON_SET_DIALOG_LAYER_POSITION : function(elLayer, nTop, nLeft){ elLayer.style.top = nTop; elLayer.style.left = nLeft; } //@lazyload_js] });
JavaScript
/*[ * TOGGLE_ACTIVE_LAYER * * 액티브 레이어가 화면에 보이는 여부를 토글 한다. * * oLayer HTMLElement 레이어로 사용할 HTML Element * sOnOpenCmd string 화면에 보이는 경우 발생 할 메시지(옵션) * aOnOpenParam array sOnOpenCmd와 함께 넘겨줄 파라미터(옵션) * sOnCloseCmd string 해당 레이어가 화면에서 숨겨질 때 발생 할 메시지(옵션) * aOnCloseParam array sOnCloseCmd와 함께 넘겨줄 파라미터(옵션) * ---------------------------------------------------------------------------]*/ /*[ * SHOW_ACTIVE_LAYER * * 액티브 레이어가 화면에 보이는 여부를 토글 한다. * * oLayer HTMLElement 레이어로 사용할 HTML Element * sOnCloseCmd string 해당 레이어가 화면에서 숨겨질 때 발생 할 메시지(옵션) * aOnCloseParam array sOnCloseCmd와 함께 넘겨줄 파라미터(옵션) * ---------------------------------------------------------------------------]*/ /*[ * HIDE_ACTIVE_LAYER * * 현재 화면에 보이는 액티브 레이어를 화면에서 숨긴다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc 한번에 한개만 화면에 보여야 하는 레이어를 관리하는 플러그인 */ nhn.husky.ActiveLayerManager = jindo.$Class({ name : "ActiveLayerManager", oCurrentLayer : null, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); }, $ON_TOGGLE_ACTIVE_LAYER : function(oLayer, sOnOpenCmd, aOnOpenParam, sOnCloseCmd, aOnCloseParam){ if(oLayer == this.oCurrentLayer){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }else{ this.oApp.exec("SHOW_ACTIVE_LAYER", [oLayer, sOnCloseCmd, aOnCloseParam]); if(sOnOpenCmd){this.oApp.exec(sOnOpenCmd, aOnOpenParam);} } }, $ON_SHOW_ACTIVE_LAYER : function(oLayer, sOnCloseCmd, aOnCloseParam){ oLayer = jindo.$(oLayer); var oPrevLayer = this.oCurrentLayer; if(oLayer == oPrevLayer){return;} this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.sOnCloseCmd = sOnCloseCmd; this.aOnCloseParam = aOnCloseParam; oLayer.style.display = "block"; this.oCurrentLayer = oLayer; this.oApp.exec("ADD_APP_PROPERTY", ["oToolBarLayer", this.oCurrentLayer]); }, $ON_HIDE_ACTIVE_LAYER : function(){ var oLayer = this.oCurrentLayer; if(!oLayer){return;} oLayer.style.display = "none"; this.oCurrentLayer = null; if(this.sOnCloseCmd){ this.oApp.exec(this.sOnCloseCmd, this.aOnCloseParam); } if(!!this.oNavigator.msafari){ this.oApp.getWYSIWYGWindow().focus(); } }, $ON_HIDE_ACTIVE_LAYER_IF_NOT_CHILD : function(el){ var elTmp = el; while(elTmp){ if(elTmp == this.oCurrentLayer){ return; } elTmp = elTmp.parentNode; } this.oApp.exec("HIDE_ACTIVE_LAYER"); }, // for backward compatibility only. // use HIDE_ACTIVE_LAYER instead! $ON_HIDE_CURRENT_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); } });
JavaScript
if(typeof window.nhn == 'undefined') { window.nhn = {}; } if(!nhn.husky) { nhn.husky = {}; } nhn.husky.SE2M_UtilPlugin = jindo.$Class({ name : "SE2M_UtilPlugin", $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["oAgent", jindo.$Agent()]); this.oApp.exec("ADD_APP_PROPERTY", ["oNavigator", jindo.$Agent().navigator()]); this.oApp.exec("ADD_APP_PROPERTY", ["oUtils", this]); }, $ON_REGISTER_HOTKEY : function(sHotkey, sCMD, aArgs, elTarget) { this.oApp.exec("ADD_HOTKEY", [sHotkey, sCMD, aArgs, (elTarget || this.oApp.getWYSIWYGDocument())]); }, $ON_SE2_ATTACH_HOVER_EVENTS : function(aElms){ this.oApp.exec("ATTACH_HOVER_EVENTS", [aElms, {fnElmToSrc: this._elm2Src, fnElmToTarget: this._elm2Target}]); }, _elm2Src : function(el){ if(el.tagName == "LI" && el.firstChild && el.firstChild.tagName == "BUTTON"){ return el.firstChild; }else{ return el; } }, _elm2Target : function(el){ if(el.tagName == "BUTTON" && el.parentNode.tagName == "LI"){ return el.parentNode; }else{ return el; } }, getScrollXY : function(){ var scrollX,scrollY; var oAppWindow = this.oApp.getWYSIWYGWindow(); if(typeof oAppWindow.scrollX == "undefined"){ scrollX = oAppWindow.document.documentElement.scrollLeft; scrollY = oAppWindow.document.documentElement.scrollTop; }else{ scrollX = oAppWindow.scrollX; scrollY = oAppWindow.scrollY; } return {x:scrollX, y:scrollY}; } }); nhn.husky.SE2M_Utils = { sURLPattern : '(http|https|ftp|mailto):(?:\\/\\/)?((:?\\w|-)+(:?\\.(:?\\w|-)+)+)([^ <>]+)?', /** * 사용자 클래스 정보를 추출한다. * @param {String} sStr 추출 String * @param {rx} rxValue rx type 형식의 값 * @param {String} sDivision value의 split 형식 * @return {Array} */ getCustomCSS : function(sStr, rxValue, sDivision) { var ret = []; if('undefined' == typeof(sStr) || 'undefined' == typeof(rxValue) || !sStr || !rxValue) { return ret; } var aMatch = sStr.match(rxValue); if(aMatch && aMatch[0]&&aMatch[1]) { if(sDivision) { ret = aMatch[1].split(sDivision); } else { ret[0] = aMatch[1]; } } return ret; }, /** * HashTable로 구성된 Array의 같은 프로퍼티를 sSeperator 로 구분된 String 값으로 변환 * @param {Object} v * @param {Object} sKey * @author senxation * @example a = [{ b : "1" }, { b : "2" }] toStringSamePropertiesOfArray(a, "b", ", "); ==> "1, 2" */ toStringSamePropertiesOfArray : function(v, sKey, sSeperator) { if (v instanceof Array) { var a = []; for (var i = 0; i < v.length; i++) { a.push(v[i][sKey]); } return a.join(",").replace(/,/g, sSeperator); } else { if (typeof v[sKey] == "undefined") { return ""; } if (typeof v[sKey] == "string") { return v[sKey]; } } }, /** * 단일 객체를 배열로 만들어줌 * @param {Object} v * @return {Array} * @author senxation * @example makeArray("test"); ==> ["test"] */ makeArray : function(v) { if (v === null || typeof v === "undefined"){ return []; } if (v instanceof Array) { return v; } var a = []; a.push(v); return a; }, /** * 말줄임을 할때 줄일 내용과 컨테이너가 다를 경우 처리 * 컨테이너의 css white-space값이 "normal"이어야한다. (컨테이너보다 텍스트가 길면 여러행으로 표현되는 상태) * @param {HTMLElement} elText 말줄임할 엘리먼트 * @param {HTMLElement} elContainer 말줄임할 엘리먼트를 감싸는 컨테이너 * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Number} nLine 최대 라인수 (미지정시 1) * @author senxation * @example //div가 2줄 이하가 되도록 strong 내부의 내용을 줄임 <div> <strong id="a">말줄임을적용할내용말줄임을적용할내용말줄임을적용할내용</strong><span>상세보기</span> <div> ellipsis(jindo.$("a"), jindo.$("a").parentNode, "...", 2); */ ellipsis : function(elText, elContainer, sStringTail, nLine) { sStringTail = sStringTail || "..."; if (typeof nLine == "undefined") { nLine = 1; } var welText = jindo.$Element(elText); var welContainer = jindo.$Element(elContainer); var sText = welText.html(); var nLength = sText.length; var nCurrentHeight = welContainer.height(); var nIndex = 0; welText.html('A'); var nHeight = welContainer.height(); if (nCurrentHeight < nHeight * (nLine + 0.5)) { return welText.html(sText); } /** * 지정된 라인보다 커질때까지 전체 남은 문자열의 절반을 더해나감 */ nCurrentHeight = nHeight; while(nCurrentHeight < nHeight * (nLine + 0.5)) { nIndex += Math.max(Math.ceil((nLength - nIndex)/2), 1); welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentHeight = welContainer.height(); } /** * 지정된 라인이 될때까지 한글자씩 잘라냄 */ while(nCurrentHeight > nHeight * (nLine + 0.5)) { nIndex--; welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentHeight = welContainer.height(); } }, /** * 최대 가로사이즈를 지정하여 말줄임한다. * elText의 css white-space값이 "nowrap"이어야한다. (컨테이너보다 텍스트가 길면 행변환되지않고 가로로 길게 표현되는 상태) * @param {HTMLElement} elText 말줄임할 엘리먼트 * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Function} fCondition 조건 함수. 내부에서 true를 리턴하는 동안에만 말줄임을 진행한다. * @author senxation * @example //150픽셀 이하가 되도록 strong 내부의 내용을 줄임 <strong id="a">말줄임을적용할내용말줄임을적용할내용말줄임을적용할내용</strong>> ellipsisByPixel(jindo.$("a"), "...", 150); */ ellipsisByPixel : function(elText, sStringTail, nPixel, fCondition) { sStringTail = sStringTail || "..."; var welText = jindo.$Element(elText); var nCurrentWidth = welText.width(); if (nCurrentWidth < nPixel) { return; } var sText = welText.html(); var nLength = sText.length; var nIndex = 0; if (typeof fCondition == "undefined") { var nWidth = welText.html('A').width(); nCurrentWidth = nWidth; while(nCurrentWidth < nPixel) { nIndex += Math.max(Math.ceil((nLength - nIndex)/2), 1); welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentWidth = welText.width(); } fCondition = function() { return true; }; } nIndex = welText.html().length - sStringTail.length; while(nCurrentWidth > nPixel) { if (!fCondition()) { break; } nIndex--; welText.html(sText.substring(0, nIndex) + sStringTail); nCurrentWidth = welText.width(); } }, /** * 여러개의 엘리먼트를 각각의 지정된 최대너비로 말줄임한다. * 말줄임할 엘리먼트의 css white-space값이 "nowrap"이어야한다. (컨테이너보다 텍스트가 길면 행변환되지않고 가로로 길게 표현되는 상태) * @param {Array} aElement 말줄임할 엘리먼트의 배열. 지정된 순서대로 말줄임한다. * @param {String} sStringTail 말줄임을 표현할 문자열 (미지정시 ...) * @param {Array} aMinWidth 말줄임할 너비의 배열. * @param {Function} fCondition 조건 함수. 내부에서 true를 리턴하는 동안에만 말줄임을 진행한다. * @example //#a #b #c의 너비를 각각 100, 50, 50픽셀로 줄임 (div#parent 가 200픽셀 이하이면 중단) //#c의 너비를 줄이는 동안 fCondition에서 false를 리턴하면 b, a는 말줄임 되지 않는다. <div id="parent"> <strong id="a">말줄임을적용할내용</strong> <strong id="b">말줄임을적용할내용</strong> <strong id="c">말줄임을적용할내용</strong> <div> ellipsisElementsToDesinatedWidth([jindo.$("c"), jindo.$("b"), jindo.$("a")], "...", [100, 50, 50], function(){ if (jindo.$Element("parent").width() > 200) { return true; } return false; }); */ ellipsisElementsToDesinatedWidth : function(aElement, sStringTail, aMinWidth, fCondition) { jindo.$A(aElement).forEach(function(el, i){ if (!el) { jindo.$A.Continue(); } nhn.husky.SE2M_Utils.ellipsisByPixel(el, sStringTail, aMinWidth[i], fCondition); }); }, /** * 숫자를 입력받아 정해진 길이만큼 앞에 "0"이 추가된 문자열을 구한다. * @param {Number} nNumber * @param {Number} nLength * @return {String} * @example paddingZero(10, 5); ==> "00010" (String) */ paddingZero : function(nNumber, nLength) { var sResult = nNumber.toString(); while (sResult.length < nLength) { sResult = ("0" + sResult); } return sResult; }, /** * string을 byte 단위로 짤라서 tail를 붙힌다. * @param {String} sString * @param {Number} nByte * @param {String} sTail * @example cutStringToByte('일이삼사오육', 6, '...') ==> '일이삼...' (string) */ cutStringToByte : function(sString, nByte, sTail){ if(sString === null || sString.length === 0) { return sString; } sString = sString.replace(/ +/g, " "); if (!sTail && sTail != "") { sTail = "..."; } var maxByte = nByte; var n=0; var nLen = sString.length; for(var i=0; i<nLen;i++){ n += this.getCharByte(sString.charAt(i)); if(n == maxByte){ if(i == nLen-1) { return sString; } else { return sString.substring(0,i)+sTail; } } else if( n > maxByte ) { return sString.substring(0, i)+sTail; } } return sString; }, /** * 입력받은 문자의 byte 구한다. * @param {String} ch * */ getCharByte : function(ch){ if (ch === null || ch.length < 1) { return 0; } var byteSize = 0; var str = escape(ch); if ( str.length == 1 ) { // when English then 1byte byteSize ++; } else if ( str.indexOf("%u") != -1 ) { // when Korean then 2byte byteSize += 2; } else if ( str.indexOf("%") != -1 ) { // else 3byte byteSize += str.length/3; } return byteSize; }, /** * Hash Table에서 원하는 키값만을 가지는 필터된 새로운 Hash Table을 구한다. * @param {HashTable} htUnfiltered * @param {Array} aKey * @return {HashTable} * @author senxation * @example getFilteredHashTable({ a : 1, b : 2, c : 3, d : 4 }, ["a", "c"]); ==> { a : 1, c : 3 } */ getFilteredHashTable : function(htUnfiltered, vKey) { if (!(vKey instanceof Array)) { return arguments.callee.call(this, htUnfiltered, [ vKey ]); } var waKey = jindo.$A(vKey); return jindo.$H(htUnfiltered).filter(function(vValue, sKey){ if (waKey.has(sKey) && vValue) { return true; } else { return false; } }).$value(); }, isBlankNode : function(elNode){ var isBlankTextNode = this.isBlankTextNode; var bEmptyContent = function(elNode){ if(!elNode) { return true; } if(isBlankTextNode(elNode)){ return true; } if(elNode.tagName == "BR") { return true; } if(elNode.innerHTML == "&nbsp;" || elNode.innerHTML == "") { return true; } return false; }; var bEmptyP = function(elNode){ if(bEmptyContent(elNode)){ return true; } if(elNode.tagName == "P"){ for(var i=elNode.childNodes.length-1; i>=0; i--){ var elTmp = elNode.childNodes[i]; if(isBlankTextNode(elTmp)){ elTmp.parentNode.removeChild(elTmp); } } if(elNode.childNodes.length == 1 && bEmptyContent(elNode.firstChild)){ return true; } } return false; }; if(bEmptyP(elNode)){ return true; } for(var i=0, nLen=elNode.childNodes.length; i<nLen; i++){ var elTmp = elNode.childNodes[i]; if(!bEmptyP(elTmp)){ return false; } } return true; }, isBlankTextNode : function(oNode){ var sText; if(oNode.nodeType == 3){ sText = oNode.nodeValue; sText = sText.replace(unescape("%uFEFF"), ''); if(sText == "") { return true; } } return false; }, /** * elNode의 상위 노드 중 태그명이 sTagName과 일치하는 것이 있다면 반환. * @param {String} sTagName 검색 할 태그명 * @param {HTMLElement} elNode 검색 시작점으로 사용 할 노드 * @return {HTMLElement} 부모 노드 중 태그명이 sTagName과 일치하는 노드. 없을 경우 null 반환 */ findAncestorByTagName : function(sTagName, elNode){ while(elNode && elNode.tagName != sTagName) { elNode = elNode.parentNode; } return elNode; }, loadCSS : function(url, fnCallback){ var oDoc = document; var elHead = oDoc.getElementsByTagName("HEAD")[0]; var elStyle = oDoc.createElement ("LINK"); elStyle.setAttribute("type", "text/css"); elStyle.setAttribute("rel", "stylesheet"); elStyle.setAttribute("href", url); if(fnCallback){ elStyle.onreadystatechange = function(){ if(elStyle.readyState != "complete"){ return; } // [SMARTEDITORSUS-308] [IE9] 응답이 304인 경우 // onreadystatechage 핸들러에서 readyState 가 complete 인 경우가 두 번 발생 // LINK 엘리먼트의 속성으로 콜백 실행 여부를 플래그로 남겨놓아 처리함 if(elStyle.getAttribute("_complete")){ return; } elStyle.setAttribute("_complete", true); fnCallback(); }; } elHead.appendChild (elStyle); }, getUniqueId : function(sPrefix) { return (sPrefix || '') + jindo.$Date().time() + (Math.random() * 100000).toFixed(); }, /** * @param {Object} oSrc value copy할 object * @return {Object} * @example * var oSource = [1, 3, 4, { a:1, b:2, c: { a:1 }}]; var oTarget = oSource; // call by reference oTarget = nhn.husky.SE2M_Utils.clone(oSource); oTarget[1] = 2; oTarget[3].a = 100; console.log(oSource); // check for deep copy console.log(oTarget, oTarget instanceof Object); // check instance type! */ clone : function(oSrc, oChange) { if ('undefined' != typeof(oSrc) && !!oSrc && (oSrc.constructor == Array || oSrc.constructor == Object)) { var oCopy = (oSrc.constructor == Array ? [] : {} ); for (var property in oSrc) { if ('undefined' != typeof(oChange) && !!oChange[property]) { oCopy[property] = arguments.callee(oChange[property]); } else { oCopy[property] = arguments.callee(oSrc[property]); } } return oCopy; } return oSrc; }, getHtmlTagAttr : function(sHtmlTag, sAttr) { var rx = new RegExp('\\s' + sAttr + "=('([^']*)'|\"([^\"]*)\"|([^\"' >]*))", 'i'); var aResult = rx.exec(sHtmlTag); if (!aResult) { return ''; } var sAttrTmp = (aResult[1] || aResult[2] || aResult[3]); // for chrome 5.x bug! if (!!sAttrTmp) { sAttrTmp = sAttrTmp.replace(/[\"]/g, ''); } return sAttrTmp; }, /** * iframe 영역의 aling 정보를 다시 세팅하는 부분. * iframe 형태의 산출물을 에디터에 삽입 이후에 에디터 정렬기능을 추가 하였을때 ir_to_db 이전 시점에서 div태그에 정렬을 넣어주는 로직임. * 브라우저 형태에 따라 정렬 태그가 iframe을 감싸는 div 혹은 p 태그에 정렬이 추가된다. * @param {HTMLElement} el iframe의 parentNode * @param {Document} oDoc document */ // [COM-1151] SE2M_PreStringConverter 에서 수정하도록 변경 iframeAlignConverter : function(el, oDoc){ var sTagName = el.tagName.toUpperCase(); if(sTagName == "DIV" || sTagName == 'P'){ //irToDbDOM 에서 최상위 노드가 div 엘리먼트 이므로 parentNode가 없으면 최상의 div 노드 이므로 리턴한다. if(el.parentNode === null ){ return; } var elWYSIWYGDoc = oDoc; var wel = jindo.$Element(el); var sHtml = wel.html(); //현재 align을 얻어오기. var sAlign = jindo.$Element(el).attr('align') || jindo.$Element(el).css('text-align'); //if(!sAlign){ // P > DIV의 경우 문제 발생, 수정 화면에 들어 왔을 때 태그 깨짐 // return; //} //새로운 div 노드 생성한다. var welAfter = jindo.$Element(jindo.$('<div></div>', elWYSIWYGDoc)); welAfter.html(sHtml).attr('align', sAlign); wel.replace(welAfter); } }, /** * jindo.$JSON.fromXML을 변환한 메서드. * 소숫점이 있는 경우의 처리 시에 숫자로 변환하지 않도록 함(parseFloat 사용 안하도록 수정) * 관련 BTS : [COM-1093] * @param {String} sXML XML 형태의 문자열 * @return {jindo.$JSON} */ getJsonDatafromXML : function(sXML) { var o = {}; var re = /\s*<(\/?[\w:\-]+)((?:\s+[\w:\-]+\s*=\s*(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'))*)\s*((?:\/>)|(?:><\/\1>|\s*))|\s*<!\[CDATA\[([\w\W]*?)\]\]>\s*|\s*>?([^<]*)/ig; var re2= /^[0-9]+(?:\.[0-9]+)?$/; var ec = {"&amp;":"&","&nbsp;":" ","&quot;":"\"","&lt;":"<","&gt;":">"}; var fg = {tags:["/"],stack:[o]}; var es = function(s){ if (typeof s == "undefined") { return ""; } return s.replace(/&[a-z]+;/g, function(m){ return (typeof ec[m] == "string")?ec[m]:m; }); }; var at = function(s,c) { s.replace(/([\w\:\-]+)\s*=\s*(?:"((?:\\"|[^"])*)"|'((?:\\'|[^'])*)')/g, function($0,$1,$2,$3) { c[$1] = es(($2?$2.replace(/\\"/g,'"'):undefined)||($3?$3.replace(/\\'/g,"'"):undefined)); }); }; var em = function(o) { for(var x in o){ if (o.hasOwnProperty(x)) { if(Object.prototype[x]) { continue; } return false; } } return true; }; // $0 : 전체 // $1 : 태그명 // $2 : 속성문자열 // $3 : 닫는태그 // $4 : CDATA바디값 // $5 : 그냥 바디값 var cb = function($0,$1,$2,$3,$4,$5) { var cur, cdata = ""; var idx = fg.stack.length - 1; if (typeof $1 == "string" && $1) { if ($1.substr(0,1) != "/") { var has_attr = (typeof $2 == "string" && $2); var closed = (typeof $3 == "string" && $3); var newobj = (!has_attr && closed)?"":{}; cur = fg.stack[idx]; if (typeof cur[$1] == "undefined") { cur[$1] = newobj; cur = fg.stack[idx+1] = cur[$1]; } else if (cur[$1] instanceof Array) { var len = cur[$1].length; cur[$1][len] = newobj; cur = fg.stack[idx+1] = cur[$1][len]; } else { cur[$1] = [cur[$1], newobj]; cur = fg.stack[idx+1] = cur[$1][1]; } if (has_attr) { at($2,cur); } fg.tags[idx+1] = $1; if (closed) { fg.tags.length--; fg.stack.length--; } } else { fg.tags.length--; fg.stack.length--; } } else if (typeof $4 == "string" && $4) { cdata = $4; } else if (typeof $5 == "string" && $5) { cdata = es($5); } if (cdata.length > 0) { var par = fg.stack[idx-1]; var tag = fg.tags[idx]; if (re2.test(cdata)) { //cdata = parseFloat(cdata); }else if (cdata == "true" || cdata == "false"){ cdata = new Boolean(cdata); } if(typeof par =='undefined') { return; } if (par[tag] instanceof Array) { var o = par[tag]; if (typeof o[o.length-1] == "object" && !em(o[o.length-1])) { o[o.length-1].$cdata = cdata; o[o.length-1].toString = function(){ return cdata; }; } else { o[o.length-1] = cdata; } } else { if (typeof par[tag] == "object" && !em(par[tag])) { par[tag].$cdata = cdata; par[tag].toString = function() { return cdata; }; } else { par[tag] = cdata; } } } }; sXML = sXML.replace(/<(\?|\!-)[^>]*>/g, ""); sXML.replace(re, cb); return jindo.$Json(o); } }; /** * nhn.husky.AutoResizer * HTML모드와 TEXT 모드의 편집 영역인 TEXTAREA에 대한 자동확장 처리 */ nhn.husky.AutoResizer = jindo.$Class({ welHiddenDiv : null, welCloneDiv : null, elContainer : null, $init : function(el, htOption){ var aCopyStyle = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'paddingTop', 'paddingLeft', 'paddingBottom', 'paddingRight', 'width' ], i = aCopyStyle.length, oCss = { "position" : "absolute", "top" : -9999, "left" : -9999, "opacity": 0, "overflow": "hidden", "wordWrap" : "break-word" }; this.nMinHeight = htOption.nMinHeight; this.wfnCallback = htOption.wfnCallback; this.elContainer = el.parentNode; this.welTextArea = jindo.$Element(el); // autoresize를 적용할 TextArea this.welHiddenDiv = jindo.$Element('<div>'); this.wfnResize = jindo.$Fn(this._resize, this); this.sOverflow = this.welTextArea.css("overflow"); this.welTextArea.css("overflow", "hidden"); while(i--){ oCss[aCopyStyle[i]] = this.welTextArea.css(aCopyStyle[i]); } this.welHiddenDiv.css(oCss); this.nLastHeight = this.welTextArea.height(); }, bind : function(){ this.welCloneDiv = jindo.$Element(this.welHiddenDiv.$value().cloneNode(false)); this.wfnResize.attach(this.welTextArea, "keyup"); this.welCloneDiv.appendTo(this.elContainer); this._resize(); }, unbind : function(){ this.wfnResize.detach(this.welTextArea, "keyup"); this.welTextArea.css("overflow", this.sOverflow); if(this.welCloneDiv){ this.welCloneDiv.leave(); } }, _resize : function(){ var sContents = this.welTextArea.$value().value, bExpand = false, nHeight; if(sContents === this.sContents){ return; } this.sContents = sContents.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\n/g, '<br>'); this.sContents += "<br>"; // 마지막 개행 뒤에 <br>을 더 붙여주어야 늘어나는 높이가 동일함 this.welCloneDiv.html(this.sContents); nHeight = this.welCloneDiv.height(); if(nHeight < this.nMinHeight){ nHeight = this.nMinHeight; } this.welTextArea.css("height", nHeight + "px"); this.elContainer.style.height = nHeight + "px"; if(this.nLastHeight < nHeight){ bExpand = true; } this.wfnCallback(bExpand); } }); /** * 문자를 연결하는 '+' 대신에 java와 유사하게 처리하도록 문자열 처리하도록 만드는 object * @author nox * @example var sTmp1 = new StringBuffer(); sTmp1.append('1').append('2').append('3'); var sTmp2 = new StringBuffer('1'); sTmp2.append('2').append('3'); var sTmp3 = new StringBuffer('1').append('2').append('3'); */ if ('undefined' != typeof(StringBuffer)) { StringBuffer = {}; } StringBuffer = function(str) { this._aString = []; if ('undefined' != typeof(str)) { this.append(str); } }; StringBuffer.prototype.append = function(str) { this._aString.push(str); return this; }; StringBuffer.prototype.toString = function() { return this._aString.join(''); }; StringBuffer.prototype.setLength = function(nLen) { if('undefined' == typeof(nLen) || 0 >= nLen) { this._aString.length = 0; } else { this._aString.length = nLen; } }; /** * Installed Font Detector * @author hooriza * * @see http://remysharp.com/2008/07/08/how-to-detect-if-a-font-is-installed-only-using-javascript/ */ (function() { var oDummy = null; IsInstalledFont = function(sFont) { var sDefFont = sFont == 'Comic Sans MS' ? 'Courier New' : 'Comic Sans MS'; if (!oDummy) { oDummy = document.createElement('div'); } var sStyle = 'position:absolute !important; font-size:200px !important; left:-9999px !important; top:-9999px !important;'; oDummy.innerHTML = 'mmmmiiiii'+unescape('%uD55C%uAE00'); oDummy.style.cssText = sStyle + 'font-family:"' + sDefFont + '" !important'; var elBody = document.body || document.documentElement; if(elBody.firstChild){ elBody.insertBefore(oDummy, elBody.firstChild); }else{ document.body.appendChild(oDummy); } var sOrg = oDummy.offsetWidth + '-' + oDummy.offsetHeight; oDummy.style.cssText = sStyle + 'font-family:"' + sFont + '", "' + sDefFont + '" !important'; var bInstalled = sOrg != (oDummy.offsetWidth + '-' + oDummy.offsetHeight); document.body.removeChild(oDummy); return bInstalled; }; })();
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to string conversion. Ususally used to convert the IR value. * @name hp_StringConverterManager.js */ nhn.husky.StringConverterManager = jindo.$Class({ name : "StringConverterManager", oConverters : null, $init : function(){ this.oConverters = {}; this.oConverters_DOM = {}; }, $BEFORE_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["applyConverter", jindo.$Fn(this.applyConverter, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addConverter", jindo.$Fn(this.addConverter, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addConverter_DOM", jindo.$Fn(this.addConverter_DOM, this).bind()]); }, applyConverter : function(sRuleName, sContents, oDocument){ //string을 넣는 이유:IE의 경우,본문 앞에 있는 html 주석이 삭제되는 경우가 있기때문에 임시 string을 추가해준것임. var sTmpStr = "@"+(new Date()).getTime()+"@"; var rxTmpStr = new RegExp(sTmpStr, "g"); var oRes = {sContents:sTmpStr+sContents}; oDocument = oDocument || document; this.oApp.exec("MSG_STRING_CONVERTER_STARTED", [sRuleName, oRes]); // this.oApp.exec("MSG_STRING_CONVERTER_STARTED_"+sRuleName, [oRes]); var aConverters; sContents = oRes.sContents; aConverters = this.oConverters_DOM[sRuleName]; if(aConverters){ var elContentsHolder = oDocument.createElement("DIV"); elContentsHolder.innerHTML = sContents; for(var i=0; i<aConverters.length; i++){ aConverters[i](elContentsHolder); } sContents = elContentsHolder.innerHTML; // 내용물에 EMBED등이 있을 경우 IE에서 페이지 나갈 때 권한 오류 발생 할 수 있어 명시적으로 노드 삭제. elContentsHolder.innerHTML = ""; //IE의 경우, sContents를 innerHTML로 넣는 경우 string과 <p>tag 사이에 '\n\'개행문자를 넣어준다. if( jindo.$Agent().navigator().ie ){ sTmpStr = sTmpStr +'(\r\n)?'; //ie+win에서는 개행이 \r\n로 들어감. rxTmpStr = new RegExp(sTmpStr , "g"); } } aConverters = this.oConverters[sRuleName]; if(aConverters){ for(var i=0; i<aConverters.length; i++){ var sTmpContents = aConverters[i](sContents); if(typeof sTmpContents != "undefined"){ sContents = sTmpContents; } } } oRes = {sContents:sContents}; this.oApp.exec("MSG_STRING_CONVERTER_ENDED", [sRuleName, oRes]); oRes.sContents = oRes.sContents.replace(rxTmpStr, ""); return oRes.sContents; }, $ON_ADD_CONVERTER : function(sRuleName, funcConverter){ var aCallerStack = this.oApp.aCallerStack; funcConverter.sPluginName = aCallerStack[aCallerStack.length-2].name; this.addConverter(sRuleName, funcConverter); }, $ON_ADD_CONVERTER_DOM : function(sRuleName, funcConverter){ var aCallerStack = this.oApp.aCallerStack; funcConverter.sPluginName = aCallerStack[aCallerStack.length-2].name; this.addConverter_DOM(sRuleName, funcConverter); }, addConverter : function(sRuleName, funcConverter){ var aConverters = this.oConverters[sRuleName]; if(!aConverters){ this.oConverters[sRuleName] = []; } this.oConverters[sRuleName][this.oConverters[sRuleName].length] = funcConverter; }, addConverter_DOM : function(sRuleName, funcConverter){ var aConverters = this.oConverters_DOM[sRuleName]; if(!aConverters){ this.oConverters_DOM[sRuleName] = []; } this.oConverters_DOM[sRuleName][this.oConverters_DOM[sRuleName].length] = funcConverter; } }); //}
JavaScript
/** * @fileOverview This file contains Husky plugin that takes care of the operations related to quote * @name hp_SE_Quote.js * @required SE_EditingArea_WYSIWYG */ nhn.husky.SE2M_Quote = jindo.$Class({ name : "SE2M_Quote", htQuoteStyles_view : null, $init : function(){ var htConfig = nhn.husky.SE2M_Configuration.Quote || {}; var sImageBaseURL = htConfig.sImageBaseURL; this.nMaxLevel = htConfig.nMaxLevel || 14; this.htQuoteStyles_view = {}; this.htQuoteStyles_view["se2_quote1"] = "_zoom:1;padding:0 8px; margin:0 0 30px 20px; margin-right:15px; border-left:2px solid #cccccc;color:#888888;"; this.htQuoteStyles_view["se2_quote2"] = "_zoom:1;margin:0 0 30px 13px;padding:0 8px 0 16px;background:url("+sImageBaseURL+"/bg_quote2.gif) 0 3px no-repeat;color:#888888;"; this.htQuoteStyles_view["se2_quote3"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #cccccc;color:#888888;"; this.htQuoteStyles_view["se2_quote4"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #66b246;color:#888888;"; this.htQuoteStyles_view["se2_quote5"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px dashed #cccccc;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; this.htQuoteStyles_view["se2_quote6"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #e5e5e5;color:#888888;"; this.htQuoteStyles_view["se2_quote7"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #66b246;color:#888888;"; this.htQuoteStyles_view["se2_quote8"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:1px solid #e5e5e5;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; this.htQuoteStyles_view["se2_quote9"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:2px solid #e5e5e5;color:#888888;"; this.htQuoteStyles_view["se2_quote10"] = "_zoom:1;margin:0 0 30px 0;padding:10px;border:2px solid #e5e5e5;background:url("+sImageBaseURL+"/bg_b1.png) repeat;_background:none;_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+sImageBaseURL+"/bg_b1.png',sizingMethod='scale');color:#888888;"; }, _assignHTMLElements : function(){ //@ec this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_seditor_blockquote_layer", this.oApp.htOptions.elAppContainer); this.aLI = jindo.$$("LI", this.elDropdownLayer); }, $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER", ["DB_TO_IR", jindo.$Fn(function(sContents){ sContents = sContents.replace(/<(blockquote)[^>]*class=['"]?(se2_quote[0-9]+)['"]?[^>]*>/gi, "<$1 class=$2>"); return sContents; }, this).bind()]); this.oApp.exec("ADD_CONVERTER", ["IR_TO_DB", jindo.$Fn(function(sContents){ var htQuoteStyles_view = this.htQuoteStyles_view; sContents = sContents.replace(/<(blockquote)[^>]*class=['"]?(se2_quote[0-9]+)['"]?[^>]*>/gi, function(sAll, sTag, sClassName){ return '<'+sTag+' class='+sClassName+' style="'+htQuoteStyles_view[sClassName]+'">'; }); return sContents; }, this).bind()]); this.htSE1toSE2Map = { "01" : "1", "02" : "2", "03" : "6", "04" : "8", "05" : "9", "07" : "3", "08" : "5" }; // convert SE1's quotes to SE2's // -> 블로그 개발 쪽에서 처리 하기로 함. /* this.oApp.exec("ADD_CONVERTER", ["DB_TO_IR", jindo.$Fn(function(sContents){ return sContents.replace(/<blockquote[^>]* class="?vview_quote([0-9]+)"?[^>]*>((?:\s|.)*?)<\/blockquote>/ig, jindo.$Fn(function(m0,sQuoteType,sQuoteContents){ if (/<!--quote_txt-->((?:\s|.)*?)<!--\/quote_txt-->/ig.test(sQuoteContents)){ if(!this.htSE1toSE2Map[sQuoteType]){ return m0; } return '<blockquote class="se2_quote'+this.htSE1toSE2Map[sQuoteType]+'">'+RegExp.$1+'</blockquote>'; }else{ return ''; } }, this).bind()); }, this).bind()]); */ }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLElements(); this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "EVENT_SE2_BLOCKQUOTE_LAYER_CLICK", []); this.oApp.delayedExec("SE2_ATTACH_HOVER_EVENTS", [this.aLI], 0); }, $ON_MSG_APP_READY: function(){ this.oApp.exec("REGISTER_UI_EVENT", ["quote", "click", "TOGGLE_BLOCKQUOTE_LAYER"]); }, //@lazyload_js TOGGLE_BLOCKQUOTE_LAYER[ $ON_TOGGLE_BLOCKQUOTE_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "SELECT_UI", ["quote"], "DESELECT_UI", ["quote"]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['quote']); }, $ON_EVENT_SE2_BLOCKQUOTE_LAYER_CLICK : function(weEvent){ var elButton = nhn.husky.SE2M_Utils.findAncestorByTagName("BUTTON", weEvent.element); if(!elButton || elButton.tagName != "BUTTON"){return;} var sClass = elButton.className; this.oApp.exec("APPLY_BLOCKQUOTE", [sClass]); }, $ON_APPLY_BLOCKQUOTE : function(sClass){ if(sClass.match(/(se2_quote[0-9]+)/)){ this._wrapBlock("BLOCKQUOTE", RegExp.$1); }else{ this._unwrapBlock("BLOCKQUOTE"); } this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, /** * 인용구의 중첩 가능한 최대 개수를 넘었는지 확인함 * 인용구 내부에서 인용구를 적용하면 중첩되지 않으므로 자식노드에 대해서만 확인함 */ _isExceedMaxDepth : function(elNode){ var countChildQuote = function(elNode){ var elChild = elNode.firstChild; var nCount = 0; var nMaxCount = 0; if(!elChild){ if(elNode.tagName && elNode.tagName === "BLOCKQUOTE"){ return 1; }else{ return 0; } } while(elChild){ if(elChild.nodeType === 1){ nCount = countChildQuote(elChild); if(elChild.tagName === "BLOCKQUOTE"){ nCount += 1; } if(nMaxCount < nCount){ nMaxCount = nCount; } if(nMaxCount >= this.nMaxLevel){ return nMaxCount; } } elChild = elChild.nextSibling; } return nMaxCount; }; return (countChildQuote(elNode) >= this.nMaxLevel); }, _unwrapBlock : function(tag){ var oSelection = this.oApp.getSelection(); var elCommonAncestor = oSelection.commonAncestorContainer; while(elCommonAncestor && elCommonAncestor.tagName != tag){elCommonAncestor = elCommonAncestor.parentNode;} if(!elCommonAncestor){return;} this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["CANCEL BLOCK QUOTE", {sSaveTarget:"BODY"}]); while(elCommonAncestor.firstChild){elCommonAncestor.parentNode.insertBefore(elCommonAncestor.firstChild, elCommonAncestor);} elCommonAncestor.parentNode.removeChild(elCommonAncestor); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["CANCEL BLOCK QUOTE", {sSaveTarget:"BODY"}]); }, _wrapBlock : function(tag, className){ var oSelection, oLineInfo, oStart, oEnd, rxDontUseAsWhole = /BODY|TD|LI/i, oStartNode, oEndNode, oNode, elCommonAncestor, elCommonNode, elParentQuote, elInsertBefore, oFormattingNode, elNextNode, elParentNode, aQuoteChild, aQuoteCloneChild, i, nLen, oP, sBookmarkID; this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["BLOCK QUOTE", {sSaveTarget:"BODY"}]); oSelection = this.oApp.getSelection(); // var sBookmarkID = oSelection.placeStringBookmark(); // [SMARTEDITORSUS-430] 문자를 입력하고 Enter 후 인용구를 적용할 때 위의 문자들이 인용구 안에 들어가는 문제 if(oSelection.startContainer === oSelection.endContainer && oSelection.startContainer.nodeType === 1 && oSelection.startContainer.tagName === "P" && nhn.husky.SE2M_Utils.isBlankNode(oSelection.startContainer)){ oLineInfo = oSelection.getLineInfo(true); }else{ oLineInfo = oSelection.getLineInfo(false); } oStart = oLineInfo.oStart; oEnd = oLineInfo.oEnd; if(oStart.bParentBreak && !rxDontUseAsWhole.test(oStart.oLineBreaker.tagName)){ oStartNode = oStart.oNode.parentNode; }else{ oStartNode = oStart.oNode; } if(oEnd.bParentBreak && !rxDontUseAsWhole.test(oEnd.oLineBreaker.tagName)){ oEndNode = oEnd.oNode.parentNode; }else{ oEndNode = oEnd.oNode; } oSelection.setStartBefore(oStartNode); oSelection.setEndAfter(oEndNode); oNode = this._expandToTableStart(oSelection, oEndNode); if(oNode){ oEndNode = oNode; oSelection.setEndAfter(oNode); } oNode = this._expandToTableStart(oSelection, oStartNode); if(oNode){ oStartNode = oNode; oSelection.setStartBefore(oNode); } oNode = oStartNode; // IE에서는 commonAncestorContainer 자체는 select 가능하지 않고, 하위에 commonAncestorContainer를 대체 하더라도 똑같은 영역이 셀렉트 되어 보이는 // 노드가 있을 경우 하위 노드가 commonAncestorContainer로 반환됨. // 그래서, 스크립트로 commonAncestorContainer 계산 하도록 함. // 예) // <P><SPAN>TEST</SPAN></p>를 선택 할 경우, <SPAN>TEST</SPAN>가 commonAncestorContainer로 잡힘 oSelection.fixCommonAncestorContainer(); elCommonAncestor = oSelection.commonAncestorContainer; if(oSelection.startContainer == oSelection.endContainer && oSelection.endOffset-oSelection.startOffset == 1){ elCommonNode = oSelection.startContainer.childNodes[oSelection.startOffset]; }else{ elCommonNode = oSelection.commonAncestorContainer; } elParentQuote = this._findParentQuote(elCommonNode); if(elParentQuote){ elParentQuote.className = className; return; } while(!elCommonAncestor.tagName || (elCommonAncestor.tagName && elCommonAncestor.tagName.match(/UL|OL|LI|IMG|IFRAME/))){ elCommonAncestor = elCommonAncestor.parentNode; } // find the insertion position for the formatting tag right beneath the common ancestor container while(oNode && oNode != elCommonAncestor && oNode.parentNode != elCommonAncestor){oNode = oNode.parentNode;} if(oNode == elCommonAncestor){ elInsertBefore = elCommonAncestor.firstChild; }else{ elInsertBefore = oNode; } oFormattingNode = oSelection._document.createElement(tag); if(className){ oFormattingNode.className = className; //this._setStyle(oFormattingNode, this.htQuoteStyles_editor[className]); } elCommonAncestor.insertBefore(oFormattingNode, elInsertBefore); oSelection.setStartAfter(oFormattingNode); oSelection.setEndAfter(oEndNode); oSelection.surroundContents(oFormattingNode); if(this._isExceedMaxDepth(oFormattingNode)){ alert(this.oApp.$MSG("SE2M_Quote.exceedMaxCount").replace("#MaxCount#", (this.nMaxLevel + 1))); this.oApp.exec("HIDE_ACTIVE_LAYER", []); elNextNode = oFormattingNode.nextSibling; elParentNode = oFormattingNode.parentNode; aQuoteChild = oFormattingNode.childNodes; aQuoteCloneChild = []; jindo.$Element(oFormattingNode).leave(); for(i = 0, nLen = aQuoteChild.length; i < nLen; i++){ aQuoteCloneChild[i] = aQuoteChild[i]; } for(i = 0, nLen = aQuoteCloneChild.length; i < nLen; i++){ if(!!elNextNode){ jindo.$Element(elNextNode).before(aQuoteCloneChild[i]); }else{ jindo.$Element(elParentNode).append(aQuoteCloneChild[i]); } } return; } oSelection.selectNodeContents(oFormattingNode); // insert an empty line below, so the text cursor can move there if(oFormattingNode && oFormattingNode.parentNode && oFormattingNode.parentNode.tagName == "BODY" && !oFormattingNode.nextSibling){ oP = oSelection._document.createElement("P"); //oP.innerHTML = unescape("<br/>"); oP.innerHTML = "&nbsp;"; oFormattingNode.parentNode.insertBefore(oP, oFormattingNode.nextSibling); } // oSelection.removeStringBookmark(sBookmarkID); // Insert an empty line inside the blockquote if it's empty. // This is done to position the cursor correctly when the contents of the blockquote is empty in Chrome. if(nhn.husky.SE2M_Utils.isBlankNode(oFormattingNode)){ // oFormattingNode.innerHTML = ""; // oP = oSelection._document.createElement("P"); // oP.innerHTML = "&nbsp;"; // oFormattingNode.insertBefore(oP, null); // oSelection = this.oApp.getEmptySelection(); // oSelection.selectNode(oP); // [SMARTEDITORSUS-645] 편집영역 포커스 없이 인용구 추가했을 때 IE7에서 박스가 늘어나는 문제 oFormattingNode.innerHTML = "&nbsp;"; oSelection.selectNodeContents(oFormattingNode); oSelection.collapseToStart(); oSelection.select(); } //oSelection.select(); this.oApp.exec("REFRESH_WYSIWYG"); setTimeout(jindo.$Fn(function(oSelection){ sBookmarkID = oSelection.placeStringBookmark(); oSelection.select(); oSelection.removeStringBookmark(sBookmarkID); this.oApp.exec("FOCUS"); // [SMARTEDITORSUS-469] [SMARTEDITORSUS-434] 에디터 로드 후 최초 삽입한 인용구 안에 포커스가 가지 않는 문제 },this).bind(oSelection), 0); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["BLOCK QUOTE", {sSaveTarget:"BODY"}]); return oFormattingNode; }, _expandToTableStart : function(oSelection, oNode){ var elCommonAncestor = oSelection.commonAncestorContainer; var oResultNode = null; var bLastIteration = false; while(oNode && !bLastIteration){ if(oNode == elCommonAncestor){bLastIteration = true;} if(/TBODY|TFOOT|THEAD|TR/i.test(oNode.tagName)){ oResultNode = this._getTableRoot(oNode); break; } oNode = oNode.parentNode; } return oResultNode; }, _getTableRoot : function(oNode){ while(oNode && oNode.tagName != "TABLE"){oNode = oNode.parentNode;} return oNode; }, _setStyle : function(el, sStyle) { el.setAttribute("style", sStyle); el.style.cssText = sStyle; }, //@lazyload_js] // [SMARTEDITORSUS-209] 인용구 내에 내용이 없을 때 Backspace 로 인용구가 삭제되도록 처리 $ON_EVENT_EDITING_AREA_KEYDOWN : function(weEvent) { var oSelection, elParentQuote; if ('WYSIWYG' !== this.oApp.getEditingMode()){ return; } if(8 !== weEvent.key().keyCode){ return; } oSelection = this.oApp.getSelection(); oSelection.fixCommonAncestorContainer(); elParentQuote = this._findParentQuote(oSelection.commonAncestorContainer); if(!elParentQuote){ return; } if(this._isBlankQuote(elParentQuote)){ weEvent.stop(jindo.$Event.CANCEL_DEFAULT); oSelection.selectNode(elParentQuote); oSelection.collapseToStart(); jindo.$Element(elParentQuote).leave(); oSelection.select(); } }, // [SMARTEDITORSUS-215] Delete 로 인용구 뒤의 P 가 제거되지 않도록 처리 $ON_EVENT_EDITING_AREA_KEYUP : function(weEvent) { var oSelection, elParentQuote, oP; if ('WYSIWYG' !== this.oApp.getEditingMode()){ return; } if(46 !== weEvent.key().keyCode){ return; } oSelection = this.oApp.getSelection(); oSelection.fixCommonAncestorContainer(); elParentQuote = this._findParentQuote(oSelection.commonAncestorContainer); if(!elParentQuote){ return false; } if(!elParentQuote.nextSibling){ weEvent.stop(jindo.$Event.CANCEL_DEFAULT); oP = oSelection._document.createElement("P"); oP.innerHTML = "&nbsp;"; jindo.$Element(elParentQuote).after(oP); setTimeout(jindo.$Fn(function(oSelection){ var sBookmarkID = oSelection.placeStringBookmark(); oSelection.select(); oSelection.removeStringBookmark(sBookmarkID); },this).bind(oSelection), 0); } }, _isBlankQuote : function(elParentQuote){ var elChild, aChildNodes, i, nLen, bChrome = this.oApp.oNavigator.chrome, bSafari = this.oApp.oNavigator.safari, isBlankText = function(sText){ sText = sText.replace(/[\r\n]/ig, '').replace(unescape("%uFEFF"), ''); if(sText === ""){ return true; } if(sText === "&nbsp;" || sText === " "){ // [SMARTEDITORSUS-479] return true; } return false; }, isBlank = function(oNode){ if(oNode.nodeType === 3 && isBlankText(oNode.nodeValue)){ return true; } if((oNode.tagName === "P" || oNode.tagName === "SPAN") && (isBlankText(oNode.innerHTML) || oNode.innerHTML === "<br>")){ return true; } return false; }, isBlankTable = function(oNode){ if((jindo.$$("tr", oNode)).length === 0){ return true; } return false; }; if(isBlankText(elParentQuote.innerHTML) || elParentQuote.innerHTML === "<br>"){ return true; } if(bChrome || bSafari){ // [SMARTEDITORSUS-352], [SMARTEDITORSUS-502] var aTable = jindo.$$("TABLE", elParentQuote), nTable = aTable.length, elTable; for(i=0; i<nTable; i++){ elTable = aTable[i]; if(isBlankTable(elTable)){ jindo.$Element(elTable).leave(); } } } aChildNodes = elParentQuote.childNodes; for(i=0, nLen=aChildNodes.length; i<nLen; i++){ elChild = aChildNodes[i]; if(!isBlank(elChild)){ return false; } } return true; }, _findParentQuote : function(el){ return this._findAncestor(jindo.$Fn(function(elNode){ if(!elNode){return false;} if(elNode.tagName !== "BLOCKQUOTE"){return false;} if(!elNode.className){return false;} var sClassName = elNode.className; if(!this.htQuoteStyles_view[sClassName]){return false;} return true; }, this).bind(), el); }, _findAncestor : function(fnCondition, elNode){ while(elNode && !fnCondition(elNode)){elNode = elNode.parentNode;} return elNode; } });
JavaScript
if(typeof window.nhn=='undefined') window.nhn = {}; /** * @fileOverview This file contains a function that takes care of various operations related to find and replace * @name N_FindReplace.js */ nhn.FindReplace = jindo.$Class({ sKeyword : "", window : null, document : null, bBrowserSupported : false, // true if End Of Contents is reached during last execution of find bEOC : false, $init : function(win){ this.sInlineContainer = "SPAN|B|U|I|S|STRIKE"; this.rxInlineContainer = new RegExp("^("+this.sInlineContainer+")$"); this.window = win; this.document = this.window.document; if(this.document.domain != this.document.location.hostname){ var oAgentInfo = jindo.$Agent(); var oNavigatorInfo = oAgentInfo.navigator(); if(oNavigatorInfo.firefox && oNavigatorInfo.version < 3){ this.bBrowserSupported = false; this.find = function(){return 3}; return; } } this.bBrowserSupported = true; }, // 0: found // 1: not found // 2: keyword required // 3: browser not supported find : function(sKeyword, bCaseMatch, bBackwards, bWholeWord){ var bSearchResult, bFreshSearch; this.window.focus(); if(!sKeyword) return 2; // try find starting from current cursor position this.bEOC = false; bSearchResult = this.findNext(sKeyword, bCaseMatch, bBackwards, bWholeWord); if(bSearchResult) return 0; // end of the contents could have been reached so search again from the beginning this.bEOC = true; bSearchResult = this.findNew(sKeyword, bCaseMatch, bBackwards, bWholeWord); if(bSearchResult) return 0; return 1; }, findNew : function (sKeyword, bCaseMatch, bBackwards, bWholeWord){ this.findReset(); return this.findNext(sKeyword, bCaseMatch, bBackwards, bWholeWord); }, findNext : function(sKeyword, bCaseMatch, bBackwards, bWholeWord){ var bSearchResult; bCaseMatch = bCaseMatch || false; bWholeWord = bWholeWord || false; bBackwards = bBackwards || false; if(this.window.find){ var bWrapAround = false; return this.window.find(sKeyword, bCaseMatch, bBackwards, bWrapAround, bWholeWord); } // IE solution if(this.document.body.createTextRange){ try{ var iOption = 0; if(bBackwards) iOption += 1; if(bWholeWord) iOption += 2; if(bCaseMatch) iOption += 4; this.window.focus(); this._range = this.document.selection.createRangeCollection().item(0); this._range.collapse(false); bSearchResult = this._range.findText(sKeyword, 1, iOption); this._range.select(); return bSearchResult; }catch(e){ return false; } } return false; }, findReset : function() { if (this.window.find){ this.window.getSelection().removeAllRanges(); return; } // IE solution if(this.document.body.createTextRange){ this._range = this.document.body.createTextRange(); this._range.collapse(true); this._range.select(); } }, // 0: replaced & next word found // 1: replaced & next word not found // 2: not replaced & next word found // 3: not replaced & next word not found // 4: sOriginalWord required replace : function(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord){ if(!sOriginalWord) return 4; var oSelection = new nhn.HuskyRange(this.window); oSelection.setFromSelection(); bCaseMatch = bCaseMatch || false; var bMatch, selectedText = oSelection.toString(); if(bCaseMatch) bMatch = (selectedText == sOriginalWord); else bMatch = (selectedText.toLowerCase() == sOriginalWord.toLowerCase()); if(!bMatch) return this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord)+2; if(typeof Replacement == "function"){ // the returned oSelection must contain the replacement oSelection = Replacement(oSelection); }else{ oSelection.pasteText(Replacement); } // force it to find the NEXT occurance of sOriginalWord oSelection.select(); return this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord); }, // returns number of replaced words // -1 : if original word is not given replaceAll : function(sOriginalWord, Replacement, bCaseMatch, bWholeWord){ if(!sOriginalWord) return -1; var bBackwards = false; var iReplaceResult; var iResult = 0; var win = this.window; if(this.find(sOriginalWord, bCaseMatch, bBackwards, bWholeWord) !== 0){ return iResult; } var oSelection = new nhn.HuskyRange(this.window); oSelection.setFromSelection(); // 시작점의 북마크가 지워지면서 시작점을 지나서 replace가 되는 현상 방지용 // 첫 단어 앞쪽에 특수 문자 삽입 해서, replace와 함께 북마크가 사라지는 것 방지 oSelection.collapseToStart(); var oTmpNode = this.window.document.createElement("SPAN"); oTmpNode.innerHTML = unescape("%uFEFF"); oSelection.insertNode(oTmpNode); oSelection.select(); var sBookmark = oSelection.placeStringBookmark(); this.bEOC = false; while(!this.bEOC){ iReplaceResult = this.replace(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord); if(iReplaceResult == 0 || iReplaceResult == 1){ iResult++; } } var startingPointReached = function(){ var oCurSelection = new nhn.HuskyRange(win); oCurSelection.setFromSelection(); oSelection.moveToBookmark(sBookmark); var pos = oSelection.compareBoundaryPoints(nhn.W3CDOMRange.START_TO_END, oCurSelection); if(pos == 1) return false; return true; } iReplaceResult = 0; this.bEOC = false; while(!startingPointReached() && iReplaceResult == 0 && !this.bEOC){ iReplaceResult = this.replace(sOriginalWord, Replacement, bCaseMatch, bBackwards, bWholeWord); if(iReplaceResult == 0 || iReplaceResult == 1) iResult++; } oSelection.moveToBookmark(sBookmark); oSelection.select(); oSelection.removeStringBookmark(sBookmark); // setTimeout 없이 바로 지우면 IE8 브라우저가 빈번하게 죽어버림 setTimeout(function(){ oTmpNode.parentNode.removeChild(oTmpNode); }, 0); return iResult; }, _isBlankTextNode : function(oNode){ if(oNode.nodeType == 3 && oNode.nodeValue == ""){return true;} return false; }, _getNextNode : function(elNode, bDisconnected){ if(!elNode || elNode.tagName == "BODY"){ return {elNextNode: null, bDisconnected: false}; } if(elNode.nextSibling){ elNode = elNode.nextSibling; while(elNode.firstChild){ if(elNode.tagName && !this.rxInlineContainer.test(elNode.tagName)){ bDisconnected = true; } elNode = elNode.firstChild; } return {elNextNode: elNode, bDisconnected: bDisconnected}; } return this._getNextNode(nhn.DOMFix.parentNode(elNode), bDisconnected); }, _getNextTextNode : function(elNode, bDisconnected){ var htNextNode, elNode; while(true){ htNextNode = this._getNextNode(elNode, bDisconnected); elNode = htNextNode.elNextNode; bDisconnected = htNextNode.bDisconnected; if(elNode && elNode.nodeType != 3 && !this.rxInlineContainer.test(elNode.tagName)){ bDisconnected = true; } if(!elNode || (elNode.nodeType==3 && !this._isBlankTextNode(elNode))){ break; } } return {elNextText: elNode, bDisconnected: bDisconnected}; }, _getFirstTextNode : function(){ // 문서에서 제일 앞쪽에 위치한 아무 노드 찾기 var elFirstNode = this.document.body.firstChild; while(!!elFirstNode && elFirstNode.firstChild){ elFirstNode = elFirstNode.firstChild; } // 문서에 아무 노드도 없음 if(!elFirstNode){ return null; } // 처음 노드가 텍스트 노드가 아니거나 bogus 노드라면 다음 텍스트 노드를 찾음 if(elFirstNode.nodeType != 3 || this._isBlankTextNode(elFirstNode)){ var htTmp = this._getNextTextNode(elFirstNode, false); elFirstNode = htTmp.elNextText; } return elFirstNode; }, _addToTextMap : function(elNode, aTexts, aElTexts, nLen){ var nStartPos = aTexts[nLen].length; for(var i=0, nTo=elNode.nodeValue.length; i<nTo; i++){ aElTexts[nLen][nStartPos+i] = [elNode, i]; } aTexts[nLen] += elNode.nodeValue; }, _createTextMap : function(){ var aTexts = []; var aElTexts = []; var nLen=-1; var elNode = this._getFirstTextNode(); var htNextNode = {elNextText: elNode, bDisconnected: true}; while(elNode){ if(htNextNode.bDisconnected){ nLen++; aTexts[nLen] = ""; aElTexts[nLen] = []; } this._addToTextMap(htNextNode.elNextText, aTexts, aElTexts, nLen); htNextNode = this._getNextTextNode(elNode, false); elNode = htNextNode.elNextText; } return {aTexts: aTexts, aElTexts: aElTexts}; }, replaceAll_js : function(sOriginalWord, Replacement, bCaseMatch, bWholeWord){ try{ var t0 = new Date(); var htTmp = this._createTextMap(); var t1 = new Date(); var aTexts = htTmp.aTexts; var aElTexts = htTmp.aElTexts; // console.log(sOriginalWord); // console.log(aTexts); // console.log(aElTexts); var nMatchCnt = 0; var nOriginLen = sOriginalWord.length; // 단어 한개씩 비교 for(var i=0, niLen=aTexts.length; i<niLen; i++){ var sText = aTexts[i]; // 단어 안에 한글자씩 비교 //for(var j=0, njLen=sText.length - nOriginLen; j<njLen; j++){ for(var j=sText.length-nOriginLen; j>=0; j--){ var sTmp = sText.substring(j, j+nOriginLen); if(bWholeWord && (j > 0 && sText.charAt(j-1).match(/[a-zA-Z가-힣]/)) ){ continue; } if(sTmp == sOriginalWord){ nMatchCnt++; var oSelection = new nhn.HuskyRange(this.window); // 마지막 글자의 뒷부분 처리 var elContainer, nOffset; if(j+nOriginLen < aElTexts[i].length){ elContainer = aElTexts[i][j+nOriginLen][0]; nOffset = aElTexts[i][j+nOriginLen][1]; }else{ elContainer = aElTexts[i][j+nOriginLen-1][0]; nOffset = aElTexts[i][j+nOriginLen-1][1]+1; } oSelection.setEnd(elContainer, nOffset, true, true); oSelection.setStart(aElTexts[i][j][0], aElTexts[i][j][1], true); if(typeof Replacement == "function"){ // the returned oSelection must contain the replacement oSelection = Replacement(oSelection); }else{ oSelection.pasteText(Replacement); } j -= nOriginLen; } continue; } } /* var t2 = new Date(); console.log("OK"); console.log(sOriginalWord); console.log("MC:"+(t1-t0)); console.log("RP:"+(t2-t1)); */ return nMatchCnt; }catch(e){ /* console.log("ERROR"); console.log(sOriginalWord); console.log(new Date()-t0); */ return nMatchCnt; } } });
JavaScript
/** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font style in the table. * @requires SE2M_TableEditor.js * @name SE2M_TableBlockManager */ nhn.husky.SE2M_TableBlockStyler = jindo.$Class({ name : "SE2M_TableBlockStyler", nSelectedTD : 0, htSelectedTD : {}, aTdRange : [], $init : function(){ }, $LOCAL_BEFORE_ALL : function(){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_MSG_APP_READY : function(){ this.oDocument = this.oApp.getWYSIWYGDocument(); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG") return; this.setTdBlock(); }, /** * selected Area가 td block인지 체크하는 함수. */ $ON_IS_SELECTED_TD_BLOCK : function(sAttr,oReturn) { if( this.nSelectedTD > 0){ oReturn[sAttr] = true; return oReturn[sAttr]; }else{ oReturn[sAttr] = false; return oReturn[sAttr]; } }, /** * */ $ON_GET_SELECTED_TD_BLOCK : function(sAttr,oReturn){ //use : this.oApp.exec("GET_SELECTED_TD_BLOCK",['aCells',this.htSelectedTD]); oReturn[sAttr] = this.htSelectedTD.aTdCells; }, setTdBlock : function() { this.oApp.exec("GET_SELECTED_CELLS",['aTdCells',this.htSelectedTD]); //tableEditor로 부터 얻어온다. var aNodes = this.htSelectedTD.aTdCells; if(aNodes){ this.nSelectedTD = aNodes.length; } }, $ON_DELETE_BLOCK_CONTENTS : function(){ var self = this, welParent, oBlockNode, oChildNode; this.setTdBlock(); for (var j = 0; j < this.nSelectedTD ; j++){ jindo.$Element(this.htSelectedTD.aTdCells[j]).child( function(elChild){ welParent = jindo.$Element(elChild._element.parentNode); welParent.remove(elChild); oBlockNode = self.oDocument.createElement('P'); if (jindo.$Agent().navigator().firefox) { oChildNode = self.oDocument.createElement('BR'); } else { oChildNode = self.oDocument.createTextNode('\u00A0'); } oBlockNode.appendChild(oChildNode); welParent.append(oBlockNode); }, 1); } } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to table creation * @name hp_SE_Table.js */ nhn.husky.SE2M_TableCreator = jindo.$Class({ name : "SE2M_TableCreator", _sSETblClass : "__se_tbl", nRows : 3, nColumns : 4, nBorderSize : 1, sBorderColor : "#000000", sBGColor: "#000000", nBorderStyleIdx : 3, nTableStyleIdx : 1, nMinRows : 1, nMaxRows : 20, nMinColumns : 1, nMaxColumns : 20, nMinBorderWidth : 1, nMaxBorderWidth : 10, rxLastDigits : null, sReEditGuideMsg_table : null, // 테두리 스타일 목록 // 표 스타일 스타일 목록 oSelection : null, $ON_MSG_APP_READY : function(){ this.sReEditGuideMsg_table = this.oApp.$MSG(nhn.husky.SE2M_Configuration.SE2M_ReEditAction.aReEditGuideMsg[3]); this.oApp.exec("REGISTER_UI_EVENT", ["table", "click", "TOGGLE_TABLE_LAYER"]); }, // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER_DOM", ["IR_TO_DB", jindo.$Fn(this.irToDbDOM, this).bind()]); this.oApp.exec("ADD_CONVERTER_DOM", ["DB_TO_IR", jindo.$Fn(this.dbToIrDOM, this).bind()]); }, irToDbDOM : function(oTmpNode){ /** * 저장을 위한 Table Tag 는 아래와 같이 변경됩니다. * (1) <TABLE> * <table border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;" attr_no_border_tbl="1" class="__se_tbl"> * --> <table border="0" cellpadding="1" cellspacing="0" attr_no_border_tbl="1" class="__se_tbl"> * (2) <TD> * <td style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#ffef00" width="245"><p>&nbsp;</p></td> * --> <td style="background-color:#ffef00" width="245">&nbsp;</td> */ var aNoBorderTable = []; var aTables = jindo.$$('table[class=__se_tbl]', oTmpNode, {oneTimeOffCache:true}); // 테두리가 없음 속성의 table (임의로 추가한 attr_no_border_tbl 속성이 있는 table 을 찾음) jindo.$A(aTables).forEach(function(oValue, nIdx, oArray) { if(jindo.$Element(oValue).attr("attr_no_border_tbl")){ aNoBorderTable.push(oValue); } }, this); if(aNoBorderTable.length < 1){ return; } // [SMARTEDITORSUS-410] 글 저장 시, 테두리 없음 속성을 선택할 때 임의로 표시한 가이드 라인 property 만 style 에서 제거해 준다. // <TABLE> 과 <TD> 의 속성값을 변경 및 제거 var aTDs = [], oTable; for(var i = 0, nCount = aNoBorderTable.length; i < nCount; i++){ oTable = aNoBorderTable[i]; // <TABLE> 에서 border, cellpadding 속성값 변경, style property 제거 jindo.$Element(oTable).css({"border": "", "borderLeft": "", "borderBottom": ""}); jindo.$Element(oTable).attr({"border": 0, "cellpadding": 1}); // <TD> 에서는 background-color 를 제외한 style 을 모두 제거 aTDs = jindo.$$('tbody>tr>td', oTable); jindo.$A(aTDs).forEach(function(oTD, nIdx, oTDArray) { jindo.$Element(oTD).css({"border": "", "borderTop": "", "borderRight": ""}); }); } }, dbToIrDOM : function(oTmpNode){ /** * 수정을 위한 Table Tag 는 아래와 같이 변경됩니다. * (1) <TABLE> * <table border="0" cellpadding="1" cellspacing="0" attr_no_border_tbl="1" class="__se_tbl"> * --> <table border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;" attr_no_border_tbl="1" class="__se_tbl"> * (2) <TD> * <td style="background-color:#ffef00" width="245">&nbsp;</td> * --> <td style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#ffef00" width="245"><p>&nbsp;</p></td> */ var aNoBorderTable = []; var aTables = jindo.$$('table[class=__se_tbl]', oTmpNode, {oneTimeOffCache:true}); // 테두리가 없음 속성의 table (임의로 추가한 attr_no_border_tbl 속성이 있는 table 을 찾음) jindo.$A(aTables).forEach(function(oValue, nIdx, oArray) { if(jindo.$Element(oValue).attr("attr_no_border_tbl")){ aNoBorderTable.push(oValue); } }, this); if(aNoBorderTable.length < 1){ return; } // <TABLE> 과 <TD> 의 속성값을 변경/추가 var aTDs = [], oTable; for(var i = 0, nCount = aNoBorderTable.length; i < nCount; i++){ oTable = aNoBorderTable[i]; // <TABLE> 에서 border, cellpadding 속성값 변경/ style 속성 추가 jindo.$Element(oTable).css({"border": "1px dashed #c7c7c7", "borderLeft": 0, "borderBottom": 0}); jindo.$Element(oTable).attr({"border": 1, "cellpadding": 0}); // <TD> 에서 style 속성값 추가 aTDs = jindo.$$('tbody>tr>td', oTable); jindo.$A(aTDs).forEach(function(oTD, nIdx, oTDArray) { jindo.$Element(oTD).css({"border": "1px dashed #c7c7c7", "borderTop": 0, "borderRight": 0}); }); } }, //@lazyload_js TOGGLE_TABLE_LAYER[ _assignHTMLObjects : function(oAppContainer){ this.oApp.exec("LOAD_HTML", ["create_table"]); var tmp = null; this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_table_layer", oAppContainer); this.welDropdownLayer = jindo.$Element(this.elDropdownLayer); tmp = jindo.$$("INPUT", this.elDropdownLayer); this.elText_row = tmp[0]; this.elText_col = tmp[1]; this.elRadio_manualStyle = tmp[2]; this.elText_borderSize = tmp[3]; this.elText_borderColor = tmp[4]; this.elText_BGColor = tmp[5]; this.elRadio_templateStyle = tmp[6]; tmp = jindo.$$("BUTTON", this.elDropdownLayer); this.elBtn_rowInc = tmp[0]; this.elBtn_rowDec = tmp[1]; this.elBtn_colInc = tmp[2]; this.elBtn_colDec = tmp[3]; this.elBtn_borderStyle = tmp[4]; this.elBtn_incBorderSize = jindo.$$.getSingle("BUTTON.se2m_incBorder", this.elDropdownLayer); this.elBtn_decBorderSize = jindo.$$.getSingle("BUTTON.se2m_decBorder", this.elDropdownLayer); this.elLayer_Dim1 = jindo.$$.getSingle("DIV.se2_t_dim0", this.elDropdownLayer); this.elLayer_Dim2 = jindo.$$.getSingle("DIV.se2_t_dim3", this.elDropdownLayer); // border style layer contains btn elm's tmp = jindo.$$("SPAN.se2_pre_color>BUTTON", this.elDropdownLayer); this.elBtn_borderColor = tmp[0]; this.elBtn_BGColor = tmp[1]; this.elBtn_tableStyle = jindo.$$.getSingle("DIV.se2_select_ty2>BUTTON", this.elDropdownLayer); tmp = jindo.$$("P.se2_btn_area>BUTTON", this.elDropdownLayer); this.elBtn_apply = tmp[0]; this.elBtn_cancel = tmp[1]; this.elTable_preview = jindo.$$.getSingle("TABLE.husky_se2m_table_preview", this.elDropdownLayer); this.elLayer_borderStyle = jindo.$$.getSingle("DIV.husky_se2m_table_border_style_layer", this.elDropdownLayer); this.elPanel_borderStylePreview = jindo.$$.getSingle("SPAN.husky_se2m_table_border_style_preview", this.elDropdownLayer); this.elPanel_borderColorPallet = jindo.$$.getSingle("DIV.husky_se2m_table_border_color_pallet", this.elDropdownLayer); this.elPanel_bgColorPallet = jindo.$$.getSingle("DIV.husky_se2m_table_bgcolor_pallet", this.elDropdownLayer); this.elLayer_tableStyle = jindo.$$.getSingle("DIV.husky_se2m_table_style_layer", this.elDropdownLayer); this.elPanel_tableStylePreview = jindo.$$.getSingle("SPAN.husky_se2m_table_style_preview", this.elDropdownLayer); this.aElBtn_borderStyle = jindo.$$("BUTTON", this.elLayer_borderStyle); this.aElBtn_tableStyle = jindo.$$("BUTTON", this.elLayer_tableStyle); this.sNoBorderText = jindo.$$.getSingle("SPAN.se2m_no_border", this.elDropdownLayer).innerHTML; this.rxLastDigits = RegExp("([0-9]+)$"); }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.oApp.registerBrowserEvent(this.elText_row, "change", "TABLE_SET_ROW_NUM", [null, 0]); this.oApp.registerBrowserEvent(this.elText_col, "change", "TABLE_SET_COLUMN_NUM", [null, 0]); this.oApp.registerBrowserEvent(this.elText_borderSize, "change", "TABLE_SET_BORDER_SIZE", [null, 0]); this.oApp.registerBrowserEvent(this.elBtn_rowInc, "click", "TABLE_INC_ROW"); this.oApp.registerBrowserEvent(this.elBtn_rowDec, "click", "TABLE_DEC_ROW"); jindo.$Fn(this._numRowKeydown, this).attach(this.elText_row.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_colInc, "click", "TABLE_INC_COLUMN"); this.oApp.registerBrowserEvent(this.elBtn_colDec, "click", "TABLE_DEC_COLUMN"); jindo.$Fn(this._numColKeydown, this).attach(this.elText_col.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_incBorderSize, "click", "TABLE_INC_BORDER_SIZE"); this.oApp.registerBrowserEvent(this.elBtn_decBorderSize, "click", "TABLE_DEC_BORDER_SIZE"); jindo.$Fn(this._borderSizeKeydown, this).attach(this.elText_borderSize.parentNode, "keydown"); this.oApp.registerBrowserEvent(this.elBtn_borderStyle, "click", "TABLE_TOGGLE_BORDER_STYLE_LAYER"); this.oApp.registerBrowserEvent(this.elBtn_tableStyle, "click", "TABLE_TOGGLE_STYLE_LAYER"); this.oApp.registerBrowserEvent(this.elBtn_borderColor, "click", "TABLE_TOGGLE_BORDER_COLOR_PALLET"); this.oApp.registerBrowserEvent(this.elBtn_BGColor, "click", "TABLE_TOGGLE_BGCOLOR_PALLET"); this.oApp.registerBrowserEvent(this.elRadio_manualStyle, "click", "TABLE_ENABLE_MANUAL_STYLE"); this.oApp.registerBrowserEvent(this.elRadio_templateStyle, "click", "TABLE_ENABLE_TEMPLATE_STYLE"); //this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "TABLE_LAYER_CLICKED"); //this.oApp.registerBrowserEvent(this.elLayer_borderStyle, "click", "TABLE_BORDER_STYLE_LAYER_CLICKED"); //this.oApp.registerBrowserEvent(this.elLayer_tableStyle, "click", "TABLE_STYLE_LAYER_CLICKED"); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_borderStyle]); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_tableStyle]); var i; for(i=0; i<this.aElBtn_borderStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_borderStyle[i], "click", "TABLE_SELECT_BORDER_STYLE"); } for(i=0; i<this.aElBtn_tableStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_tableStyle[i], "click", "TABLE_SELECT_STYLE"); } this.oApp.registerBrowserEvent(this.elBtn_apply, "click", "TABLE_INSERT"); this.oApp.registerBrowserEvent(this.elBtn_cancel, "click", "HIDE_ACTIVE_LAYER"); this.oApp.exec("TABLE_SET_BORDER_COLOR", [/#[0-9A-Fa-f]{6}/.test(this.elText_borderColor.value) ? this.elText_borderColor.value : "#cccccc"]); this.oApp.exec("TABLE_SET_BGCOLOR", [/#[0-9A-Fa-f]{6}/.test(this.elText_BGColor.value) ? this.elText_BGColor.value : "#ffffff"]); // 1: manual style // 2: template style this.nStyleMode = 1; // add #BorderSize+x# if needed //--- // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. this.aTableStyleByBorder = [ '', 'border="1" cellpadding="0" cellspacing="0" style="border:1px dashed #c7c7c7; border-left:0; border-bottom:0;"', 'border="1" cellpadding="0" cellspacing="0" style="border:#BorderSize#px dashed #BorderColor#; border-left:0; border-bottom:0;"', 'border="0" cellpadding="0" cellspacing="0" style="border:#BorderSize#px solid #BorderColor#; border-left:0; border-bottom:0;"', 'border="0" cellpadding="0" cellspacing="1" style="border:#BorderSize#px solid #BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border:#BorderSize#px double #BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border-width:#BorderSize*2#px #BorderSize#px #BorderSize#px #BorderSize*2#px; border-style:solid;border-color:#BorderColor#;"', 'border="0" cellpadding="0" cellspacing="1" style="border-width:#BorderSize#px #BorderSize*2#px #BorderSize*2#px #BorderSize#px; border-style:solid;border-color:#BorderColor#;"' ]; this.aTDStyleByBorder = [ '', 'style="border:1px dashed #c7c7c7; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px dashed #BorderColor#; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px solid #BorderColor#; border-top:0; border-right:0; background-color:#BGColor#"', 'style="border:#BorderSize#px solid #BorderColor#; background-color:#BGColor#"', 'style="border:#BorderSize+2#px double #BorderColor#; background-color:#BGColor#"', 'style="border-width:#BorderSize#px #BorderSize*2#px #BorderSize*2#px #BorderSize#px; border-style:solid;border-color:#BorderColor#; background-color:#BGColor#"', 'style="border-width:#BorderSize*2#px #BorderSize#px #BorderSize#px #BorderSize*2#px; border-style:solid;border-color:#BorderColor#; background-color:#BGColor#"' ]; this.oApp.registerBrowserEvent(this.elDropdownLayer, "keydown", "EVENT_TABLE_CREATE_KEYDOWN"); this._drawTableDropdownLayer(); }, $ON_TABLE_SELECT_BORDER_STYLE : function(weEvent){ var elButton = weEvent.currentElement; // var aMatch = this.rxLastDigits.exec(weEvent.element.className); var aMatch = this.rxLastDigits.exec(elButton.className); this._selectBorderStyle(aMatch[1]); }, $ON_TABLE_SELECT_STYLE : function(weEvent){ var aMatch = this.rxLastDigits.exec(weEvent.element.className); this._selectTableStyle(aMatch[1]); }, $ON_TOGGLE_TABLE_LAYER : function(){ // this.oSelection = this.oApp.getSelection(); this._showNewTable(); this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "SELECT_UI", ["table"], "TABLE_CLOSE", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['table']); }, $ON_TABLE_BORDER_STYLE_LAYER_CLICKED : function(weEvent){ top.document.title = weEvent.element.tagName; }, $ON_TABLE_CLOSE_ALL : function(){ this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); this.oApp.exec("TABLE_HIDE_BORDER_STYLE_LAYER", []); this.oApp.exec("TABLE_HIDE_STYLE_LAYER", []); }, $ON_TABLE_INC_ROW : function(){ this.oApp.exec("TABLE_SET_ROW_NUM", [null, 1]); }, $ON_TABLE_DEC_ROW : function(){ this.oApp.exec("TABLE_SET_ROW_NUM", [null, -1]); }, $ON_TABLE_INC_COLUMN : function(){ this.oApp.exec("TABLE_SET_COLUMN_NUM", [null, 1]); }, $ON_TABLE_DEC_COLUMN : function(){ this.oApp.exec("TABLE_SET_COLUMN_NUM", [null, -1]); }, $ON_TABLE_SET_ROW_NUM : function(nRows, nRowDiff){ nRows = nRows || parseInt(this.elText_row.value, 10) || 0; nRowDiff = nRowDiff || 0; nRows += nRowDiff; if(nRows < this.nMinRows){nRows = this.nMinRows;} if(nRows > this.nMaxRows){nRows = this.nMaxRows;} this.elText_row.value = nRows; this._showNewTable(); }, $ON_TABLE_SET_COLUMN_NUM : function(nColumns, nColumnDiff){ nColumns = nColumns || parseInt(this.elText_col.value, 10) || 0; nColumnDiff = nColumnDiff || 0; nColumns += nColumnDiff; if(nColumns < this.nMinColumns){nColumns = this.nMinColumns;} if(nColumns > this.nMaxColumns){nColumns = this.nMaxColumns;} this.elText_col.value = nColumns; this._showNewTable(); }, _getTableString : function(){ var sTable; if(this.nStyleMode == 1){ sTable = this._doGetTableString(this.nColumns, this.nRows, this.nBorderSize, this.sBorderColor, this.sBGColor, this.nBorderStyleIdx); }else{ sTable = this._doGetTableString(this.nColumns, this.nRows, this.nBorderSize, this.sBorderColor, this.sBGColor, 0); } return sTable; }, $ON_TABLE_INSERT : function(){ this.oApp.exec("IE_FOCUS", []); // [SMARTEDITORSUS-500] IE인 경우 명시적인 focus 추가 //[SMARTEDITORSUS-596]이벤트 발생이 안되는 경우, //max 제한이 적용이 안되기 때문에 테이블 사입 시점에 다시한번 Max 값을 검사한다. this.oApp.exec("TABLE_SET_COLUMN_NUM"); this.oApp.exec("TABLE_SET_ROW_NUM"); this._loadValuesFromHTML(); var sTable, elLinebreak, elBody, welBody, elTmpDiv, elTable, elFirstTD, oSelection, elTableHolder, htBrowser; elBody = this.oApp.getWYSIWYGDocument().body; welBody = jindo.$Element(elBody); htBrowser = jindo.$Agent().navigator(); this.nTableWidth = elBody.offsetWidth; sTable = this._getTableString(); elTmpDiv = this.oApp.getWYSIWYGDocument().createElement("DIV"); elTmpDiv.innerHTML = sTable; elTable = elTmpDiv.firstChild; elTable.className = this._sSETblClass; oSelection = this.oApp.getSelection(); oSelection = this._divideParagraph(oSelection); // [SMARTEDITORSUS-306] this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["INSERT TABLE", {sSaveTarget:"BODY"}]); // If the table were inserted within a styled(strikethough & etc) paragraph, the table may inherit the style in IE. elTableHolder = this.oApp.getWYSIWYGDocument().createElement("DIV"); // 영역을 잡았을 경우, 영역 지우고 테이블 삽입 oSelection.deleteContents(); oSelection.insertNode(elTableHolder); oSelection.selectNode(elTableHolder); this.oApp.exec("REMOVE_STYLE", [oSelection]); if(htBrowser.ie && this.oApp.getWYSIWYGDocument().body.childNodes.length === 1 && this.oApp.getWYSIWYGDocument().body.firstChild === elTableHolder){ // IE에서 table이 body에 바로 붙어 있을 경우, 정렬등에서 문제가 발생 함으로 elTableHolder(DIV)를 남겨둠 elTableHolder.insertBefore(elTable, null); }else{ elTableHolder.parentNode.insertBefore(elTable, elTableHolder); elTableHolder.parentNode.removeChild(elTableHolder); } // FF : 테이블 하단에 BR이 없을 경우, 커서가 테이블 밑으로 이동할 수 없어 BR을 삽입 해 줌. //[SMARTEDITORSUS-181][IE9] 표나 요약글 등의 테이블에서 > 테이블 외부로 커서 이동 불가 if(htBrowser.firefox){ elLinebreak = this.oApp.getWYSIWYGDocument().createElement("BR"); elTable.parentNode.insertBefore(elLinebreak, elTable.nextSibling); }else if(htBrowser.ie ){ elLinebreak = this.oApp.getWYSIWYGDocument().createElement("p"); elTable.parentNode.insertBefore(elLinebreak, elTable.nextSibling); } if(this.nStyleMode == 2){ this.oApp.exec("STYLE_TABLE", [elTable, this.nTableStyleIdx]); } elFirstTD = elTable.getElementsByTagName("TD")[0]; oSelection.selectNodeContents(elFirstTD.firstChild || elFirstTD); oSelection.collapseToEnd(); oSelection.select(); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["INSERT TABLE", {sSaveTarget:"BODY"}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec('MSG_DISPLAY_REEDIT_MESSAGE_SHOW', [this.name, this.sReEditGuideMsg_table]); }, /** * P 안에 Table 이 추가되지 않도록 P 태그를 분리함 * * [SMARTEDITORSUS-306] * P 에 Table 을 추가한 경우, DOM 에서 비정상적인 P 를 생성하여 깨지는 경우가 발생함 * 테이블이 추가되는 부분에 P 가 있는 경우, P 를 분리시켜주는 처리 */ _divideParagraph : function(oSelection){ var oParentP, welParentP, sNodeVaule, sBM, oSWrapper, oEWrapper; oSelection.fixCommonAncestorContainer(); // [SMARTEDITORSUS-423] 엔터에 의해 생성된 P 가 아닌 이전 P 가 선택되지 않도록 fix 하도록 처리 oParentP = oSelection.findAncestorByTagName("P"); if(!oParentP){ return oSelection; } if(!oParentP.firstChild || nhn.husky.SE2M_Utils.isBlankNode(oParentP)){ oSelection.selectNode(oParentP); // [SMARTEDITORSUS-423] 불필요한 개행이 일어나지 않도록 빈 P 를 선택하여 TABLE 로 대체하도록 처리 oSelection.select(); return oSelection; } sBM = oSelection.placeStringBookmark(); oSelection.moveToBookmark(sBM); oSWrapper = this.oApp.getWYSIWYGDocument().createElement("P"); oSelection.setStartBefore(oParentP.firstChild); oSelection.surroundContents(oSWrapper); oSelection.collapseToEnd(); oEWrapper = this.oApp.getWYSIWYGDocument().createElement("P"); oSelection.setEndAfter(oParentP.lastChild); oSelection.surroundContents(oEWrapper); oSelection.collapseToStart(); oSelection.removeStringBookmark(sBM); welParentP = jindo.$Element(oParentP); welParentP.after(oEWrapper); welParentP.after(oSWrapper); welParentP.leave(); oSelection = this.oApp.getEmptySelection(); oSelection.setEndAfter(oSWrapper); oSelection.setStartBefore(oEWrapper); oSelection.select(); return oSelection; }, $ON_TABLE_CLOSE : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.oApp.exec("DESELECT_UI", ["table"]); }, $ON_TABLE_SET_BORDER_SIZE : function(nBorderWidth, nBorderWidthDiff){ nBorderWidth = nBorderWidth || parseInt(this.elText_borderSize.value, 10) || 0; nBorderWidthDiff = nBorderWidthDiff || 0; nBorderWidth += nBorderWidthDiff; if(nBorderWidth < this.nMinBorderWidth){nBorderWidth = this.nMinBorderWidth;} if(nBorderWidth > this.nMaxBorderWidth){nBorderWidth = this.nMaxBorderWidth;} this.elText_borderSize.value = nBorderWidth; }, $ON_TABLE_INC_BORDER_SIZE : function(){ this.oApp.exec("TABLE_SET_BORDER_SIZE", [null, 1]); }, $ON_TABLE_DEC_BORDER_SIZE : function(){ this.oApp.exec("TABLE_SET_BORDER_SIZE", [null, -1]); }, $ON_TABLE_TOGGLE_BORDER_STYLE_LAYER : function(){ if(this.elLayer_borderStyle.style.display == "block"){ this.oApp.exec("TABLE_HIDE_BORDER_STYLE_LAYER", []); }else{ this.oApp.exec("TABLE_SHOW_BORDER_STYLE_LAYER", []); } }, $ON_TABLE_SHOW_BORDER_STYLE_LAYER : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.elBtn_borderStyle.className = "se2_view_more2"; this.elLayer_borderStyle.style.display = "block"; this._refresh(); }, $ON_TABLE_HIDE_BORDER_STYLE_LAYER : function(){ this.elBtn_borderStyle.className = "se2_view_more"; this.elLayer_borderStyle.style.display = "none"; this._refresh(); }, $ON_TABLE_TOGGLE_STYLE_LAYER : function(){ if(this.elLayer_tableStyle.style.display == "block"){ this.oApp.exec("TABLE_HIDE_STYLE_LAYER", []); }else{ this.oApp.exec("TABLE_SHOW_STYLE_LAYER", []); } }, $ON_TABLE_SHOW_STYLE_LAYER : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.elBtn_tableStyle.className = "se2_view_more2"; this.elLayer_tableStyle.style.display = "block"; this._refresh(); }, $ON_TABLE_HIDE_STYLE_LAYER : function(){ this.elBtn_tableStyle.className = "se2_view_more"; this.elLayer_tableStyle.style.display = "none"; this._refresh(); }, $ON_TABLE_TOGGLE_BORDER_COLOR_PALLET : function(){ if(this.welDropdownLayer.hasClass("p1")){ this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); }else{ this.oApp.exec("TABLE_SHOW_BORDER_COLOR_PALLET", []); } }, $ON_TABLE_SHOW_BORDER_COLOR_PALLET : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.welDropdownLayer.addClass("p1"); this.welDropdownLayer.removeClass("p2"); this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_SET_BORDER_COLOR_FROM_PALETTE", this.elPanel_borderColorPallet]); this.elPanel_borderColorPallet.parentNode.style.display = "block"; }, $ON_TABLE_HIDE_BORDER_COLOR_PALLET : function(){ this.welDropdownLayer.removeClass("p1"); this.oApp.exec("HIDE_COLOR_PALETTE", []); this.elPanel_borderColorPallet.parentNode.style.display = "none"; }, $ON_TABLE_TOGGLE_BGCOLOR_PALLET : function(){ if(this.welDropdownLayer.hasClass("p2")){ this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); }else{ this.oApp.exec("TABLE_SHOW_BGCOLOR_PALLET", []); } }, $ON_TABLE_SHOW_BGCOLOR_PALLET : function(){ this.oApp.exec("TABLE_CLOSE_ALL", []); this.welDropdownLayer.removeClass("p1"); this.welDropdownLayer.addClass("p2"); this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_SET_BGCOLOR_FROM_PALETTE", this.elPanel_bgColorPallet]); this.elPanel_bgColorPallet.parentNode.style.display = "block"; }, $ON_TABLE_HIDE_BGCOLOR_PALLET : function(){ this.welDropdownLayer.removeClass("p2"); this.oApp.exec("HIDE_COLOR_PALETTE", []); this.elPanel_bgColorPallet.parentNode.style.display = "none"; }, $ON_TABLE_SET_BORDER_COLOR_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_SET_BORDER_COLOR", [sColorCode]); this.oApp.exec("TABLE_HIDE_BORDER_COLOR_PALLET", []); }, $ON_TABLE_SET_BORDER_COLOR : function(sColorCode){ this.elText_borderColor.value = sColorCode; this.elBtn_borderColor.style.backgroundColor = sColorCode; }, $ON_TABLE_SET_BGCOLOR_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_SET_BGCOLOR", [sColorCode]); this.oApp.exec("TABLE_HIDE_BGCOLOR_PALLET", []); }, $ON_TABLE_SET_BGCOLOR : function(sColorCode){ this.elText_BGColor.value = sColorCode; this.elBtn_BGColor.style.backgroundColor = sColorCode; }, $ON_TABLE_ENABLE_MANUAL_STYLE : function(){ this.nStyleMode = 1; this._drawTableDropdownLayer(); }, $ON_TABLE_ENABLE_TEMPLATE_STYLE : function(){ this.nStyleMode = 2; this._drawTableDropdownLayer(); }, $ON_EVENT_TABLE_CREATE_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.elBtn_apply.focus(); this.oApp.exec("TABLE_INSERT"); oEvent.stop(); } }, _drawTableDropdownLayer : function(){ if(this.nBorderStyleIdx == 1){ this.elPanel_borderStylePreview.innerHTML = this.sNoBorderText; this.elLayer_Dim1.className = "se2_t_dim2"; }else{ this.elPanel_borderStylePreview.innerHTML = ""; this.elLayer_Dim1.className = "se2_t_dim0"; } if(this.nStyleMode == 1){ this.elRadio_manualStyle.checked = true; this.elLayer_Dim2.className = "se2_t_dim3"; this.elText_borderSize.disabled = false; this.elText_borderColor.disabled = false; this.elText_BGColor.disabled = false; }else{ this.elRadio_templateStyle.checked = true; this.elLayer_Dim2.className = "se2_t_dim1"; this.elText_borderSize.disabled = true; this.elText_borderColor.disabled = true; this.elText_BGColor.disabled = true; } this.oApp.exec("TABLE_CLOSE_ALL", []); }, _selectBorderStyle : function(nStyleNum){ this.elPanel_borderStylePreview.className = "se2_b_style"+nStyleNum; this.nBorderStyleIdx = nStyleNum; this._drawTableDropdownLayer(); }, _selectTableStyle : function(nStyleNum){ this.elPanel_tableStylePreview.className = "se2_t_style"+nStyleNum; this.nTableStyleIdx = nStyleNum; this._drawTableDropdownLayer(); }, _showNewTable : function(){ var oTmp = document.createElement("DIV"); this._loadValuesFromHTML(); oTmp.innerHTML = this._getPreviewTableString(this.nColumns, this.nRows); //this.nTableWidth = 0; //oTmp.innerHTML = this._getTableString(); var oNewTable = oTmp.firstChild; this.elTable_preview.parentNode.insertBefore(oNewTable, this.elTable_preview); this.elTable_preview.parentNode.removeChild(this.elTable_preview); this.elTable_preview = oNewTable; this._refresh(); }, _getPreviewTableString : function(nColumns, nRows){ var sTable = '<table border="0" cellspacing="1" class="se2_pre_table husky_se2m_table_preview">'; var sRow = '<tr>'; for(var i=0; i<nColumns; i++){ sRow += "<td><p>&nbsp;</p></td>\n"; } sRow += "</tr>\n"; sTable += "<tbody>"; for(var i=0; i<nRows; i++){ sTable += sRow; } sTable += "</tbody>\n"; sTable += "</table>\n"; return sTable; }, _loadValuesFromHTML : function(){ this.nColumns = parseInt(this.elText_col.value, 10) || 1; this.nRows = parseInt(this.elText_row.value, 10) || 1; this.nBorderSize = parseInt(this.elText_borderSize.value, 10) || 1; this.sBorderColor = this.elText_borderColor.value; this.sBGColor = this.elText_BGColor.value; }, _doGetTableString : function(nColumns, nRows, nBorderSize, sBorderColor, sBGColor, nBorderStyleIdx){ var nTDWidth = parseInt(this.nTableWidth/nColumns, 10); var nBorderSize = this.nBorderSize; var sTableStyle = this.aTableStyleByBorder[nBorderStyleIdx].replace(/#BorderSize#/g, this.nBorderSize).replace(/#BorderSize\*([0-9]+)#/g, function(sAll, s1){return nBorderSize*parseInt(s1, 10);}).replace(/#BorderSize\+([0-9]+)#/g, function(sAll, s1){return nBorderSize+parseInt(s1, 10);}).replace("#BorderColor#", this.sBorderColor).replace("#BGColor#", this.sBGColor); var sTDStyle = this.aTDStyleByBorder[nBorderStyleIdx].replace(/#BorderSize#/g, this.nBorderSize).replace(/#BorderSize\*([0-9]+)#/g, function(sAll, s1){return nBorderSize*parseInt(s1, 10);}).replace(/#BorderSize\+([0-9]+)#/g, function(sAll, s1){return nBorderSize+parseInt(s1, 10);}).replace("#BorderColor#", this.sBorderColor).replace("#BGColor#", this.sBGColor); if(nTDWidth){ sTDStyle += " width="+nTDWidth; }else{ //sTableStyle += " width=100%"; sTableStyle += "class=se2_pre_table"; } // [SMARTEDITORSUS-365] 테이블퀵에디터 > 속성 직접입력 > 테두리 스타일 // - 테두리 없음을 선택하는 경우 본문에 삽입하는 표에 가이드 라인을 표시해 줍니다. 보기 시에는 테두리가 보이지 않습니다. // - 글 저장 시에는 글 작성 시에 적용하였던 style 을 제거합니다. 이를 위해서 임의의 속성(attr_no_border_tbl)을 추가하였다가 저장 시점에서 제거해 주도록 합니다. var sTempNoBorderClass = (nBorderStyleIdx == 1) ? 'attr_no_border_tbl="1"' : ''; var sTable = "<table "+sTableStyle+" "+sTempNoBorderClass+">"; var sRow = "<tr>"; for(var i=0; i<nColumns; i++){ sRow += "<td "+sTDStyle+"><p>&nbsp;</p></td>\n"; } sRow += "</tr>\n"; sTable += "<tbody>\n"; for(var i=0; i<nRows; i++){ sTable += sRow; } sTable += "</tbody>\n"; sTable += "</table>\n<br>"; return sTable; }, _numRowKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_ROW", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_ROW", []); } }, _numColKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_COLUMN", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_COLUMN", []); } }, _borderSizeKeydown : function(weEvent){ var oKeyInfo = weEvent.key(); // up if(oKeyInfo.keyCode == 38){ this.oApp.exec("TABLE_INC_BORDER_SIZE", []); } // down if(oKeyInfo.keyCode == 40){ this.oApp.exec("TABLE_DEC_BORDER_SIZE", []); } }, _refresh : function(){ // the dropdown layer breaks without this line in IE 6 when modifying the preview table this.elDropdownLayer.style.zoom=0; this.elDropdownLayer.style.zoom=""; } //@lazyload_js] }); //}
JavaScript
nhn.husky.SE2M_TableEditor = jindo.$Class({ name : "SE2M_TableEditor", _sSETblClass : "__se_tbl", _sSEReviewTblClass : "__se_tbl_review", STATUS : { S_0 : 1, // neither cell selection nor cell resizing is active MOUSEDOWN_CELL : 2, // mouse down on a table cell CELL_SELECTING : 3, // cell selection is in progress CELL_SELECTED : 4, // cell selection was (completely) made MOUSEOVER_BORDER : 5, // mouse is over a table/cell border and the cell resizing grip is shown MOUSEDOWN_BORDER : 6 // mouse down on the cell resizing grip (cell resizing is in progress) }, CELL_SELECTION_CLASS : "se2_te_selection", MIN_CELL_WIDTH : 5, MIN_CELL_HEIGHT : 5, TMP_BGC_ATTR : "_se2_tmp_te_bgc", TMP_BGIMG_ATTR : "_se2_tmp_te_bg_img", ATTR_TBL_TEMPLATE : "_se2_tbl_template", nStatus : 1, nMouseEventsStatus : 0, aSelectedCells : [], $ON_REGISTER_CONVERTERS : function(){ // remove the cell selection class this.oApp.exec("ADD_CONVERTER_DOM", ["WYSIWYG_TO_IR", jindo.$Fn(function(elTmpNode){ if(this.aSelectedCells.length < 1){ //return sContents; return; } var aCells; var aCellType = ["TD", "TH"]; for(var n = 0; n < aCellType.length; n++){ aCells = elTmpNode.getElementsByTagName(aCellType[n]); for(var i = 0, nLen = aCells.length; i < nLen; i++){ if(aCells[i].className){ aCells[i].className = aCells[i].className.replace(this.CELL_SELECTION_CLASS, ""); if(aCells[i].getAttribute(this.TMP_BGC_ATTR)){ aCells[i].style.backgroundColor = aCells[i].getAttribute(this.TMP_BGC_ATTR); aCells[i].removeAttribute(this.TMP_BGC_ATTR); }else if(aCells[i].getAttribute(this.TMP_BGIMG_ATTR)){ jindo.$Element(this.aCells[i]).css("backgroundImage",aCells[i].getAttribute(this.TMP_BGIMG_ATTR)); aCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } } } } // this.wfnMouseDown.attach(this.elResizeCover, "mousedown"); // return elTmpNode.innerHTML; // var rxSelectionColor = new RegExp("<(TH|TD)[^>]*)("+this.TMP_BGC_ATTR+"=[^> ]*)([^>]*>)", "gi"); }, this).bind()]); }, //@lazyload_js EVENT_EDITING_AREA_MOUSEMOVE:SE2M_TableTemplate.js[ _assignHTMLObjects : function(){ this.oApp.exec("LOAD_HTML", ["qe_table"]); this.elQELayer = jindo.$$.getSingle("DIV.q_table_wrap", this.oApp.htOptions.elAppContainer); this.elQELayer.style.zIndex = 150; this.elBtnAddRowBelow = jindo.$$.getSingle("BUTTON.se2_addrow", this.elQELayer); this.elBtnAddColumnRight = jindo.$$.getSingle("BUTTON.se2_addcol", this.elQELayer); this.elBtnSplitRow = jindo.$$.getSingle("BUTTON.se2_seprow", this.elQELayer); this.elBtnSplitColumn = jindo.$$.getSingle("BUTTON.se2_sepcol", this.elQELayer); this.elBtnDeleteRow = jindo.$$.getSingle("BUTTON.se2_delrow", this.elQELayer); this.elBtnDeleteColumn = jindo.$$.getSingle("BUTTON.se2_delcol", this.elQELayer); this.elBtnMergeCell = jindo.$$.getSingle("BUTTON.se2_merrow", this.elQELayer); this.elBtnBGPalette = jindo.$$.getSingle("BUTTON.husky_se2m_table_qe_bgcolor_btn", this.elQELayer); this.elBtnBGIMGPalette = jindo.$$.getSingle("BUTTON.husky_se2m_table_qe_bgimage_btn", this.elQELayer); this.elPanelBGPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_bg_paletteHolder", this.elQELayer); this.elPanelBGIMGPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_bg_img_paletteHolder", this.elQELayer); this.elPanelTableBGArea = jindo.$$.getSingle("DIV.se2_qe2", this.elQELayer); this.elPanelTableTemplateArea = jindo.$$.getSingle("DL.se2_qe3", this.elQELayer); this.elPanelReviewBGArea = jindo.$$.getSingle("DL.husky_se2m_tbl_qe_review_bg", this.elQELayer); this.elPanelBGImg = jindo.$$.getSingle("DD", this.elPanelReviewBGArea); this.welPanelTableBGArea = jindo.$Element(this.elPanelTableBGArea); this.welPanelTableTemplateArea = jindo.$Element(this.elPanelTableTemplateArea); this.welPanelReviewBGArea = jindo.$Element(this.elPanelReviewBGArea); // this.elPanelReviewBtnArea = jindo.$$.getSingle("DIV.se2_btn_area", this.elQELayer); //My리뷰 버튼 레이어 this.elPanelDim1 = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim1", this.elQELayer); this.elPanelDim2 = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim2", this.elQELayer); this.elPanelDimDelCol = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim_del_col", this.elQELayer); this.elPanelDimDelRow = jindo.$$.getSingle("DIV.husky_se2m_tbl_qe_dim_del_row", this.elQELayer); this.elInputRadioBGColor = jindo.$$.getSingle("INPUT.husky_se2m_radio_bgc", this.elQELayer); this.elInputRadioBGImg = jindo.$$.getSingle("INPUT.husky_se2m_radio_bgimg", this.elQELayer); this.elSelectBoxTemplate = jindo.$$.getSingle("DIV.se2_select_ty2", this.elQELayer); this.elInputRadioTemplate = jindo.$$.getSingle("INPUT.husky_se2m_radio_template", this.elQELayer); this.elPanelQETemplate = jindo.$$.getSingle("DIV.se2_layer_t_style", this.elQELayer); this.elBtnQETemplate = jindo.$$.getSingle("BUTTON.husky_se2m_template_more", this.elQELayer); this.elPanelQETemplatePreview = jindo.$$.getSingle("SPAN.se2_t_style1", this.elQELayer); this.aElBtn_tableStyle = jindo.$$("BUTTON", this.elPanelQETemplate); for(i = 0; i < this.aElBtn_tableStyle.length; i++){ this.oApp.registerBrowserEvent(this.aElBtn_tableStyle[i], "click", "TABLE_QE_SELECT_TEMPLATE"); } }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!sMsg.match(/(REGISTER_CONVERTERS)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return true; }else{ if(!sMsg.match(/(EVENT_EDITING_AREA_MOUSEMOVE)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return false; } } this.htResizing = {}; this.nDraggableCellEdge = 2; var elBody = jindo.$Element(document.body); this.nPageLeftRightMargin = parseInt(elBody.css("marginLeft"), 10) + parseInt(elBody.css("marginRight"), 10); this.nPageTopBottomMargin = parseInt(elBody.css("marginTop"), 10) + parseInt(elBody.css("marginBottom"), 10); //this.nPageLeftRightMargin = parseInt(elBody.css("marginLeft"), 10)+parseInt(elBody.css("marginRight"), 10) + parseInt(elBody.css("paddingLeft"), 10)+parseInt(elBody.css("paddingRight"), 10); //this.nPageTopBottomMargin = parseInt(elBody.css("marginTop"), 10)+parseInt(elBody.css("marginBottom"), 10) + parseInt(elBody.css("paddingTop"), 10)+parseInt(elBody.css("paddingBottom"), 10); this.QE_DIM_MERGE_BTN = 1; this.QE_DIM_BG_COLOR = 2; this.QE_DIM_REVIEW_BG_IMG = 3; this.QE_DIM_TABLE_TEMPLATE = 4; this.rxLastDigits = RegExp("([0-9]+)$"); this._assignHTMLObjects(); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aElBtn_tableStyle]); this.addCSSClass(this.CELL_SELECTION_CLASS, "background-color:#B4C9E9;"); this._createCellResizeGrip(); this.elIFrame = this.oApp.getWYSIWYGWindow().frameElement; this.htFrameOffset = jindo.$Element(this.elIFrame).offset(); var elTarget; this.sEmptyTDSrc = ""; if(this.oApp.oNavigator.ie){ this.sEmptyTDSrc = "<p>&nbsp;</p>"; }else{ if(this.oApp.oNavigator.firefox){ this.sEmptyTDSrc = "<p><br/></p>"; }else{ this.sEmptyTDSrc = "<p>&nbsp;</p>"; } } elTarget = this.oApp.getWYSIWYGDocument(); /* jindo.$Fn(this._mousedown_WYSIWYGDoc, this).attach(elTarget, "mousedown"); jindo.$Fn(this._mousemove_WYSIWYGDoc, this).attach(elTarget, "mousemove"); jindo.$Fn(this._mouseup_WYSIWYGDoc, this).attach(elTarget, "mouseup"); */ elTarget = this.elResizeCover; this.wfnMousedown_ResizeCover = jindo.$Fn(this._mousedown_ResizeCover, this); this.wfnMousemove_ResizeCover = jindo.$Fn(this._mousemove_ResizeCover, this); this.wfnMouseup_ResizeCover = jindo.$Fn(this._mouseup_ResizeCover, this); this.wfnMousedown_ResizeCover.attach(elTarget, "mousedown"); this._changeTableEditorStatus(this.STATUS.S_0); // this.oApp.registerBrowserEvent(doc, "click", "EVENT_EDITING_AREA_CLICK"); this.oApp.registerBrowserEvent(this.elBtnMergeCell, "click", "TE_MERGE_CELLS"); this.oApp.registerBrowserEvent(this.elBtnSplitColumn, "click", "TE_SPLIT_COLUMN"); this.oApp.registerBrowserEvent(this.elBtnSplitRow, "click", "TE_SPLIT_ROW"); // this.oApp.registerBrowserEvent(this.elBtnAddColumnLeft, "click", "TE_INSERT_COLUMN_LEFT"); this.oApp.registerBrowserEvent(this.elBtnAddColumnRight, "click", "TE_INSERT_COLUMN_RIGHT"); this.oApp.registerBrowserEvent(this.elBtnAddRowBelow, "click", "TE_INSERT_ROW_BELOW"); // this.oApp.registerBrowserEvent(this.elBtnAddRowAbove, "click", "TE_INSERT_ROW_ABOVE"); this.oApp.registerBrowserEvent(this.elBtnDeleteColumn, "click", "TE_DELETE_COLUMN"); this.oApp.registerBrowserEvent(this.elBtnDeleteRow, "click", "TE_DELETE_ROW"); this.oApp.registerBrowserEvent(this.elInputRadioBGColor, "click", "DRAW_QE_RADIO_OPTION", [2]); this.oApp.registerBrowserEvent(this.elInputRadioBGImg, "click", "DRAW_QE_RADIO_OPTION", [3]); this.oApp.registerBrowserEvent(this.elInputRadioTemplate, "click", "DRAW_QE_RADIO_OPTION", [4]); this.oApp.registerBrowserEvent(this.elBtnBGPalette, "click", "TABLE_QE_TOGGLE_BGC_PALETTE"); // this.oApp.registerBrowserEvent(this.elPanelReviewBtnArea, "click", "SAVE_QE_MY_REVIEW_ITEM"); //My리뷰 버튼 레이어 this.oApp.registerBrowserEvent(this.elBtnBGIMGPalette, "click", "TABLE_QE_TOGGLE_IMG_PALETTE"); this.oApp.registerBrowserEvent(this.elPanelBGIMGPaletteHolder, "click", "TABLE_QE_SET_IMG_FROM_PALETTE"); //this.elPanelQETemplate //this.elBtnQETemplate this.oApp.registerBrowserEvent(this.elBtnQETemplate, "click", "TABLE_QE_TOGGLE_TEMPLATE"); this.oApp.registerBrowserEvent(document.body, "mouseup", "EVENT_OUTER_DOC_MOUSEUP"); this.oApp.registerBrowserEvent(document.body, "mousemove", "EVENT_OUTER_DOC_MOUSEMOVE"); }, $ON_EVENT_EDITING_AREA_KEYUP : function(oEvent){ // for undo/redo and other hotkey functions var oKeyInfo = oEvent.key(); // 229: Korean/Eng, 33, 34: page up/down, 35,36: end/home, 37,38,39,40: left, up, right, down, 16: shift if(oKeyInfo.keyCode == 229 || oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode == 16){ return; }else if(oKeyInfo.keyCode == 8 || oKeyInfo.keyCode == 46){ this.oApp.exec("DELETE_BLOCK_CONTENTS"); oEvent.stop(); } switch(this.nStatus){ case this.STATUS.CELL_SELECTED: this._changeTableEditorStatus(this.STATUS.S_0); break; } }, $ON_TABLE_QE_SELECT_TEMPLATE : function(weEvent){ var aMatch = this.rxLastDigits.exec(weEvent.element.className); var elCurrentTable = this.elSelectionStartTable; this._changeTableEditorStatus(this.STATUS.S_0); this.oApp.exec("STYLE_TABLE", [elCurrentTable, aMatch[1]]); //this._selectTableStyle(aMatch[1]); var elSaveTarget = !!elCurrentTable && elCurrentTable.parentNode ? elCurrentTable.parentNode : null; var sSaveTarget = !elCurrentTable ? "BODY" : null; this.oApp.exec("RECORD_UNDO_ACTION", ["CHANGE_TABLE_STYLE", {elSaveTarget:elSaveTarget, sSaveTarget : sSaveTarget, bDontSaveSelection:true}]); }, $BEFORE_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(sMode !== "WYSIWYG" && this.nStatus !== this.STATUS.S_0){ this._changeTableEditorStatus(this.STATUS.S_0); } }, // [Undo/Redo] Table Selection 처리와 관련된 부분 주석 처리 // $AFTER_DO_RECORD_UNDO_HISTORY : function(){ // if(this.nStatus != this.STATUS.CELL_SELECTED){ // return; // } // // if(this.aSelectedCells.length < 1){ // return; // } // // var aTables = this.oApp.getWYSIWYGDocument().getElementsByTagName("TABLE"); // for(var nTableIdx = 0, nLen = aTables.length; nTableIdx < nLen; nTableIdx++){ // if(aTables[nTableIdx] === this.elSelectionStartTable){ // break; // } // } // // var aUndoHistory = this.oApp.getUndoHistory(); // var oUndoStateIdx = this.oApp.getUndoStateIdx(); // if(!aUndoHistory[oUndoStateIdx.nIdx].htTableSelection){ // aUndoHistory[oUndoStateIdx.nIdx].htTableSelection = []; // } // aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep] = { // nTableIdx : nTableIdx, // nSX : this.htSelectionSPos.x, // nSY : this.htSelectionSPos.y, // nEX : this.htSelectionEPos.x, // nEY : this.htSelectionEPos.y // }; // }, // // $BEFORE_RESTORE_UNDO_HISTORY : function(){ // if(this.nStatus == this.STATUS.CELL_SELECTED){ // var oSelection = this.oApp.getEmptySelection(); // oSelection.selectNode(this.elSelectionStartTable); // oSelection.collapseToEnd(); // oSelection.select(); // } // }, // // $AFTER_RESTORE_UNDO_HISTORY : function(){ // var aUndoHistory = this.oApp.getUndoHistory(); // var oUndoStateIdx = this.oApp.getUndoStateIdx(); // // if(aUndoHistory[oUndoStateIdx.nIdx].htTableSelection && aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep]){ // var htTableSelection = aUndoHistory[oUndoStateIdx.nIdx].htTableSelection[oUndoStateIdx.nStep]; // this.elSelectionStartTable = this.oApp.getWYSIWYGDocument().getElementsByTagName("TABLE")[htTableSelection.nTableIdx]; // this.htMap = this._getCellMapping(this.elSelectionStartTable); // // this.htSelectionSPos.x = htTableSelection.nSX; // this.htSelectionSPos.y = htTableSelection.nSY; // this.htSelectionEPos.x = htTableSelection.nEX; // this.htSelectionEPos.y = htTableSelection.nEY; // this._selectCells(this.htSelectionSPos, this.htSelectionEPos); // // this._startCellSelection(); // this._changeTableEditorStatus(this.STATUS.CELL_SELECTED); // }else{ // this._changeTableEditorStatus(this.STATUS.S_0); // } // }, /** * 테이블 셀 배경색 셋팅 */ $ON_TABLE_QE_TOGGLE_BGC_PALETTE : function(){ if(this.elPanelBGPaletteHolder.parentNode.style.display == "block"){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); }else{ this.oApp.exec("SHOW_TABLE_QE_BGC_PALETTE", []); } }, $ON_SHOW_TABLE_QE_BGC_PALETTE : function(){ this.elPanelBGPaletteHolder.parentNode.style.display = "block"; this.oApp.exec("SHOW_COLOR_PALETTE", ["TABLE_QE_SET_BGC_FROM_PALETTE", this.elPanelBGPaletteHolder]); }, $ON_HIDE_TABLE_QE_BGC_PALETTE : function(){ this.elPanelBGPaletteHolder.parentNode.style.display = "none"; this.oApp.exec("HIDE_COLOR_PALETTE", []); }, $ON_TABLE_QE_SET_BGC_FROM_PALETTE : function(sColorCode){ this.oApp.exec("TABLE_QE_SET_BGC", [sColorCode]); if(this.oSelection){ this.oSelection.select(); } this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TABLE_QE_SET_BGC : function(sColorCode){ this.elBtnBGPalette.style.backgroundColor = sColorCode; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ this.aSelectedCells[i].setAttribute(this.TMP_BGC_ATTR, sColorCode); this.aSelectedCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } this.sQEAction = "TABLE_SET_BGCOLOR"; }, /** * 테이블 리뷰 테이블 배경 이미지 셋팅 */ $ON_TABLE_QE_TOGGLE_IMG_PALETTE : function(){ if(this.elPanelBGIMGPaletteHolder.parentNode.style.display == "block"){ this.oApp.exec("HIDE_TABLE_QE_IMG_PALETTE", []); }else{ this.oApp.exec("SHOW_TABLE_QE_IMG_PALETTE", []); } }, $ON_SHOW_TABLE_QE_IMG_PALETTE : function(){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "block"; }, $ON_HIDE_TABLE_QE_IMG_PALETTE : function(){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "none"; }, $ON_TABLE_QE_SET_IMG_FROM_PALETTE : function(elEvt){ this.oApp.exec("TABLE_QE_SET_IMG", [elEvt.element]); if(this.oSelection){ this.oSelection.select(); } this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TABLE_QE_SET_IMG : function(elSelected){ var sClassName = jindo.$Element(elSelected).className(); var welBtnBGIMGPalette = jindo.$Element(this.elBtnBGIMGPalette); var aBtnClassNames = welBtnBGIMGPalette.className().split(" "); for(var i = 0, nLen = aBtnClassNames.length; i < nLen; i++){ if(aBtnClassNames[i].indexOf("cellimg") > 0){ welBtnBGIMGPalette.removeClass(aBtnClassNames[i]); } } jindo.$Element(this.elBtnBGIMGPalette).addClass(sClassName); var n = sClassName.substring(11, sClassName.length); //se2_cellimg11 var sImageName = "pattern_"; if(n === "0"){ for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ jindo.$Element(this.aSelectedCells[i]).css("backgroundImage", ""); this.aSelectedCells[i].removeAttribute(this.TMP_BGC_ATTR); this.aSelectedCells[i].removeAttribute(this.TMP_BGIMG_ATTR); } }else{ if(n == 19 || n == 20 || n == 21 || n == 22 || n == 25 || n == 26){ //파일 사이즈때문에 jpg sImageName = sImageName + n + ".jpg"; }else{ sImageName = sImageName + n + ".gif"; } for(var j = 0, nLen = this.aSelectedCells.length; j < nLen ; j++){ jindo.$Element(this.aSelectedCells[j]).css("backgroundImage", "url("+"http://static.se2.naver.com/static/img/"+sImageName+")"); this.aSelectedCells[j].removeAttribute(this.TMP_BGC_ATTR); this.aSelectedCells[j].setAttribute(this.TMP_BGIMG_ATTR, "url("+"http://static.se2.naver.com/static/img/"+sImageName+")"); } } this.sQEAction = "TABLE_SET_BGIMAGE"; }, $ON_SAVE_QE_MY_REVIEW_ITEM : function(){ this.oApp.exec("SAVE_MY_REVIEW_ITEM"); this.oApp.exec("CLOSE_QE_LAYER"); }, /** * 테이블 퀵 에디터 Show */ $ON_SHOW_COMMON_QE : function(){ if(jindo.$Element(this.elSelectionStartTable).hasClass(this._sSETblClass)){ this.oApp.exec("SHOW_TABLE_QE"); }else{ if(jindo.$Element(this.elSelectionStartTable).hasClass(this._sSEReviewTblClass)){ this.oApp.exec("SHOW_REVIEW_QE"); } } }, $ON_SHOW_TABLE_QE : function(){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); this.oApp.exec("TABLE_QE_HIDE_TEMPLATE", []); this.oApp.exec("SETUP_TABLE_QE_MODE", [0]); this.oApp.exec("OPEN_QE_LAYER", [this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y], this.elQELayer, "table"]); //this.oApp.exec("FOCUS"); }, $ON_SHOW_REVIEW_QE : function(){ this.oApp.exec("SETUP_TABLE_QE_MODE", [1]); this.oApp.exec("OPEN_QE_LAYER", [this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y], this.elQELayer, "review"]); }, $ON_CLOSE_SUB_LAYER_QE : function(){ if(typeof this.elPanelBGPaletteHolder != 'undefined'){ this.elPanelBGPaletteHolder.parentNode.style.display = "none"; } if(typeof this.elPanelBGIMGPaletteHolder != 'undefined'){ this.elPanelBGIMGPaletteHolder.parentNode.style.display = "none"; } }, // 0: table // 1: review $ON_SETUP_TABLE_QE_MODE : function(nMode){ var bEnableMerge = true; if(typeof nMode == "number"){ this.nQEMode = nMode; } if(this.aSelectedCells.length < 2){ bEnableMerge = false; } this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_MERGE_BTN, bEnableMerge]); //null인경우를 대비해서 default값을 지정해준다. var sBackgroundColor = this.aSelectedCells[0].getAttribute(this.TMP_BGC_ATTR) || "rgb(255,255,255)"; var bAllMatched = true; for(var i = 1, nLen = this.aSelectedCells.length; i < nLen; i++){ if(sBackgroundColor != this.aSelectedCells[i].getAttribute(this.TMP_BGC_ATTR)){ bAllMatched = false; break; } } if(bAllMatched){ this.elBtnBGPalette.style.backgroundColor = sBackgroundColor; }else{ this.elBtnBGPalette.style.backgroundColor = "#FFFFFF"; } var sBackgroundImage = this.aSelectedCells[0].getAttribute(this.TMP_BGIMG_ATTR) || ""; var bAllMatchedImage = true; var sPatternInfo, nPatternImage = 0; var welBtnBGIMGPalette = jindo.$Element(this.elBtnBGIMGPalette); if(!!sBackgroundImage){ var aPattern = sBackgroundImage.match(/\_[0-9]*/); sPatternInfo = (!!aPattern)?aPattern[0] : "_0"; nPatternImage = sPatternInfo.substring(1, sPatternInfo.length); for(var i = 1, nLen = this.aSelectedCells.length; i < nLen; i++){ if(sBackgroundImage != this.aSelectedCells[i].getAttribute(this.TMP_BGIMG_ATTR)){ bAllMatchedImage = false; break; } } } var aBtnClassNames = welBtnBGIMGPalette.className().split(/\s/); for(var j = 0, nLen = aBtnClassNames.length; j < nLen; j++){ if(aBtnClassNames[j].indexOf("cellimg") > 0){ welBtnBGIMGPalette.removeClass(aBtnClassNames[j]); } } if(bAllMatchedImage && nPatternImage > 0){ welBtnBGIMGPalette.addClass("se2_cellimg" + nPatternImage); }else{ welBtnBGIMGPalette.addClass("se2_cellimg0"); } if(this.nQEMode === 0){ //table this.elPanelTableTemplateArea.style.display = "block"; // this.elSelectBoxTemplate.style.display = "block"; this.elPanelReviewBGArea.style.display = "none"; // this.elSelectBoxTemplate.style.position = ""; //this.elPanelReviewBtnArea.style.display = "none"; //My리뷰 버튼 레이어 // 배경Area에서 css를 제거해야함 jindo.$Element(this.elPanelTableBGArea).className("se2_qe2"); var nTpl = this.parseIntOr0(this.elSelectionStartTable.getAttribute(this.ATTR_TBL_TEMPLATE)); if(nTpl){ //this.elInputRadioTemplate.checked = "true"; }else{ this.elInputRadioBGColor.checked = "true"; nTpl = 1; } this.elPanelQETemplatePreview.className = "se2_t_style" + nTpl; this.elPanelBGImg.style.position = ""; }else if(this.nQEMode == 1){ //review this.elPanelTableTemplateArea.style.display = "none"; // this.elSelectBoxTemplate.style.display = "none"; this.elPanelReviewBGArea.style.display = "block"; // this.elSelectBoxTemplate.style.position = "static"; // this.elPanelReviewBtnArea.style.display = "block"; //My리뷰 버튼 레이어 var nTpl = this.parseIntOr0(this.elSelectionStartTable.getAttribute(this.ATTR_REVIEW_TEMPLATE)); this.elPanelBGImg.style.position = "relative"; }else{ this.elPanelTableTemplateArea.style.display = "none"; this.elPanelReviewBGArea.style.display = "none"; // this.elPanelReviewBtnArea.style.display = "none"; //My리뷰 버튼 레이어 } this.oApp.exec("DRAW_QE_RADIO_OPTION", [0]); }, // nClickedIdx // 0: none // 2: bg color // 3: bg img // 4: template $ON_DRAW_QE_RADIO_OPTION : function(nClickedIdx){ if(nClickedIdx !== 0 && nClickedIdx != 2){ this.oApp.exec("HIDE_TABLE_QE_BGC_PALETTE", []); } if(nClickedIdx !== 0 && nClickedIdx != 3){ this.oApp.exec("HIDE_TABLE_QE_IMG_PALETTE", []); } if(nClickedIdx !== 0 && nClickedIdx != 4){ this.oApp.exec("TABLE_QE_HIDE_TEMPLATE", []); } if(this.nQEMode === 0){ // bg image option does not exist in table mode. so select the bgcolor option if(this.elInputRadioBGImg.checked){ this.elInputRadioBGColor.checked = "true"; } if(this.elInputRadioBGColor.checked){ // one dimming layer is being shared so only need to dim once and the rest will be undimmed automatically //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, true]); this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_TABLE_TEMPLATE, false]); }else{ this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, false]); //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_TABLE_TEMPLATE, true]); } }else{ // template option does not exist in review mode. so select the bgcolor optio if(this.elInputRadioTemplate.checked){ this.elInputRadioBGColor.checked = "true"; } if(this.elInputRadioBGColor.checked){ //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, true]); this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_REVIEW_BG_IMG, false]); }else{ this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_BG_COLOR, false]); //this.oApp.exec("TABLE_QE_DIM", [this.QE_DIM_REVIEW_BG_IMG, true]); } } }, // nPart // 1: Merge cell btn // 2: Cell bg color // 3: Review - bg image // 4: Table - Template // // bUndim // true: Undim // false(default): Dim $ON_TABLE_QE_DIM : function(nPart, bUndim){ var elPanelDim; var sDimClassPrefix = "se2_qdim"; if(nPart == 1){ elPanelDim = this.elPanelDim1; }else{ elPanelDim = this.elPanelDim2; } if(bUndim){ nPart = 0; } elPanelDim.className = sDimClassPrefix + nPart; }, $ON_TE_SELECT_TABLE : function(elTable){ this.elSelectionStartTable = elTable; this.htMap = this._getCellMapping(this.elSelectionStartTable); }, $ON_TE_SELECT_CELLS : function(htSPos, htEPos){ this._selectCells(htSPos, htEPos); }, $ON_TE_MERGE_CELLS : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1){ return; } this._removeClassFromSelection(); var i, elFirstTD, elTD; elFirstTD = this.aSelectedCells[0]; var elTable = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elFirstTD); var nHeight, nWidth; var elCurTD, elLastTD = this.aSelectedCells[0]; nHeight = parseInt(elLastTD.style.height || elLastTD.getAttribute("height"), 10); nWidth = parseInt(elLastTD.style.width || elLastTD.getAttribute("width"), 10); //nHeight = elLastTD.offsetHeight; //nWidth = elLastTD.offsetWidth; for(i = this.htSelectionSPos.x + 1; i < this.htSelectionEPos.x + 1; i++){ curTD = this.htMap[i][this.htSelectionSPos.y]; if(curTD == elLastTD){ continue; } elLastTD = curTD; nWidth += parseInt(curTD.style.width || curTD.getAttribute("width"), 10); //nWidth += curTD.offsetWidth; } elLastTD = this.aSelectedCells[0]; for(i = this.htSelectionSPos.y + 1; i < this.htSelectionEPos.y + 1; i++){ curTD = this.htMap[this.htSelectionSPos.x][i]; if(curTD == elLastTD){ continue; } elLastTD = curTD; nHeight += parseInt(curTD.style.height || curTD.getAttribute("height"), 10); //nHeight += curTD.offsetHeight; } if(nWidth){ elFirstTD.style.width = nWidth + "px"; } if(nHeight){ elFirstTD.style.height = nHeight + "px"; } elFirstTD.setAttribute("colSpan", this.htSelectionEPos.x - this.htSelectionSPos.x + 1); elFirstTD.setAttribute("rowSpan", this.htSelectionEPos.y - this.htSelectionSPos.y + 1); for(i = 1; i < this.aSelectedCells.length; i++){ elTD = this.aSelectedCells[i]; if(elTD.parentNode){ if(!nhn.husky.SE2M_Utils.isBlankNode(elTD)){ elFirstTD.innerHTML += elTD.innerHTML; } elTD.parentNode.removeChild(elTD); } } // this._updateSelection(); this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "TABLE_CELL_MERGE"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_TABLE_QE_TOGGLE_TEMPLATE : function(){ if(this.elPanelQETemplate.style.display == "block"){ this.oApp.exec("TABLE_QE_HIDE_TEMPLATE"); }else{ this.oApp.exec("TABLE_QE_SHOW_TEMPLATE"); } }, $ON_TABLE_QE_SHOW_TEMPLATE : function(){ this.elPanelQETemplate.style.display = "block"; this.oApp.exec("POSITION_TOOLBAR_LAYER", [this.elPanelQETemplate]); }, $ON_TABLE_QE_HIDE_TEMPLATE : function(){ this.elPanelQETemplate.style.display = "none"; }, $ON_STYLE_TABLE : function(elTable, nTableStyleIdx){ if(!elTable){ if(!this._t){ this._t = 1; } elTable = this.elSelectionStartTable; nTableStyleIdx = (this._t++) % 20 + 1; } if(this.oSelection){ this.oSelection.select(); } this._applyTableTemplate(elTable, nTableStyleIdx); }, $ON_TE_DELETE_COLUMN : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1) { return; } this._selectAll_Column(); this._deleteSelectedCells(); this.sQEAction = "DELETE_TABLE_COLUMN"; this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TE_DELETE_ROW : function(){ if(this.aSelectedCells.length === 0 || this.aSelectedCells.length == 1) { return; } this._selectAll_Row(); this._deleteSelectedCells(); this.sQEAction = "DELETE_TABLE_ROW"; this._changeTableEditorStatus(this.STATUS.S_0); }, $ON_TE_INSERT_COLUMN_RIGHT : function(){ if(this.aSelectedCells.length === 0) { return; } this._selectAll_Column(); this._insertColumnAfter(this.htSelectionEPos.x); }, $ON_TE_INSERT_COLUMN_LEFT : function(){ this._selectAll_Column(); this._insertColumnAfter(this.htSelectionSPos.x - 1); }, $ON_TE_INSERT_ROW_BELOW : function(){ if(this.aSelectedCells.length === 0) { return; } this._insertRowBelow(this.htSelectionEPos.y); }, $ON_TE_INSERT_ROW_ABOVE : function(){ this._insertRowBelow(this.htSelectionSPos.y - 1); }, $ON_TE_SPLIT_COLUMN : function(){ var nSpan, nNewSpan, nWidth, nNewWidth; var elCurCell, elNewTD; if(this.aSelectedCells.length === 0) { return; } this._removeClassFromSelection(); var elLastCell = this.aSelectedCells[0]; // Assign colSpan>1 to all selected cells. // If current colSpan == 1 then increase the colSpan of the cell and all the vertically adjacent cells. for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; if(nSpan > 1){ continue; } var htPos = this._getBasisCellPosition(elCurCell); for(var y = 0; y < this.htMap[0].length;){ elCurCell = this.htMap[htPos.x][y]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; elCurCell.setAttribute("colSpan", nSpan+1); y += parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; } } for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; nNewSpan = (nSpan/2).toFixed(0); elCurCell.setAttribute("colSpan", nNewSpan); elNewTD = this._shallowCloneTD(elCurCell); elNewTD.setAttribute("colSpan", nSpan-nNewSpan); elLastCell = elNewTD; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; elNewTD.setAttribute("rowSpan", nSpan); elNewTD.innerHTML = "&nbsp;"; nWidth = elCurCell.width || elCurCell.style.width; if(nWidth){ nWidth = this.parseIntOr0(nWidth); elCurCell.removeAttribute("width"); nNewWidth = (nWidth/2).toFixed(); elCurCell.style.width = nNewWidth + "px"; elNewTD.style.width = (nWidth - nNewWidth) + "px"; } elCurCell.parentNode.insertBefore(elNewTD, elCurCell.nextSibling); } this._reassignCellSizes(this.elSelectionStartTable); this.htMap = this._getCellMapping(this.elSelectionStartTable); var htPos = this._getBasisCellPosition(elLastCell); this.htSelectionEPos.x = htPos.x; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this.sQEAction = "SPLIT_TABLE_COLUMN"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_TE_SPLIT_ROW : function(){ var nSpan, nNewSpan, nHeight, nHeight; var elCurCell, elNewTD, htPos, elNewTR; if(this.aSelectedCells.length === 0) { return; } var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); this._removeClassFromSelection(); //top.document.title = this.htSelectionSPos.x+","+this.htSelectionSPos.y+"::"+this.htSelectionEPos.x+","+this.htSelectionEPos.y; var nNewRows = 0; // Assign rowSpan>1 to all selected cells. // If current rowSpan == 1 then increase the rowSpan of the cell and all the horizontally adjacent cells. var elNextTRInsertionPoint; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; if(nSpan > 1){ continue; } htPos = this._getBasisCellPosition(elCurCell); elNextTRInsertionPoint = aTR[htPos.y]; // a new TR has to be inserted when there's an increase in rowSpan elNewTR = this.oApp.getWYSIWYGDocument().createElement("TR"); elNextTRInsertionPoint.parentNode.insertBefore(elNewTR, elNextTRInsertionPoint.nextSibling); nNewRows++; // loop through horizontally adjacent cells and increase their rowSpan for(var x = 0; x < this.htMap.length;){ elCurCell = this.htMap[x][htPos.y]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; elCurCell.setAttribute("rowSpan", nSpan + 1); x += parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; } } aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var htPos1, htPos2; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elCurCell = this.aSelectedCells[i]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; nNewSpan = (nSpan/2).toFixed(0); elCurCell.setAttribute("rowSpan", nNewSpan); elNewTD = this._shallowCloneTD(elCurCell); elNewTD.setAttribute("rowSpan", nSpan - nNewSpan); nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; elNewTD.setAttribute("colSpan", nSpan); elNewTD.innerHTML = "&nbsp;"; nHeight = elCurCell.height || elCurCell.style.height; if(nHeight){ nHeight = this.parseIntOr0(nHeight); elCurCell.removeAttribute("height"); nNewHeight = (nHeight/2).toFixed(); elCurCell.style.height = nNewHeight + "px"; elNewTD.style.height = (nHeight - nNewHeight) + "px"; } //var elTRInsertTo = elCurCell.parentNode; //for(var ii=0; ii<nNewSpan; ii++) elTRInsertTo = elTRInsertTo.nextSibling; var nTRIdx = jindo.$A(aTR).indexOf(elCurCell.parentNode); var nNextTRIdx = parseInt(nTRIdx, 10)+parseInt(nNewSpan, 10); var elTRInsertTo = aTR[nNextTRIdx]; var oSiblingTDs = elTRInsertTo.childNodes; var elInsertionPt = null; var tmp; htPos1 = this._getBasisCellPosition(elCurCell); for(var ii = 0, nNumTDs = oSiblingTDs.length; ii < nNumTDs; ii++){ tmp = oSiblingTDs[ii]; if(!tmp.tagName || tmp.tagName != "TD"){ continue; } htPos2 = this._getBasisCellPosition(tmp); if(htPos1.x < htPos2.x){ elInsertionPt = tmp; break; } } elTRInsertTo.insertBefore(elNewTD, elInsertionPt); } this._reassignCellSizes(this.elSelectionStartTable); this.htMap = this._getCellMapping(this.elSelectionStartTable); this.htSelectionEPos.y += nNewRows; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this.sQEAction = "SPLIT_TABLE_ROW"; this.oApp.exec("SHOW_COMMON_QE"); }, $ON_MSG_CELL_SELECTED : function(){ // disable row/col delete btn this.elPanelDimDelCol.className = "se2_qdim6r"; this.elPanelDimDelRow.className = "se2_qdim6c"; if(this.htSelectionSPos.x === 0 && this.htSelectionEPos.x === this.htMap.length - 1){ this.oApp.exec("MSG_ROW_SELECTED"); } if(this.htSelectionSPos.y === 0 && this.htSelectionEPos.y === this.htMap[0].length - 1){ this.oApp.exec("MSG_COL_SELECTED"); } this.oApp.exec("SHOW_COMMON_QE"); }, $ON_MSG_ROW_SELECTED : function(){ this.elPanelDimDelRow.className = ""; }, $ON_MSG_COL_SELECTED : function(){ this.elPanelDimDelCol.className = ""; }, $ON_EVENT_EDITING_AREA_MOUSEDOWN : function(wevE){ if(!this.oApp.isWYSIWYGEnabled()){ return; } switch(this.nStatus){ case this.STATUS.S_0: // the user may just want to resize the image if(!wevE.element){return;} if(wevE.element.tagName == "IMG"){return;} if(this.oApp.getEditingMode() !== "WYSIWYG"){return;} // change the status to MOUSEDOWN_CELL if the mouse is over a table cell var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if(elTD && elTD.tagName == "TD"){ var elTBL = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elTD); if(!jindo.$Element(elTBL).hasClass(this._sSETblClass) && !jindo.$Element(elTBL).hasClass(this._sSEReviewTblClass)){return;} if(!this._isValidTable(elTBL)){ jindo.$Element(elTBL).removeClass(this._sSETblClass); jindo.$Element(elTBL).removeClass(this._sSEReviewTblClass) return; } if(elTBL){ this.elSelectionStartTD = elTD; this.elSelectionStartTable = elTBL; this._changeTableEditorStatus(this.STATUS.MOUSEDOWN_CELL); } } break; case this.STATUS.MOUSEDOWN_CELL: break; case this.STATUS.CELL_SELECTING: break; case this.STATUS.CELL_SELECTED: this._changeTableEditorStatus(this.STATUS.S_0); break; } }, $ON_EVENT_EDITING_AREA_MOUSEMOVE : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG"){return;} switch(this.nStatus){ case this.STATUS.S_0: // if(this._isOnBorder(wevE)){ //this._changeTableEditorStatus(this.MOUSEOVER_BORDER); this._showCellResizeGrip(wevE); }else{ this._hideResizer(); } break; case this.STATUS.MOUSEDOWN_CELL: // change the status to CELL_SELECTING if the mouse moved out of the inital TD var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if((elTD && elTD !== this.elSelectionStartTD) || !elTD){ if(!elTD){elTD = this.elSelectionStartTD;} this._reassignCellSizes(this.elSelectionStartTable); this._startCellSelection(); this._selectBetweenCells(this.elSelectionStartTD, elTD); } break; case this.STATUS.CELL_SELECTING: // show selection var elTD = nhn.husky.SE2M_Utils.findAncestorByTagName("TD", wevE.element); if(!elTD || elTD === this.elLastSelectedTD){return;} var elTBL = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", elTD); if(elTBL !== this.elSelectionStartTable){return;} this.elLastSelectedTD = elTD; this._selectBetweenCells(this.elSelectionStartTD, elTD); break; case this.STATUS.CELL_SELECTED: break; } }, // 셀 선택 상태에서 문서영역을 상/하로 벗어날 경우, 벗어난 방향으로 선택 셀을 늘려가며 문서의 스크롤을 해줌 $ON_EVENT_OUTER_DOC_MOUSEMOVE : function(wevE){ switch(this.nStatus){ case this.STATUS.CELL_SELECTING: var htPos = wevE.pos(); var nYPos = htPos.pageY; var nXPos = htPos.pageX; if(nYPos < this.htEditingAreaPos.top){ var y = this.htSelectionSPos.y; if(y > 0){ this.htSelectionSPos.y--; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.aSelectedCells[0]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ if(nYPos > this.htEditingAreaPos.bottom){ var y = this.htSelectionEPos.y; if(y < this.htMap[0].length - 1){ this.htSelectionEPos.y++; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } } } if(nXPos < this.htEditingAreaPos.left){ var x = this.htSelectionSPos.x; if(x > 0){ this.htSelectionSPos.x--; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.aSelectedCells[0]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ if(nXPos > this.htEditingAreaPos.right){ var x = this.htSelectionEPos.x; if(x < this.htMap.length - 1){ this.htSelectionEPos.x++; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); var oSelection = this.oApp.getSelection(); oSelection.selectNodeContents(this.htMap[this.htSelectionEPos.x][this.htSelectionEPos.y]); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } } } break; } }, $ON_EVENT_OUTER_DOC_MOUSEUP : function(wevE){ this._eventEditingAreaMouseup(wevE); }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(wevE){ this._eventEditingAreaMouseup(wevE); }, _eventEditingAreaMouseup : function(wevE){ if(this.oApp.getEditingMode() != "WYSIWYG"){return;} switch(this.nStatus){ case this.STATUS.S_0: break; case this.STATUS.MOUSEDOWN_CELL: this._changeTableEditorStatus(this.STATUS.S_0); break; case this.STATUS.CELL_SELECTING: this._changeTableEditorStatus(this.STATUS.CELL_SELECTED); break; case this.STATUS.CELL_SELECTED: break; } }, /** * Table의 block으로 잡힌 영역을 넘겨준다. * @see hp_SE2M_TableBlockStyler.js */ $ON_GET_SELECTED_CELLS : function(sAttr,oReturn){ if(!!this.aSelectedCells){ oReturn[sAttr] = this.aSelectedCells; } }, _coverResizeLayer : function(){ this.elResizeCover.style.position = "absolute"; var size = jindo.$Document().clientSize(); this.elResizeCover.style.width = size.width - this.nPageLeftRightMargin + "px"; this.elResizeCover.style.height = size.height - this.nPageTopBottomMargin + "px"; //this.elResizeCover.style.width = size.width + "px"; //this.elResizeCover.style.height = size.height + "px"; //document.body.insertBefore(this.elResizeCover, document.body.firstChild); document.body.appendChild(this.elResizeCover); }, _uncoverResizeLayer : function(){ this.elResizeGrid.appendChild(this.elResizeCover); this.elResizeCover.style.position = ""; this.elResizeCover.style.width = "100%"; this.elResizeCover.style.height = "100%"; }, _reassignCellSizes : function(elTable){ var allCells = new Array(2); allCells[0] = jindo.$$(">TBODY>TR>TD", elTable, {oneTimeOffCache:true}); allCells[1] = jindo.$$(">TBODY>TR>TH", elTable, {oneTimeOffCache:true}); var aAllCellsWithSizeInfo = new Array(allCells[0].length + allCells[1].length); var numCells = 0; var nTblBorderPadding = this.parseIntOr0(elTable.border); var nTblCellPadding = this.parseIntOr0(elTable.cellPadding); // remember all the dimensions first and then assign later. // this is done this way because if the table/cell size were set in %, setting one cell size would change size of other cells, which are still yet in %. // 1 for TD and 1 for TH for(var n = 0; n < 2; n++){ for(var i = 0; i < allCells[n].length; i++){ var elCell = allCells[n][i]; var welCell = jindo.$Element(elCell); var nPaddingLeft = this.parseIntOr0(welCell.css("paddingLeft")); var nPaddingRight = this.parseIntOr0(welCell.css("paddingRight")); var nPaddingTop = this.parseIntOr0(welCell.css("paddingTop")); var nPaddingBottom = this.parseIntOr0(welCell.css("paddingBottom")); var nBorderLeft = this.parseBorder(welCell.css("borderLeftWidth"), welCell.css("borderLeftStyle")); var nBorderRight = this.parseBorder(welCell.css("borderRightWidth"), welCell.css("borderRightStyle")); var nBorderTop = this.parseBorder(welCell.css("borderTopWidth"), welCell.css("borderTopStyle")); var nBorderBottom = this.parseBorder(welCell.css("borderBottomWidth"), welCell.css("borderBottomStyle")); var nOffsetWidth, nOffsetHeight; if(this.oApp.oNavigator["firefox"]){ // Firefox nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight + "px"; }else{ // IE, Chrome nOffsetWidth = elCell.offsetWidth - (nPaddingLeft + nPaddingRight + nBorderLeft + nBorderRight) + "px"; nOffsetHeight = elCell.offsetHeight - (nPaddingTop + nPaddingBottom + nBorderTop + nBorderBottom) + "px"; } aAllCellsWithSizeInfo[numCells++] = [elCell, nOffsetWidth, nOffsetHeight ]; } } for(var i = 0; i < numCells; i++){ var aCellInfo = aAllCellsWithSizeInfo[i]; aCellInfo[0].removeAttribute("width"); aCellInfo[0].removeAttribute("height"); aCellInfo[0].style.width = aCellInfo[1]; aCellInfo[0].style.height = aCellInfo[2]; // jindo.$Element(aCellInfo[0]).css("width", aCellInfo[1]); // jindo.$Element(aCellInfo[0]).css("height", aCellInfo[2]); } elTable.removeAttribute("width"); elTable.removeAttribute("height"); elTable.style.width = ""; elTable.style.height = ""; }, _mousedown_ResizeCover : function(oEvent){ this.bResizing = true; this.nStartHeight = oEvent.pos().clientY; this.wfnMousemove_ResizeCover.attach(this.elResizeCover, "mousemove"); this.wfnMouseup_ResizeCover.attach(document, "mouseup"); this._coverResizeLayer(); this.elResizeGrid.style.border = "1px dotted black"; this.nStartHeight = oEvent.pos().clientY; this.nStartWidth = oEvent.pos().clientX; this._reassignCellSizes(this.htResizing.elTable); this.htMap = this._getCellMapping(this.htResizing.elTable); var htPosition = this._getBasisCellPosition(this.htResizing.elCell); var nOffsetX = (parseInt(this.htResizing.elCell.getAttribute("colspan")) || 1) - 1; var nOffsetY = (parseInt(this.htResizing.elCell.getAttribute("rowspan")) || 1) - 1; var x = htPosition.x + nOffsetX + this.htResizing.nHA; var y = htPosition.y + nOffsetY + this.htResizing.nVA; if(x < 0 || y < 0){return;} this.htAllAffectedCells = this._getAllAffectedCells(x, y, this.htResizing.nResizeMode, this.htResizing.elTable); }, _mousemove_ResizeCover : function(oEvent){ var nHeightChange = oEvent.pos().clientY - this.nStartHeight; var nWidthChange = oEvent.pos().clientX - this.nStartWidth; var oEventPos = oEvent.pos(); if(this.htResizing.nResizeMode == 1){ this.elResizeGrid.style.left = oEventPos.pageX - this.parseIntOr0(this.elResizeGrid.style.width)/2 + "px"; }else{ this.elResizeGrid.style.top = oEventPos.pageY - this.parseIntOr0(this.elResizeGrid.style.height)/2 + "px"; } }, _mouseup_ResizeCover : function(oEvent){ this.bResizing = false; this._hideResizer(); this._uncoverResizeLayer(); this.elResizeGrid.style.border = ""; this.wfnMousemove_ResizeCover.detach(this.elResizeCover, "mousemove"); this.wfnMouseup_ResizeCover.detach(document, "mouseup"); var nHeightChange = 0; var nWidthChange = 0; if(this.htResizing.nResizeMode == 2){ nHeightChange = oEvent.pos().clientY - this.nStartHeight; } if(this.htResizing.nResizeMode == 1){ nWidthChange = oEvent.pos().clientX - this.nStartWidth; if(this.htAllAffectedCells.nMinBefore != -1 && nWidthChange < -1*this.htAllAffectedCells.nMinBefore){ nWidthChange = -1 * this.htAllAffectedCells.nMinBefore + this.MIN_CELL_WIDTH; } if(this.htAllAffectedCells.nMinAfter != -1 && nWidthChange > this.htAllAffectedCells.nMinAfter){ nWidthChange = this.htAllAffectedCells.nMinAfter - this.MIN_CELL_WIDTH; } } var aCellsBefore = this.htAllAffectedCells.aCellsBefore; for(var i = 0; i < aCellsBefore.length; i++){ var elCell = aCellsBefore[i]; var width = this.parseIntOr0(elCell.style.width) + nWidthChange; elCell.style.width = Math.max(width, this.MIN_CELL_WIDTH) + "px"; var height = this.parseIntOr0(elCell.style.height) + nHeightChange; elCell.style.height = Math.max(height, this.MIN_CELL_HEIGHT) + "px"; } var aCellsAfter = this.htAllAffectedCells.aCellsAfter; for(var i = 0; i < aCellsAfter.length; i++){ var elCell = aCellsAfter[i]; var width = this.parseIntOr0(elCell.style.width) - nWidthChange; elCell.style.width = Math.max(width, this.MIN_CELL_WIDTH) + "px"; var height = this.parseIntOr0(elCell.style.height) - nHeightChange; elCell.style.height = Math.max(height, this.MIN_CELL_HEIGHT) + "px"; } }, $ON_CLOSE_QE_LAYER : function(){ this._changeTableEditorStatus(this.STATUS.S_0); }, _changeTableEditorStatus : function(nNewStatus){ if(this.nStatus == nNewStatus){return;} this.nStatus = nNewStatus; switch(nNewStatus){ case this.STATUS.S_0: if(this.nStatus == this.STATUS.MOUSEDOWN_CELL){ break; } this._deselectCells(); // 히스토리 저장 (선택 위치는 저장하지 않음) if(!!this.sQEAction){ this.oApp.exec("RECORD_UNDO_ACTION", [this.sQEAction, {elSaveTarget:this.elSelectionStartTable, bDontSaveSelection:true}]); this.sQEAction = ""; } if(this.oApp.oNavigator["safari"] || this.oApp.oNavigator["chrome"]){ this.oApp.getWYSIWYGDocument().onselectstart = null; } this.oApp.exec("ENABLE_WYSIWYG", []); this.oApp.exec("CLOSE_QE_LAYER"); this.elSelectionStartTable = null; break; case this.STATUS.CELL_SELECTING: if(this.oApp.oNavigator.ie){ document.body.setCapture(false); } break; case this.STATUS.CELL_SELECTED: this.oApp.delayedExec("MSG_CELL_SELECTED", [], 0); if(this.oApp.oNavigator.ie){ document.body.releaseCapture(); } break; } this.oApp.exec("TABLE_EDITOR_STATUS_CHANGED", [this.nStatus]); }, _isOnBorder : function(wevE){ // ===========================[Start: Set/init global resizing info]=========================== // 0: not resizing // 1: horizontal resizing // 2: vertical resizing this.htResizing.nResizeMode = 0; this.htResizing.elCell = wevE.element; if(wevE.element.tagName != "TD" && wevE.element.tagName != "TH"){return false;} this.htResizing.elTable = nhn.husky.SE2M_Utils.findAncestorByTagName("TABLE", this.htResizing.elCell); if(!this.htResizing.elTable){return;} if(!jindo.$Element(this.htResizing.elTable).hasClass(this._sSETblClass) && !jindo.$Element(this.htResizing.elTable).hasClass(this._sSEReviewTblClass)){return;} // Adjustment variables: to be used to map the x, y position of the resizing point relative to elCell // eg) When left border of a cell at 2,2 is selected, the actual cell that has to be resized is the one at 1,2. So, set the horizontal adjustment to -1. // Vertical Adjustment this.htResizing.nVA = 0; // Horizontal Adjustment this.htResizing.nHA = 0; this.htResizing.nBorderLeftPos = 0; this.htResizing.nBorderTopPos = -1; this.htResizing.htEPos = wevE.pos(true); this.htResizing.nBorderSize = this.parseIntOr0(this.htResizing.elTable.border); // ===========================[E N D: Set/init global resizing info]=========================== // Separate info is required as the offsetX/Y are different in IE and FF // For IE, (0, 0) is top left corner of the cell including the border. // For FF, (0, 0) is top left corner of the cell excluding the border. var nAdjustedDraggableCellEdge1; var nAdjustedDraggableCellEdge2; if(jindo.$Agent().navigator().ie || jindo.$Agent().navigator().safari){ nAdjustedDraggableCellEdge1 = this.htResizing.nBorderSize + this.nDraggableCellEdge; nAdjustedDraggableCellEdge2 = this.nDraggableCellEdge; }else{ nAdjustedDraggableCellEdge1 = this.nDraggableCellEdge; nAdjustedDraggableCellEdge2 = this.htResizing.nBorderSize + this.nDraggableCellEdge; } // top border of the cell is selected if(this.htResizing.htEPos.offsetY <= nAdjustedDraggableCellEdge1){ // top border of the first cell can't be dragged if(this.htResizing.elCell.parentNode.previousSibling){ this.htResizing.nVA = -1; this.htResizing.nResizeMode = 2; } } // bottom border of the cell is selected if(this.htResizing.elCell.offsetHeight-nAdjustedDraggableCellEdge2 <= this.htResizing.htEPos.offsetY){ this.htResizing.nBorderTopPos = this.htResizing.elCell.offsetHeight + nAdjustedDraggableCellEdge1 - 1; this.htResizing.nResizeMode = 2; } // left border of the cell is selected if(this.htResizing.htEPos.offsetX <= nAdjustedDraggableCellEdge1){ // left border of the first cell can't be dragged if(this.htResizing.elCell.previousSibling){ this.htResizing.nHA = -1; this.htResizing.nResizeMode = 0; } } // right border of the cell is selected if(this.htResizing.elCell.offsetWidth - nAdjustedDraggableCellEdge2 <= this.htResizing.htEPos.offsetX){ this.htResizing.nBorderLeftPos = this.htResizing.elCell.offsetWidth + nAdjustedDraggableCellEdge1 - 1; this.htResizing.nResizeMode = 1; } if(this.htResizing.nResizeMode === 0){return false;} return true; }, _showCellResizeGrip : function(){ if(this.htResizing.nResizeMode == 1){ this.elResizeCover.style.cursor = "col-resize"; }else{ this.elResizeCover.style.cursor = "row-resize"; } this._showResizer(); if(this.htResizing.nResizeMode == 1){ this._setResizerSize((this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2, this.parseIntOr0(jindo.$Element(this.elIFrame).css("height"))); jindo.$Element(this.elResizeGrid).offset(this.htFrameOffset.top, this.htFrameOffset.left + this.htResizing.htEPos.clientX - this.parseIntOr0(this.elResizeGrid.style.width)/2 - this.htResizing.htEPos.offsetX + this.htResizing.nBorderLeftPos); }else{ //가변폭을 지원하기 때문에 매번 현재 Container의 크기를 구해와서 Grip을 생성해야 한다. var elIFrameWidth = this.oApp.elEditingAreaContainer.offsetWidth + "px"; this._setResizerSize(this.parseIntOr0(elIFrameWidth), (this.htResizing.nBorderSize + this.nDraggableCellEdge) * 2); jindo.$Element(this.elResizeGrid).offset(this.htFrameOffset.top + this.htResizing.htEPos.clientY - this.parseIntOr0(this.elResizeGrid.style.height)/2 - this.htResizing.htEPos.offsetY + this.htResizing.nBorderTopPos, this.htFrameOffset.left); } }, _getAllAffectedCells : function(basis_x, basis_y, iResizeMode, oTable){ if(!oTable){return [];} var oTbl = this._getCellMapping(oTable); var iTblX = oTbl.length; var iTblY = oTbl[0].length; // 선택 테두리의 앞쪽 셀 var aCellsBefore = []; // 선택 테두리의 뒤쪽 셀 var aCellsAfter = []; var htResult; var nMinBefore = -1, nMinAfter = -1; // horizontal resizing -> need to get vertical rows if(iResizeMode == 1){ for(var y = 0; y < iTblY; y++){ if(aCellsBefore.length>0 && aCellsBefore[aCellsBefore.length-1] == oTbl[basis_x][y]){continue;} aCellsBefore[aCellsBefore.length] = oTbl[basis_x][y]; var nWidth = parseInt(oTbl[basis_x][y].style.width); if(nMinBefore == -1 || nMinBefore > nWidth){ nMinBefore = nWidth; } } if(oTbl.length > basis_x+1){ for(var y = 0; y < iTblY; y++){ if(aCellsAfter.length>0 && aCellsAfter[aCellsAfter.length-1] == oTbl[basis_x+1][y]){continue;} aCellsAfter[aCellsAfter.length] = oTbl[basis_x+1][y]; var nWidth = parseInt(oTbl[basis_x + 1][y].style.width); if(nMinAfter == -1 || nMinAfter > nWidth){ nMinAfter = nWidth; } } } htResult = {aCellsBefore: aCellsBefore, aCellsAfter: aCellsAfter, nMinBefore: nMinBefore, nMinAfter: nMinAfter}; }else{ for(var x = 0; x < iTblX; x++){ if(aCellsBefore.length>0 && aCellsBefore[aCellsBefore.length - 1] == oTbl[x][basis_y]){continue;} aCellsBefore[aCellsBefore.length] = oTbl[x][basis_y]; if(nMinBefore == -1 || nMinBefore > oTbl[x][basis_y].style.height){ nMinBefore = oTbl[x][basis_y].style.height; } } // 높이 리사이징 시에는 선택 테두리 앞쪽 셀만 조절 함으로 아래쪽 셀은 생성 할 필요 없음 htResult = {aCellsBefore: aCellsBefore, aCellsAfter: aCellsAfter, nMinBefore: nMinBefore, nMinAfter: nMinAfter}; } return htResult; }, _createCellResizeGrip : function(){ this.elTmp = document.createElement("DIV"); try{ this.elTmp.innerHTML = '<div style="position:absolute; overflow:hidden; z-index: 99; "><div onmousedown="return false" style="background-color:#000000;filter:alpha(opacity=0);opacity:0.0;-moz-opacity:0.0;-khtml-opacity:0.0;cursor: col-resize; left: 0px; top: 0px; width: 100%; height: 100%;font-size:1px;z-index: 999; "></div></div>'; this.elResizeGrid = this.elTmp.firstChild; this.elResizeCover = this.elResizeGrid.firstChild; }catch(e){} document.body.appendChild(this.elResizeGrid); }, _selectAll_Row : function(){ this.htSelectionSPos.x = 0; this.htSelectionEPos.x = this.htMap.length - 1; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); }, _selectAll_Column : function(){ this.htSelectionSPos.y = 0; this.htSelectionEPos.y = this.htMap[0].length - 1; this._selectCells(this.htSelectionSPos, this.htSelectionEPos); }, _deleteSelectedColumn : function(){ var nStart = this.htSelectionSPos.x; var nEnd = this.htSelectionEPos.x; var nSpan; var elLastSplitted = null; for(var x = nStart; x <= nEnd; x++){ elCurCell = this.htMap[x][this.htSelectionSPos.y]; if(elCurCell != elLastSplitted){ elCurCell.innerHTML = ""; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; elCurCell.style.width = ""; elCurCell.setAttribute("colSpan", 1); for(var i = 0; i < nSpan - 1; i++){ var elTD = this.oApp.getWYSIWYGDocument().createElement("TD"); elCurCell.parentNode.insertBefore(elTD, elCurCell); } elLastSplitted = elCurCell; } } this.htMap = this._getCellMapping(this.elSelectionStartTable); for(var x = nStart; x <= nEnd; x++){ this._deleteColumn(nStart); } }, _deleteColumn : function(nCol){ var elCurCell; var nColWidth = 0; // obtain nColWidth first for(var y = 0; y < this.htMap[0].length; y++){ elCurCell = this.htMap[nCol][y]; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; if(nSpan == 1){ nColWidth = elCurCell.offsetWidth; break; } } var elLastDeleted = null; for(var y = 0; y < this.htMap[0].length; y++){ elCurCell = this.htMap[nCol][y]; if(elCurCell == elLastDeleted){ continue; } elLastDeleted = elCurCell; nSpan = parseInt(elCurCell.getAttribute("colSpan"), 10) || 1; if(nSpan > 1){ elCurCell.setAttribute("colSpan", nSpan - 1); elCurCell.style.width = parseInt(elCurCell.style.width) - nColWidth + "px"; }else{ elCurCell.parentNode.removeChild(elCurCell); } } aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); if(aTR.length < 1){ this.elSelectionStartTable.parentNode.removeChild(this.elSelectionStartTable); }else{ this.htMap = this._getCellMapping(this.elSelectionStartTable); } }, _deleteSelectedRow : function(){ var nStart = this.htSelectionSPos.y; var nEnd = this.htSelectionEPos.y; for(var y = nStart; y <= nEnd; y++){ this._deleteRow(nStart); } }, _deleteRow : function(nRow){ var elCurCell; var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var elCurTR = aTR[nRow]; var nRowHeight = elCurTR.offsetHeight; for(var x = 0; x < this.htMap.length; x++){ elCurCell = this.htMap[x][nRow]; nSpan = parseInt(elCurCell.getAttribute("rowSpan"), 10) || 1; if(nSpan > 1){ elCurCell.setAttribute("rowSpan", nSpan - 1); elCurCell.style.height = parseInt(elCurCell.style.height) - nRowHeight + "px"; if(elCurCell.parentNode == elCurTR){ this._appendCellAt(elCurCell, x, nRow + 1); } }else{ elCurCell.parentNode.removeChild(elCurCell); } } elCurTR.parentNode.removeChild(elCurTR); aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); if(aTR.length < 1){ this.elSelectionStartTable.parentNode.removeChild(this.elSelectionStartTable); }else{ this.htMap = this._getCellMapping(this.elSelectionStartTable); } }, _appendCellAt : function(elCell, x, y){ var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var elCurTR = aTR[y]; var elInsertionPt = null; for(var i = this.htMap.length - 1; i >= x; i--){ if(this.htMap[i][y].parentNode == elCurTR){ elInsertionPt = this.htMap[i][y]; } } elCurTR.insertBefore(elCell, elInsertionPt); }, _deleteSelectedCells : function(){ var elTmp; for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ elTmp = this.aSelectedCells[i]; elTmp.parentNode.removeChild(elTmp); } var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nWidth = this.htMap.length; if(nSelectionWidth == nWidth){ for(var i = 0, nLen = aTR.length; i < nLen; i++){ elTmp = aTR[i]; // There can be empty but necessary TR's because of Rowspan if(!this.htMap[0][i] || !this.htMap[0][i].parentNode || this.htMap[0][i].parentNode.tagName !== "TR"){ elTmp.parentNode.removeChild(elTmp); } } aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); } if(aTR.length < 1){ this.elSelectionStartTable.parentNode.removeChild(this.elSelectionStartTable); } this._updateSelection(); }, _insertColumnAfter : function(){ this._removeClassFromSelection(); this._hideTableTemplate(this.elSelectionStartTable); var aTR = jindo.$$(">TBODY>TR", this.elSelectionStartTable, {oneTimeOffCache:true}); var sInserted; var sTmpAttr_Inserted = "_tmp_inserted"; var elCell, elCellClone, elCurTR, elInsertionPt; // copy each cells in the following order: top->down, right->left // +---+---+---+---+ // |...|.2.|.1.|...| // |---+---+.1.|...| // |...|.3.|.1.|...| // |...|.3.+---+...| // |...|.3.|.4.+...| // |...+---+---+...| // |...|.6.|.5.|...| // +---+---+---+---+ for(var y = 0, nYLen = this.htMap[0].length; y < nYLen; y++){ elCurTR = aTR[y]; for(var x = this.htSelectionEPos.x; x >= this.htSelectionSPos.x; x--){ elCell = this.htMap[x][y]; //sInserted = elCell.getAttribute(sTmpAttr_Inserted); //if(sInserted){continue;} //elCell.setAttribute(sTmpAttr_Inserted, "o"); elCellClone = this._shallowCloneTD(elCell); // elCellClone의 outerHTML에 정상적인 rowSpan이 있더라도 IE에서는 이 위치에서 항상 1을 반환. (elCellClone.rowSpan & elCellClone.getAttribute("rowSpan")). //var nSpan = parseInt(elCellClone.getAttribute("rowSpan")); var nSpan = parseInt(elCell.getAttribute("rowSpan")); if(nSpan > 1){ elCellClone.setAttribute("rowSpan", 1); elCellClone.style.height = ""; } nSpan = parseInt(elCell.getAttribute("colSpan")); if(nSpan > 1){ elCellClone.setAttribute("colSpan", 1); elCellClone.style.width = ""; } // 현재 줄(TR)에 속한 셀(TD)을 찾아서 그 앞에 append 한다. elInsertionPt = null; for(var xx = this.htSelectionEPos.x; xx >= this.htSelectionSPos.x; xx--){ if(this.htMap[xx][y].parentNode == elCurTR){ elInsertionPt = this.htMap[xx][y].nextSibling; break; } } elCurTR.insertBefore(elCellClone, elInsertionPt); } } // remove the insertion marker from the original cells for(var i = 0, nLen = this.aSelectedCells.length; i < nLen; i++){ this.aSelectedCells[i].removeAttribute(sTmpAttr_Inserted); } var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nSelectionHeight = this.htSelectionEPos.y - this.htSelectionSPos.y + 1; this.htSelectionSPos.x += nSelectionWidth; this.htSelectionEPos.x += nSelectionWidth; this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "INSERT_TABLE_COLUMN"; this.oApp.exec("SHOW_COMMON_QE"); }, _insertRowBelow : function(){ this._selectAll_Row(); this._removeClassFromSelection(); this._hideTableTemplate(this.elSelectionStartTable); var elRowClone; var elTBody = this.htMap[0][0].parentNode.parentNode; var aTRs = jindo.$$(">TR", elTBody, {oneTimeOffCache:true}); var elInsertionPt = aTRs[this.htSelectionEPos.y + 1] || null; for(var y = this.htSelectionSPos.y; y <= this.htSelectionEPos.y; y++){ elRowClone = this._getTRCloneWithAllTD(y); elTBody.insertBefore(elRowClone, elInsertionPt); } var nSelectionWidth = this.htSelectionEPos.x - this.htSelectionSPos.x + 1; var nSelectionHeight = this.htSelectionEPos.y - this.htSelectionSPos.y + 1; this.htSelectionSPos.y += nSelectionHeight; this.htSelectionEPos.y += nSelectionHeight; this.htMap = this._getCellMapping(this.elSelectionStartTable); this._selectCells(this.htSelectionSPos, this.htSelectionEPos); this._showTableTemplate(this.elSelectionStartTable); this._addClassToSelection(); this.sQEAction = "INSERT_TABLE_ROW"; this.oApp.exec("SHOW_COMMON_QE"); }, _updateSelection : function(){ this.aSelectedCells = jindo.$A(this.aSelectedCells).filter(function(v){return (v.parentNode!==null && v.parentNode.parentNode!==null);}).$value(); }, _startCellSelection : function(){ this.htMap = this._getCellMapping(this.elSelectionStartTable); // De-select the default selection this.oApp.getEmptySelection().oBrowserSelection.selectNone(); if(this.oApp.oNavigator["safari"] || this.oApp.oNavigator["chrome"]){ this.oApp.getWYSIWYGDocument().onselectstart = function(){return false;}; } var elIFrame = this.oApp.getWYSIWYGWindow().frameElement; this.htEditingAreaPos = jindo.$Element(elIFrame).offset(); this.htEditingAreaPos.height = elIFrame.offsetHeight; this.htEditingAreaPos.bottom = this.htEditingAreaPos.top + this.htEditingAreaPos.height; this.htEditingAreaPos.width = elIFrame.offsetWidth; this.htEditingAreaPos.right = this.htEditingAreaPos.left + this.htEditingAreaPos.width; /* if(!this.oNavigatorInfo["firefox"]){ this.oApp.exec("DISABLE_WYSIWYG", []); } */ this._changeTableEditorStatus(this.STATUS.CELL_SELECTING); }, _selectBetweenCells : function(elCell1, elCell2){ this._deselectCells(); var oP1 = this._getBasisCellPosition(elCell1); var oP2 = this._getBasisCellPosition(elCell2); this._setEndPos(oP1); this._setEndPos(oP2); var oStartPos = {}, oEndPos = {}; oStartPos.x = Math.min(oP1.x, oP1.ex, oP2.x, oP2.ex); oStartPos.y = Math.min(oP1.y, oP1.ey, oP2.y, oP2.ey); oEndPos.x = Math.max(oP1.x, oP1.ex, oP2.x, oP2.ex); oEndPos.y = Math.max(oP1.y, oP1.ey, oP2.y, oP2.ey); this._selectCells(oStartPos, oEndPos); }, _getNextCell : function(elCell){ while(elCell){ elCell = elCell.nextSibling; if(elCell && elCell.tagName && elCell.tagName.match(/^TD|TH$/)){return elCell;} } return null; }, _getCellMapping : function(elTable){ var aTR = jindo.$$(">TBODY>TR", elTable, {oneTimeOffCache:true}); var nTD = 0; var aTD_FirstRow = aTR[0].childNodes; /* // remove empty TR's from the bottom of the table for(var i=aTR.length-1; i>0; i--){ if(!aTR[i].childNodes || aTR[i].childNodes.length === 0){ aTR[i].parentNode.removeChild(aTR[i]); aTR = aTR.slice(0, i); if(this.htSelectionSPos.y>=i) this.htSelectionSPos.y--; if(this.htSelectionEPos.y>=i) this.htSelectionEPos.y--; }else{ break; } } */ // count the number of columns for(var i = 0; i < aTD_FirstRow.length; i++){ var elTmp = aTD_FirstRow[i]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} if(elTmp.getAttribute("colSpan")){ nTD += this.parseIntOr0(elTmp.getAttribute("colSpan")); }else{ nTD ++; } } var nTblX = nTD; var nTblY = aTR.length; var aCellMapping = new Array(nTblX); for(var x = 0; x < nTblX; x++){ aCellMapping[x] = new Array(nTblY); } for(var y = 0; y < nTblY; y++){ var elCell = aTR[y].childNodes[0]; if(!elCell){continue;} if(!elCell.tagName || !elCell.tagName.match(/^TD|TH$/)){elCell = this._getNextCell(elCell);} var x = -1; while(elCell){ x++; if(!aCellMapping[x]){aCellMapping[x] = [];} if(aCellMapping[x][y]){continue;} var colSpan = parseInt(elCell.getAttribute("colSpan"), 10) || 1; var rowSpan = parseInt(elCell.getAttribute("rowSpan"), 10) || 1; /* if(y+rowSpan >= nTblY){ rowSpan = nTblY-y; elCell.setAttribute("rowSpan", rowSpan); } */ for(var yy = 0; yy < rowSpan; yy++){ for(var xx = 0; xx < colSpan; xx++){ if(!aCellMapping[x+xx]){ aCellMapping[x+xx] = []; } aCellMapping[x+xx][y+yy] = elCell; } } elCell = this._getNextCell(elCell); } } // remove empty TR's // (상단 TD의 rowspan만으로 지탱되는) 빈 TR이 있을 경우 IE7 이하에서 랜더링 오류가 발생 할 수 있어 빈 TR을 지워 줌 var bRowRemoved = false; var elLastCell = null; for(var y = 0, nRealY = 0, nYLen = aCellMapping[0].length; y < nYLen; y++, nRealY++){ elLastCell = null; if(!aTR[y].innerHTML.match(/TD|TH/i)){ for(var x = 0, nXLen = aCellMapping.length; x < nXLen; x++){ elCell = aCellMapping[x][y]; if(elCell === elLastCell){ continue; } elLastCell = elCell; var rowSpan = parseInt(elCell.getAttribute("rowSpan"), 10) || 1; if(rowSpan > 1){ elCell.setAttribute("rowSpan", rowSpan - 1); } } aTR[y].parentNode.removeChild(aTR[y]); if(this.htSelectionEPos.y >= nRealY){ nRealY--; this.htSelectionEPos.y--; } bRowRemoved = true; } } if(bRowRemoved){ return this._getCellMapping(elTable); } return aCellMapping; }, _selectCells : function(htSPos, htEPos){ this.aSelectedCells = this._getSelectedCells(htSPos, htEPos); this._addClassToSelection(); }, _deselectCells : function(){ this._removeClassFromSelection(); this.aSelectedCells = []; this.htSelectionSPos = {x:-1, y:-1}; this.htSelectionEPos = {x:-1, y:-1}; }, _addClassToSelection : function(){ var welCell, elCell; for(var i = 0; i < this.aSelectedCells.length; i++){ elCell = this.aSelectedCells[i]; welCell = jindo.$Element(elCell); welCell.addClass(this.CELL_SELECTION_CLASS); if(elCell.style.backgroundColor){ elCell.setAttribute(this.TMP_BGC_ATTR, elCell.style.backgroundColor); welCell.css("backgroundColor", ""); } if(elCell.style.backgroundImage) { elCell.setAttribute(this.TMP_BGIMG_ATTR, elCell.style.backgroundImage); welCell.css("backgroundImage", ""); } } }, _removeClassFromSelection : function(){ var welCell, elCell; for(var i = 0; i < this.aSelectedCells.length; i++){ elCell = this.aSelectedCells[i]; welCell = jindo.$Element(elCell); welCell.removeClass(this.CELL_SELECTION_CLASS); //배경색 if(elCell.getAttribute(this.TMP_BGC_ATTR)){ elCell.style.backgroundColor = elCell.getAttribute(this.TMP_BGC_ATTR); elCell.removeAttribute(this.TMP_BGC_ATTR); } //배경이미지 if(elCell.getAttribute(this.TMP_BGIMG_ATTR)) { welCell.css("backgroundImage",elCell.getAttribute(this.TMP_BGIMG_ATTR)); elCell.removeAttribute(this.TMP_BGIMG_ATTR); } } }, _expandAndSelect : function(htPos1, htPos2){ var x, y, elTD, nTmp, i; // expand top if(htPos1.y > 0){ for(x = htPos1.x; x <= htPos2.x; x++){ elTD = this.htMap[x][htPos1.y]; if(this.htMap[x][htPos1.y - 1] == elTD){ nTmp = htPos1.y - 2; while(nTmp >= 0 && this.htMap[x][nTmp] == elTD){ nTmp--; } htPos1.y = nTmp + 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand left if(htPos1.x > 0){ for(y = htPos1.y; y <= htPos2.y; y++){ elTD = this.htMap[htPos1.x][y]; if(this.htMap[htPos1.x - 1][y] == elTD){ nTmp = htPos1.x - 2; while(nTmp >= 0 && this.htMap[nTmp][y] == elTD){ nTmp--; } htPos1.x = nTmp + 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand bottom if(htPos2.y < this.htMap[0].length - 1){ for(x = htPos1.x; x <= htPos2.x; x++){ elTD = this.htMap[x][htPos2.y]; if(this.htMap[x][htPos2.y + 1] == elTD){ nTmp = htPos2.y + 2; while(nTmp < this.htMap[0].length && this.htMap[x][nTmp] == elTD){ nTmp++; } htPos2.y = nTmp - 1; this._expandAndSelect(htPos1, htPos2); return; } } } // expand right if(htPos2.x < this.htMap.length - 1){ for(y = htPos1.y; y <= htPos2.y; y++){ elTD = this.htMap[htPos2.x][y]; if(this.htMap[htPos2.x + 1][y] == elTD){ nTmp = htPos2.x + 2; while(nTmp < this.htMap.length && this.htMap[nTmp][y] == elTD){ nTmp++; } htPos2.x = nTmp - 1; this._expandAndSelect(htPos1, htPos2); return; } } } }, _getSelectedCells : function(htPos1, htPos2){ this._expandAndSelect(htPos1, htPos2); var x1 = htPos1.x; var y1 = htPos1.y; var x2 = htPos2.x; var y2 = htPos2.y; this.htSelectionSPos = htPos1; this.htSelectionEPos = htPos2; var aResult = []; for(var y = y1; y <= y2; y++){ for(var x = x1; x <= x2; x++){ if(jindo.$A(aResult).has(this.htMap[x][y])){ continue; } aResult[aResult.length] = this.htMap[x][y]; } } return aResult; }, _setEndPos : function(htPos){ var nColspan, nRowspan; nColspan = parseInt(htPos.elCell.getAttribute("colSpan"), 10) || 1; nRowspan = parseInt(htPos.elCell.getAttribute("rowSpan"), 10) || 1; htPos.ex = htPos.x + nColspan - 1; htPos.ey = htPos.y + nRowspan - 1; }, _getBasisCellPosition : function(elCell){ var x = 0, y = 0; for(x = 0; x < this.htMap.length; x++){ for(y = 0; y < this.htMap[x].length; y++){ if(this.htMap[x][y] == elCell){ return {'x': x, 'y': y, elCell: elCell}; } } } return {'x': 0, 'y': 0, elCell: elCell}; }, _applyTableTemplate : function(elTable, nTemplateIdx){ // clear style first if already exists /* if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], true); }else{ this._clearAllTableStyles(elTable); } */ if (!elTable) { return; } // 사용자가 지정한 스타일 무시하고 새 템플릿 적용 // http://bts.nhncorp.com/nhnbts/browse/COM-871 this._clearAllTableStyles(elTable); this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[nTemplateIdx], false); elTable.setAttribute(this.ATTR_TBL_TEMPLATE, nTemplateIdx); }, _clearAllTableStyles : function(elTable){ elTable.removeAttribute("border"); elTable.removeAttribute("cellPadding"); elTable.removeAttribute("cellSpacing"); elTable.style.padding = ""; elTable.style.border = ""; elTable.style.backgroundColor = ""; elTable.style.color = ""; var aTD = jindo.$$(">TBODY>TR>TD", elTable, {oneTimeOffCache:true}); for(var i = 0, nLen = aTD.length; i < nLen; i++){ aTD[i].style.padding = ""; aTD[i].style.border = ""; aTD[i].style.backgroundColor = ""; aTD[i].style.color = ""; } }, _hideTableTemplate : function(elTable){ if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], true); } }, _showTableTemplate : function(elTable){ if(elTable.getAttribute(this.ATTR_TBL_TEMPLATE)){ this._doApplyTableTemplate(elTable, nhn.husky.SE2M_TableTemplate[this.parseIntOr0(elTable.getAttribute(this.ATTR_TBL_TEMPLATE))], false); } }, _doApplyTableTemplate : function(elTable, htTableTemplate, bClearStyle){ var htTableProperty = htTableTemplate.htTableProperty; var htTableStyle = htTableTemplate.htTableStyle; var ht1stRowStyle = htTableTemplate.ht1stRowStyle; var ht1stColumnStyle = htTableTemplate.ht1stColumnStyle; var aRowStyle = htTableTemplate.aRowStyle; var elTmp; // replace all TH's with TD's if(htTableProperty){ this._copyAttributesTo(elTable, htTableProperty, bClearStyle); } if(htTableStyle){ this._copyStylesTo(elTable, htTableStyle, bClearStyle); } var aTR = jindo.$$(">TBODY>TR", elTable, {oneTimeOffCache:true}); var nStartRowNum = 0; if(ht1stRowStyle){ var nStartRowNum = 1; for(var ii = 0, nNumCells = aTR[0].childNodes.length; ii < nNumCells; ii++){ elTmp = aTR[0].childNodes[ii]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} this._copyStylesTo(elTmp, ht1stRowStyle, bClearStyle); } } var nRowSpan; var elFirstEl; if(ht1stColumnStyle){ // if the style's got a row heading, skip the 1st row. (it was taken care above) var nRowStart = ht1stRowStyle ? 1 : 0; for(var i = nRowStart, nLen = aTR.length; i < nLen;){ elFirstEl = aTR[i].firstChild; nRowSpan = 1; if(elFirstEl && elFirstEl.tagName.match(/^TD|TH$/)){ nRowSpan = parseInt(elFirstEl.getAttribute("rowSpan"), 10) || 1; this._copyStylesTo(elFirstEl, ht1stColumnStyle, bClearStyle); } i += nRowSpan; } } if(aRowStyle){ var nNumStyles = aRowStyle.length; for(var i = nStartRowNum, nLen = aTR.length; i < nLen; i++){ for(var ii = 0, nNumCells = aTR[i].childNodes.length; ii < nNumCells; ii++){ var elTmp = aTR[i].childNodes[ii]; if(!elTmp.tagName || !elTmp.tagName.match(/^TD|TH$/)){continue;} this._copyStylesTo(elTmp, aRowStyle[(i+nStartRowNum)%nNumStyles], bClearStyle); } } } }, _copyAttributesTo : function(oTarget, htProperties, bClearStyle){ var elTmp; for(var x in htProperties){ if(htProperties.hasOwnProperty(x)){ if(bClearStyle){ if(oTarget[x]){ elTmp = document.createElement(oTarget.tagName); elTmp[x] = htProperties[x]; if(elTmp[x] == oTarget[x]){ oTarget.removeAttribute(x); } } }else{ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = ""; if(!oTarget[x] || oTarget.style[x] == elTmp.style[x]){oTarget.setAttribute(x, htProperties[x]);} } } } }, _copyStylesTo : function(oTarget, htProperties, bClearStyle){ var elTmp; for(var x in htProperties){ if(htProperties.hasOwnProperty(x)){ if(bClearStyle){ if(oTarget.style[x]){ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = htProperties[x]; if(elTmp.style[x] == oTarget.style[x]){ oTarget.style[x] = ""; } } }else{ elTmp = document.createElement(oTarget.tagName); elTmp.style[x] = ""; if(!oTarget.style[x] || oTarget.style[x] == elTmp.style[x] || x.match(/^border/)){oTarget.style[x] = htProperties[x];} } } } }, _hideResizer : function(){ this.elResizeGrid.style.display = "none"; }, _showResizer : function(){ this.elResizeGrid.style.display = "block"; }, _setResizerSize : function(width, height){ this.elResizeGrid.style.width = width + "px"; this.elResizeGrid.style.height = height + "px"; }, parseBorder : function(vBorder, sBorderStyle){ if(sBorderStyle == "none"){return 0;} var num = parseInt(vBorder, 10); if(isNaN(num)){ if(typeof(vBorder) == "string"){ // IE Bug return 1; /* switch(vBorder){ case "thin": return 1; case "medium": return 3; case "thick": return 5; } */ } } return num; }, parseIntOr0 : function(num){ num = parseInt(num, 10); if(isNaN(num)){return 0;} return num; }, _shallowCloneTR : function(elTR){ var elResult = elTR.cloneNode(false); var elCurTD, elCurTDClone; for(var i = 0, nLen = elTR.childNodes.length; i < nLen; i++){ elCurTD = elTR.childNodes[i]; if(elCurTD.tagName == "TD"){ elCurTDClone = this._shallowCloneTD(elCurTD); elResult.insertBefore(elCurTDClone, null); } } return elResult; }, // _getTRCloneWithAllTD : function(nRow){ var elResult = this.htMap[0][nRow].parentNode.cloneNode(false); var elCurTD, elCurTDClone; for(var i = 0, nLen = this.htMap.length; i < nLen; i++){ elCurTD = this.htMap[i][nRow]; if(elCurTD.tagName == "TD"){ elCurTDClone = this._shallowCloneTD(elCurTD); elCurTDClone.setAttribute("rowSpan", 1); elCurTDClone.setAttribute("colSpan", 1); elCurTDClone.style.width = ""; elCurTDClone.style.height = ""; elResult.insertBefore(elCurTDClone, null); } } return elResult; }, _shallowCloneTD : function(elTD){ var elResult = elTD.cloneNode(false); elResult.innerHTML = this.sEmptyTDSrc; return elResult; }, // elTbl이 꽉 찬 직사각형 형태의 테이블인지 확인 _isValidTable : function(elTbl){ if(!elTbl || !elTbl.tagName || elTbl.tagName != "TABLE"){ return false; } this.htMap = this._getCellMapping(elTbl); var nXSize = this.htMap.length; if(nXSize < 1){return false;} var nYSize = this.htMap[0].length; if(nYSize < 1){return false;} for(var i = 1; i < nXSize; i++){ // 첫번째 열과 길이가 다른 열이 하나라도 있다면 직사각형이 아님 if(this.htMap[i].length != nYSize || !this.htMap[i][nYSize - 1]){ return false; } // 빈칸이 하나라도 있다면 꽉 찬 직사각형이 아님 for(var j = 0; j < nYSize; j++){ if(!this.htMap[i] || !this.htMap[i][j]){ return false; } } } return true; }, addCSSClass : function(sClassName, sClassRule){ var oDoc = this.oApp.getWYSIWYGDocument(); if(oDoc.styleSheets[0] && oDoc.styleSheets[0].addRule){ // IE oDoc.styleSheets[0].addRule("." + sClassName, sClassRule); }else{ // FF var elHead = oDoc.getElementsByTagName("HEAD")[0]; var elStyle = oDoc.createElement ("STYLE"); //styleElement.type = "text / css"; elHead.appendChild (elStyle); elStyle.sheet.insertRule("." + sClassName + " { "+sClassRule+" }", 0); } } //@lazyload_js] });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to Find/Replace * @name hp_SE2M_FindReplacePlugin.js */ nhn.husky.SE2M_FindReplacePlugin = jindo.$Class({ name : "SE2M_FindReplacePlugin", oEditingWindow : null, oFindReplace : null, bFindMode : true, bLayerShown : false, $init : function(){ this.nDefaultTop = 20; }, $ON_MSG_APP_READY : function(){ // the right document will be available only when the src is completely loaded this.oEditingWindow = this.oApp.getWYSIWYGWindow(); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+f", "SHOW_FIND_LAYER", []]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+h", "SHOW_REPLACE_LAYER", []]); this.oApp.exec("REGISTER_UI_EVENT", ["findAndReplace", "click", "TOGGLE_FIND_REPLACE_LAYER"]); }, $ON_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("HIDE_DIALOG_LAYER", [this.elDropdownLayer]); }, //@lazyload_js TOGGLE_FIND_REPLACE_LAYER,SHOW_FIND_LAYER,SHOW_REPLACE_LAYER,SHOW_FIND_REPLACE_LAYER:N_FindReplace.js[ _assignHTMLElements : function(){ var oAppContainer = this.oApp.htOptions.elAppContainer; this.oApp.exec("LOAD_HTML", ["find_and_replace"]); // this.oEditingWindow = jindo.$$.getSingle("IFRAME", oAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_findAndReplace_layer", oAppContainer); this.welDropdownLayer = jindo.$Element(this.elDropdownLayer); var oTmp = jindo.$$("LI", this.elDropdownLayer); this.oFindTab = oTmp[0]; this.oReplaceTab = oTmp[1]; oTmp = jindo.$$(".container > .bx", this.elDropdownLayer); this.oFindInputSet = jindo.$$.getSingle(".husky_se2m_find_ui", this.elDropdownLayer); this.oReplaceInputSet = jindo.$$.getSingle(".husky_se2m_replace_ui", this.elDropdownLayer); this.elTitle = jindo.$$.getSingle("H3", this.elDropdownLayer); this.oFindInput_Keyword = jindo.$$.getSingle("INPUT", this.oFindInputSet); oTmp = jindo.$$("INPUT", this.oReplaceInputSet); this.oReplaceInput_Original = oTmp[0]; this.oReplaceInput_Replacement = oTmp[1]; this.oFindNextButton = jindo.$$.getSingle("BUTTON.husky_se2m_find_next", this.elDropdownLayer); this.oReplaceFindNextButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace_find_next", this.elDropdownLayer); this.oReplaceButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace", this.elDropdownLayer); this.oReplaceAllButton = jindo.$$.getSingle("BUTTON.husky_se2m_replace_all", this.elDropdownLayer); this.aCloseButtons = jindo.$$("BUTTON.husky_se2m_cancel", this.elDropdownLayer); }, $LOCAL_BEFORE_FIRST : function(sMsg){ this._assignHTMLElements(); this.oFindReplace = new nhn.FindReplace(this.oEditingWindow); for(var i=0; i<this.aCloseButtons.length; i++){ // var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_DIALOG_LAYER", [this.elDropdownLayer]); var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_FIND_REPLACE_LAYER", [this.elDropdownLayer]); jindo.$Fn(func, this).attach(this.aCloseButtons[i], "click"); } jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_FIND", []), this).attach(this.oFindTab, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_REPLACE", []), this).attach(this.oReplaceTab, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("FIND", []), this).attach(this.oFindNextButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("FIND", []), this).attach(this.oReplaceFindNextButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("REPLACE", []), this).attach(this.oReplaceButton, "click"); jindo.$Fn(jindo.$Fn(this.oApp.exec, this.oApp).bind("REPLACE_ALL", []), this).attach(this.oReplaceAllButton, "click"); this.oFindInput_Keyword.value = ""; this.oReplaceInput_Original.value = ""; this.oReplaceInput_Replacement.value = ""; //레이어의 이동 범위 설정. var elIframe = this.oApp.getWYSIWYGWindow().frameElement; this.htOffsetPos = jindo.$Element(elIframe).offset(); this.nEditorWidth = elIframe.offsetWidth; this.elDropdownLayer.style.display = "block"; this.htInitialPos = this.welDropdownLayer.offset(); var htScrollXY = this.oApp.oUtils.getScrollXY(); // this.welDropdownLayer.offset(this.htOffsetPos.top-htScrollXY.y, this.htOffsetPos.left-htScrollXY.x); this.welDropdownLayer.offset(this.htOffsetPos.top, this.htOffsetPos.left); this.htTopLeftCorner = {x:parseInt(this.elDropdownLayer.style.left, 10), y:parseInt(this.elDropdownLayer.style.top, 10)}; // offset width가 IE에서 css lazy loading 때문에 제대로 잡히지 않아 상수로 설정 //this.nLayerWidth = this.elDropdownLayer.offsetWidth; this.nLayerWidth = 258; this.nLayerHeight = 160; //this.nLayerWidth = Math.abs(parseInt(this.elDropdownLayer.style.marginLeft))+20; this.elDropdownLayer.style.display = "none"; }, // [SMARTEDITORSUS-728] 찾기/바꾸기 레이어 오픈 툴바 버튼 active/inactive 처리 추가 $ON_TOGGLE_FIND_REPLACE_LAYER : function(){ if(!this.bLayerShown) { this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); } else { this.oApp.exec("HIDE_FIND_REPLACE_LAYER"); } }, $ON_SHOW_FIND_REPLACE_LAYER : function(){ this.bLayerShown = true; this.oApp.exec("DISABLE_ALL_UI", [{aExceptions: ["findAndReplace"]}]); this.oApp.exec("SELECT_UI", ["findAndReplace"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.elDropdownLayer.style.top = this.nDefaultTop+"px"; this.oApp.exec("SHOW_DIALOG_LAYER", [this.elDropdownLayer, { elHandle: this.elTitle, fnOnDragStart : jindo.$Fn(this.oApp.exec, this.oApp).bind("SHOW_EDITING_AREA_COVER"), fnOnDragEnd : jindo.$Fn(this.oApp.exec, this.oApp).bind("HIDE_EDITING_AREA_COVER"), nMinX : this.htTopLeftCorner.x, nMinY : this.nDefaultTop, nMaxX : this.htTopLeftCorner.x + this.oApp.getEditingAreaWidth() - this.nLayerWidth, nMaxY : this.htTopLeftCorner.y + this.oApp.getEditingAreaHeight() - this.nLayerHeight, sOnShowMsg : "FIND_REPLACE_LAYER_SHOWN" }]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['findreplace']); }, $ON_HIDE_FIND_REPLACE_LAYER : function() { this.oApp.exec("ENABLE_ALL_UI"); this.oApp.exec("DESELECT_UI", ["findAndReplace"]); this.oApp.exec("HIDE_ALL_DIALOG_LAYER", []); this.bLayerShown = false; }, $ON_FIND_REPLACE_LAYER_SHOWN : function(){ this.oApp.exec("POSITION_TOOLBAR_LAYER", [this.elDropdownLayer]); if(this.bFindMode){ this.oFindInput_Keyword.value = "_clear_"; this.oFindInput_Keyword.value = ""; this.oFindInput_Keyword.focus(); }else{ this.oReplaceInput_Original.value = "_clear_"; this.oReplaceInput_Original.value = ""; this.oReplaceInput_Replacement.value = ""; this.oReplaceInput_Original.focus(); } this.oApp.exec("HIDE_CURRENT_ACTIVE_LAYER", []); }, $ON_SHOW_FIND_LAYER : function(){ this.oApp.exec("SHOW_FIND"); this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); }, $ON_SHOW_REPLACE_LAYER : function(){ this.oApp.exec("SHOW_REPLACE"); this.oApp.exec("SHOW_FIND_REPLACE_LAYER"); }, $ON_SHOW_FIND : function(){ this.bFindMode = true; this.oFindInput_Keyword.value = this.oReplaceInput_Original.value; jindo.$Element(this.oFindTab).addClass("active"); jindo.$Element(this.oReplaceTab).removeClass("active"); jindo.$Element(this.oFindNextButton).removeClass("normal"); jindo.$Element(this.oFindNextButton).addClass("strong"); this.oFindInputSet.style.display = "block"; this.oReplaceInputSet.style.display = "none"; this.oReplaceButton.style.display = "none"; this.oReplaceAllButton.style.display = "none"; jindo.$Element(this.elDropdownLayer).removeClass("replace"); jindo.$Element(this.elDropdownLayer).addClass("find"); }, $ON_SHOW_REPLACE : function(){ this.bFindMode = false; this.oReplaceInput_Original.value = this.oFindInput_Keyword.value; jindo.$Element(this.oFindTab).removeClass("active"); jindo.$Element(this.oReplaceTab).addClass("active"); jindo.$Element(this.oFindNextButton).removeClass("strong"); jindo.$Element(this.oFindNextButton).addClass("normal"); this.oFindInputSet.style.display = "none"; this.oReplaceInputSet.style.display = "block"; this.oReplaceButton.style.display = "inline"; this.oReplaceAllButton.style.display = "inline"; jindo.$Element(this.elDropdownLayer).removeClass("find"); jindo.$Element(this.elDropdownLayer).addClass("replace"); }, $ON_FIND : function(){ var sKeyword; if(this.bFindMode){ sKeyword = this.oFindInput_Keyword.value; }else{ sKeyword = this.oReplaceInput_Original.value; } var oSelection = this.oApp.getSelection(); oSelection.select(); switch(this.oFindReplace.find(sKeyword, false)){ case 1: alert(this.oApp.$MSG("SE_FindReplace.keywordNotFound")); oSelection.select(); break; case 2: alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); break; } }, $ON_REPLACE : function(){ var sOriginal = this.oReplaceInput_Original.value; var sReplacement = this.oReplaceInput_Replacement.value; var oSelection = this.oApp.getSelection(); this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["REPLACE"]); var iReplaceResult = this.oFindReplace.replace(sOriginal, sReplacement, false); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["REPLACE"]); switch(iReplaceResult){ case 1: case 3: alert(this.oApp.$MSG("SE_FindReplace.keywordNotFound")); oSelection.select(); break; case 4: alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); break; } }, $ON_REPLACE_ALL : function(){ var sOriginal = this.oReplaceInput_Original.value; var sReplacement = this.oReplaceInput_Replacement.value; var oSelection = this.oApp.getSelection(); this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["REPLACE ALL", {sSaveTarget:"BODY"}]); var iReplaceAllResult = this.oFindReplace.replaceAll(sOriginal, sReplacement, false); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["REPLACE ALL", {sSaveTarget:"BODY"}]); if(iReplaceAllResult === 0){ alert(this.oApp.$MSG("SE_FindReplace.replaceKeywordNotFound")); oSelection.select(); this.oApp.exec("FOCUS"); }else{ if(iReplaceAllResult<0){ alert(this.oApp.$MSG("SE_FindReplace.keywordMissing")); oSelection.select(); }else{ alert(this.oApp.$MSG("SE_FindReplace.replaceAllResultP1")+iReplaceAllResult+this.oApp.$MSG("SE_FindReplace.replaceAllResultP2")); oSelection = this.oApp.getEmptySelection(); oSelection.select(); this.oApp.exec("FOCUS"); } } } //@lazyload_js] }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to inserting special characters * @name hp_SE2M_SCharacter.js * @required HuskyRangeManager */ nhn.husky.SE2M_SCharacter = jindo.$Class({ name : "SE2M_SCharacter", $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["sCharacter", "click", "TOGGLE_SCHARACTER_LAYER"]); }, //@lazyload_js TOGGLE_SCHARACTER_LAYER[ _assignHTMLObjects : function(oAppContainer){ oAppContainer = jindo.$(oAppContainer) || document; this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_seditor_sCharacter_layer", oAppContainer); this.oTextField = jindo.$$.getSingle("INPUT", this.elDropdownLayer); this.oInsertButton = jindo.$$.getSingle("+ BUTTON", this.oTextField); this.aCloseButton = jindo.$$("BUTTON.husky_se2m_sCharacter_close", this.elDropdownLayer); this.aSCharList = jindo.$$("UL.husky_se2m_sCharacter_list", this.elDropdownLayer); var oLabelUL = jindo.$$.getSingle("UL.se2_char_tab", this.elDropdownLayer); this.aLabel = jindo.$$(">LI", oLabelUL); }, $LOCAL_BEFORE_FIRST : function(sFullMsg){ this.bIE = jindo.$Agent().navigator().ie; this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.charSet = []; this.charSet[0] = unescape('FF5B FF5D 3014 3015 3008 3009 300A 300B 300C 300D 300E 300F 3010 3011 2018 2019 201C 201D 3001 3002 %B7 2025 2026 %A7 203B 2606 2605 25CB 25CF 25CE 25C7 25C6 25A1 25A0 25B3 25B2 25BD 25BC 25C1 25C0 25B7 25B6 2664 2660 2661 2665 2667 2663 2299 25C8 25A3 25D0 25D1 2592 25A4 25A5 25A8 25A7 25A6 25A9 %B1 %D7 %F7 2260 2264 2265 221E 2234 %B0 2032 2033 2220 22A5 2312 2202 2261 2252 226A 226B 221A 223D 221D 2235 222B 222C 2208 220B 2286 2287 2282 2283 222A 2229 2227 2228 FFE2 21D2 21D4 2200 2203 %B4 FF5E 02C7 02D8 02DD 02DA 02D9 %B8 02DB %A1 %BF 02D0 222E 2211 220F 266D 2669 266A 266C 327F 2192 2190 2191 2193 2194 2195 2197 2199 2196 2198 321C 2116 33C7 2122 33C2 33D8 2121 2668 260F 260E 261C 261E %B6 2020 2021 %AE %AA %BA 2642 2640').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[1] = unescape('%BD 2153 2154 %BC %BE 215B 215C 215D 215E %B9 %B2 %B3 2074 207F 2081 2082 2083 2084 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 FFE6 %24 FFE5 FFE1 20AC 2103 212B 2109 FFE0 %A4 2030 3395 3396 3397 2113 3398 33C4 33A3 33A4 33A5 33A6 3399 339A 339B 339C 339D 339E 339F 33A0 33A1 33A2 33CA 338D 338E 338F 33CF 3388 3389 33C8 33A7 33A8 33B0 33B1 33B2 33B3 33B4 33B5 33B6 33B7 33B8 33B9 3380 3381 3382 3383 3384 33BA 33BB 33BC 33BD 33BE 33BF 3390 3391 3392 3393 3394 2126 33C0 33C1 338A 338B 338C 33D6 33C5 33AD 33AE 33AF 33DB 33A9 33AA 33AB 33AC 33DD 33D0 33D3 33C3 33C9 33DC 33C6').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[2] = unescape('3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 326A 326B 326C 326D 326E 326F 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 327A 327B 24D0 24D1 24D2 24D3 24D4 24D5 24D6 24D7 24D8 24D9 24DA 24DB 24DC 24DD 24DE 24DF 24E0 24E1 24E2 24E3 24E4 24E5 24E6 24E7 24E8 24E9 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 246A 246B 246C 246D 246E 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 320A 320B 320C 320D 320E 320F 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 321A 321B 249C 249D 249E 249F 24A0 24A1 24A2 24A3 24A4 24A5 24A6 24A7 24A8 24A9 24AA 24AB 24AC 24AD 24AE 24AF 24B0 24B1 24B2 24B3 24B4 24B5 2474 2475 2476 2477 2478 2479 247A 247B 247C 247D 247E 247F 2480 2481 2482').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[3] = unescape('3131 3132 3133 3134 3135 3136 3137 3138 3139 313A 313B 313C 313D 313E 313F 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 314A 314B 314C 314D 314E 314F 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 315A 315B 315C 315D 315E 315F 3160 3161 3162 3163 3165 3166 3167 3168 3169 316A 316B 316C 316D 316E 316F 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 317A 317B 317C 317D 317E 317F 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 318A 318B 318C 318D 318E').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[4] = unescape('0391 0392 0393 0394 0395 0396 0397 0398 0399 039A 039B 039C 039D 039E 039F 03A0 03A1 03A3 03A4 03A5 03A6 03A7 03A8 03A9 03B1 03B2 03B3 03B4 03B5 03B6 03B7 03B8 03B9 03BA 03BB 03BC 03BD 03BE 03BF 03C0 03C1 03C3 03C4 03C5 03C6 03C7 03C8 03C9 %C6 %D0 0126 0132 013F 0141 %D8 0152 %DE 0166 014A %E6 0111 %F0 0127 I 0133 0138 0140 0142 0142 0153 %DF %FE 0167 014B 0149 0411 0413 0414 0401 0416 0417 0418 0419 041B 041F 0426 0427 0428 0429 042A 042B 042C 042D 042E 042F 0431 0432 0433 0434 0451 0436 0437 0438 0439 043B 043F 0444 0446 0447 0448 0449 044A 044B 044C 044D 044E 044F').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); this.charSet[5] = unescape('3041 3042 3043 3044 3045 3046 3047 3048 3049 304A 304B 304C 304D 304E 304F 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 305A 305B 305C 305D 305E 305F 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 306A 306B 306C 306D 306E 306F 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 307A 307B 307C 307D 307E 307F 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 308A 308B 308C 308D 308E 308F 3090 3091 3092 3093 30A1 30A2 30A3 30A4 30A5 30A6 30A7 30A8 30A9 30AA 30AB 30AC 30AD 30AE 30AF 30B0 30B1 30B2 30B3 30B4 30B5 30B6 30B7 30B8 30B9 30BA 30BB 30BC 30BD 30BE 30BF 30C0 30C1 30C2 30C3 30C4 30C5 30C6 30C7 30C8 30C9 30CA 30CB 30CC 30CD 30CE 30CF 30D0 30D1 30D2 30D3 30D4 30D5 30D6 30D7 30D8 30D9 30DA 30DB 30DC 30DD 30DE 30DF 30E0 30E1 30E2 30E3 30E4 30E5 30E6 30E7 30E8 30E9 30EA 30EB 30EC 30ED 30EE 30EF 30F0 30F1 30F2 30F3 30F4 30F5 30F6').replace(/(\S{4})/g, function(a){return "%u"+a;}).split(' '); var funcInsert = jindo.$Fn(this.oApp.exec, this.oApp).bind("INSERT_SCHARACTERS", [this.oTextField.value]); jindo.$Fn(funcInsert, this).attach(this.oInsertButton, "click"); this.oApp.exec("SET_SCHARACTER_LIST", [this.charSet]); for(var i=0; i<this.aLabel.length; i++){ var func = jindo.$Fn(this.oApp.exec, this.oApp).bind("CHANGE_SCHARACTER_SET", [i]); jindo.$Fn(func, this).attach(this.aLabel[i].firstChild, "mousedown"); } for(var i=0; i<this.aCloseButton.length; i++){ this.oApp.registerBrowserEvent(this.aCloseButton[i], "click", "HIDE_ACTIVE_LAYER", []); } this.oApp.registerBrowserEvent(this.elDropdownLayer, "click", "EVENT_SCHARACTER_CLICKED", []); }, $ON_TOGGLE_SCHARACTER_LAYER : function(){ this.oTextField.value = ""; this.oSelection = this.oApp.getSelection(); this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "MSG_SCHARACTER_LAYER_SHOWN", [], "MSG_SCHARACTER_LAYER_HIDDEN", [""]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['symbol']); }, $ON_MSG_SCHARACTER_LAYER_SHOWN : function(){ this.oTextField.focus(); this.oApp.exec("SELECT_UI", ["sCharacter"]); }, $ON_MSG_SCHARACTER_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["sCharacter"]); }, $ON_EVENT_SCHARACTER_CLICKED : function(weEvent){ var elButton = nhn.husky.SE2M_Utils.findAncestorByTagName("BUTTON", weEvent.element); if(!elButton || elButton.tagName != "BUTTON"){return;} if(elButton.parentNode.tagName != "LI"){return;} var sChar = elButton.firstChild.innerHTML; if(sChar.length > 1){return;} this.oApp.exec("SELECT_SCHARACTER", [sChar]); weEvent.stop(); }, $ON_SELECT_SCHARACTER : function(schar){ this.oTextField.value += schar; if(this.oTextField.createTextRange){ var oTextRange = this.oTextField.createTextRange(); oTextRange.collapse(false); oTextRange.select(); }else{ if(this.oTextField.selectionEnd){ this.oTextField.selectionEnd = this.oTextField.value.length; this.oTextField.focus(); } } }, $ON_INSERT_SCHARACTERS : function(){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["INSERT SCHARACTER"]); this.oSelection.pasteHTML(this.oTextField.value); this.oSelection.collapseToEnd(); this.oSelection.select(); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["INSERT SCHARACTER"]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_CHANGE_SCHARACTER_SET : function(nSCharSet){ for(var i=0; i<this.aSCharList.length; i++){ if(jindo.$Element(this.aLabel[i]).hasClass("active")){ if(i == nSCharSet){return;} jindo.$Element(this.aLabel[i]).removeClass("active"); } } this._drawSCharList(nSCharSet); jindo.$Element(this.aLabel[nSCharSet]).addClass("active"); }, $ON_SET_SCHARACTER_LIST : function(charSet){ this.charSet = charSet; this.bSCharSetDrawn = new Array(this.charSet.length); this._drawSCharList(0); }, _drawSCharList : function(i){ if(this.bSCharSetDrawn[i]){return;} this.bSCharSetDrawn[i] = true; var len = this.charSet[i].length; var aLI = new Array(len); this.aSCharList[i].innerHTML = ''; var button, span; for(var ii=0; ii<len; ii++){ aLI[ii] = jindo.$("<LI>"); if(this.bIE){ button = jindo.$("<BUTTON>"); button.setAttribute('type', 'button'); }else{ button = jindo.$("<BUTTON>"); button.type = "button"; } span = jindo.$("<SPAN>"); span.innerHTML = unescape(this.charSet[i][ii]); button.appendChild(span); aLI[ii].appendChild(button); aLI[ii].onmouseover = function(){this.className='hover'}; aLI[ii].onmouseout = function(){this.className=''}; this.aSCharList[i].appendChild(aLI[ii]); } //this.oApp.delayedExec("SE2_ATTACH_HOVER_EVENTS", [jindo.$$(">LI", this.aSCharList[i]), 0]); } //@lazyload_js] }); //}
JavaScript
// "padding", "backgroundcolor", "border", "borderTop", "borderRight", "borderBottom", "borderLeft", "color", "textAlign", "fontWeight" nhn.husky.SE2M_TableTemplate = [ {}, /* // 0 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px dashed #666666", borderRight : "0", borderBottom : "0" }, aRowStyle : [ { padding : "3px 0 2px 0", border : "1px dashed #666666", borderTop : "0", borderLeft : "0" } ] }, // 1 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #c7c7c7", borderRight : "0", borderBottom : "0" }, aRowStyle : [ { padding : "3px 0 2px 0", border : "1px solid #c7c7c7", borderTop : "0", borderLeft : "0" } ] }, // 2 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { border : "1px solid #c7c7c7" }, aRowStyle : [ { padding : "2px 0 1px 0", border : "1px solid #c7c7c7" } ] }, // 3 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { border : "1px double #c7c7c7" }, aRowStyle : [ { padding : "1px 0 0", border : "3px double #c7c7c7" } ] }, // 4 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { borderWidth : "2px 1px 1px 2px", borderStyle : "solid", borderColor : "#c7c7c7" }, aRowStyle : [ { padding : "2px 0 0", borderWidth : "1px 2px 2px 1px", borderStyle : "solid", borderColor : "#c7c7c7" } ] }, // 5 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { borderWidth : "1px 2px 2px 1px", borderStyle : "solid", borderColor : "#c7c7c7" }, aRowStyle : [ { padding : "1px 0 0", borderWidth : "2px 1px 1px 2px", borderStyle : "solid", borderColor : "#c7c7c7" } ] }, */ // Black theme ====================================================== // 6 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // 7 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", backgroundColor : "#f3f3f3", color : "#666666" } ] }, // 8 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { backgroundColor : "#ffffff", borderTop : "1px solid #c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #c7c7c7", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", borderBottom : "1px solid #c7c7c7", backgroundColor : "#f3f3f3", color : "#666666" } ] }, // 9 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #c7c7c7" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#f3f3f3", color : "#666666", borderRight : "1px solid #e7e7e7", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", borderTop : "1px solid #e7e7e7", borderRight : "1px solid #e7e7e7", color : "#666666" } ] }, // 10 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#f8f8f8", color : "#666666" }, { padding : "3px 4px 2px", backgroundColor : "#ebebeb", color : "#666666" } ] }, // 11 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, ht1stRowStyle : { padding : "3px 4px 2px", borderTop : "1px solid #000000", borderBottom : "1px solid #000000", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#ffffff", color : "#666666" }, { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#f8f8f8", color : "#666666" } ] }, // 12 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#f8f8f8", color : "#666666", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // 13 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#c7c7c7" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#333333", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#666666" } ] }, // Blue theme ====================================================== // 14 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] }, // 15 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 16 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { backgroundColor : "#ffffff", borderTop : "1px solid #a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #a6bcd1", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", borderBottom : "1px solid #a6bcd1", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 17 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, htTableStyle : { border : "1px solid #a6bcd1" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab", borderRight : "1px solid #e1eef7", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", borderTop : "1px solid #e1eef7", borderRight : "1px solid #e1eef7", color : "#3d76ab" } ] }, // 18 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#fafbfc", color : "#3d76ab" }, { padding : "3px 4px 2px", backgroundColor : "#e6ecf2", color : "#3d76ab" } ] }, // 19 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "0" }, ht1stRowStyle : { padding : "3px 4px 2px", borderTop : "1px solid #466997", borderBottom : "1px solid #466997", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#ffffff", color : "#3d76ab" }, { padding : "3px 4px 2px", borderBottom : "1px solid #ebebeb", backgroundColor : "#f6f8fa", color : "#3d76ab" } ] }, // 20 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, ht1stRowStyle : { padding : "3px 4px 2px", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#f6f8fa", color : "#3d76ab", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] }, // 21 { htTableProperty : { border : "0", cellPadding : "0", cellSpacing : "1" }, htTableStyle : { backgroundColor : "#a6bcd1" }, ht1stColumnStyle : { padding : "3px 4px 2px", backgroundColor : "#6284ab", color : "#ffffff", textAlign : "left", fontWeight : "normal" }, aRowStyle : [ { padding : "3px 4px 2px", backgroundColor : "#ffffff", color : "#3d76ab" } ] } ];
JavaScript
/*[ * LOAD_CONTENTS_FIELD * * 에디터 초기화 시에 넘어온 Contents(DB 저장 값)필드를 읽어 에디터에 설정한다. * * bDontAddUndo boolean Contents를 설정하면서 UNDO 히스토리는 추가 하지않는다. * ---------------------------------------------------------------------------]*/ /*[ * UPDATE_IR_FIELD * * 에디터의 IR값을 IR필드에 설정 한다. * * none * ---------------------------------------------------------------------------]*/ /*[ * CHANGE_EDITING_MODE * * 에디터의 편집 모드를 변경한다. * * sMode string 전환 할 모드명 * bNoFocus boolean 모드 전환 후에 에디터에 포커스를 강제로 할당하지 않는다. * ---------------------------------------------------------------------------]*/ /*[ * FOCUS * * 에디터 편집 영역에 포커스를 준다. * * none * ---------------------------------------------------------------------------]*/ /*[ * SET_IR * * IR값을 에디터에 설정 한다. * * none * ---------------------------------------------------------------------------]*/ /*[ * REGISTER_EDITING_AREA * * 편집 영역을 플러그인을 등록 시킨다. 원활한 모드 전환과 IR값 공유등를 위해서 초기화 시에 등록이 필요하다. * * oEditingAreaPlugin object 편집 영역 플러그인 인스턴스 * ---------------------------------------------------------------------------]*/ /*[ * MSG_EDITING_AREA_RESIZE_STARTED * * 편집 영역 사이즈 조절이 시작 되었음을 알리는 메시지. * * none * ---------------------------------------------------------------------------]*/ /*[ * RESIZE_EDITING_AREA * * 편집 영역 사이즈를 설정 한다. 변경 전후에 MSG_EDITIING_AREA_RESIZE_STARTED/MSG_EDITING_AREA_RESIZE_ENED를 발생 시켜 줘야 된다. * * ipNewWidth number 새 폭 * ipNewHeight number 새 높이 * ---------------------------------------------------------------------------]*/ /*[ * RESIZE_EDITING_AREA_BY * * 편집 영역 사이즈를 늘리거나 줄인다. 변경 전후에 MSG_EDITIING_AREA_RESIZE_STARTED/MSG_EDITING_AREA_RESIZE_ENED를 발생 시켜 줘야 된다. * 변경치를 입력하면 원래 사이즈에서 변경하여 px로 적용하며, width가 %로 설정된 경우에는 폭 변경치가 입력되어도 적용되지 않는다. * * ipWidthChange number 폭 변경치 * ipHeightChange number 높이 변경치 * ---------------------------------------------------------------------------]*/ /*[ * MSG_EDITING_AREA_RESIZE_ENDED * * 편집 영역 사이즈 조절이 끝났음을 알리는 메시지. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc IR 값과 복수개의 편집 영역을 관리하는 플러그인 */ nhn.husky.SE_EditingAreaManager = jindo.$Class({ name : "SE_EditingAreaManager", // Currently active plugin instance(SE_EditingArea_???) oActivePlugin : null, // Intermediate Representation of the content being edited. // This should be a textarea element. elContentsField : null, bIsDirty : false, bAutoResize : false, // [SMARTEDITORSUS-677] 에디터의 자동확장 기능 On/Off 여부 $init : function(sDefaultEditingMode, elContentsField, oDimension, fOnBeforeUnload, elAppContainer){ this.sDefaultEditingMode = sDefaultEditingMode; this.elContentsField = jindo.$(elContentsField); this._assignHTMLElements(elAppContainer); this.fOnBeforeUnload = fOnBeforeUnload; this.oEditingMode = {}; this.elContentsField.style.display = "none"; this.nMinWidth = parseInt((oDimension.nMinWidth || 60), 10); this.nMinHeight = parseInt((oDimension.nMinHeight || 60), 10); var oWidth = this._getSize([oDimension.nWidth, oDimension.width, this.elEditingAreaContainer.offsetWidth], this.nMinWidth); var oHeight = this._getSize([oDimension.nHeight, oDimension.height, this.elEditingAreaContainer.offsetHeight], this.nMinHeight); this.elEditingAreaContainer.style.width = oWidth.nSize + oWidth.sUnit; this.elEditingAreaContainer.style.height = oHeight.nSize + oHeight.sUnit; if(oWidth.sUnit === "px"){ elAppContainer.style.width = (oWidth.nSize + 2) + "px"; }else if(oWidth.sUnit === "%"){ elAppContainer.style.minWidth = this.nMinWidth + "px"; } }, _getSize : function(aSize, nMin){ var i, nLen, aRxResult, nSize, sUnit, sDefaultUnit = "px"; nMin = parseInt(nMin, 10); for(i=0, nLen=aSize.length; i<nLen; i++){ if(!aSize[i]){ continue; } if(!isNaN(aSize[i])){ nSize = parseInt(aSize[i], 10); sUnit = sDefaultUnit; break; } aRxResult = /([0-9]+)(.*)/i.exec(aSize[i]); if(!aRxResult || aRxResult.length < 2 || aRxResult[1] <= 0){ continue; } nSize = parseInt(aRxResult[1], 10); sUnit = aRxResult[2]; if(!sUnit){ sUnit = sDefaultUnit; } if(nSize < nMin && sUnit === sDefaultUnit){ nSize = nMin; } break; } if(!sUnit){ sUnit = sDefaultUnit; } if(isNaN(nSize) || (nSize < nMin && sUnit === sDefaultUnit)){ nSize = nMin; } return {nSize : nSize, sUnit : sUnit}; }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elEditingAreaContainer = jindo.$$.getSingle("DIV.husky_seditor_editing_area_container", elAppContainer); //@ec] }, $BEFORE_MSG_APP_READY : function(msg){ this.oNavigator = jindo.$Agent().navigator(); this.oApp.exec("ADD_APP_PROPERTY", ["elEditingAreaContainer", this.elEditingAreaContainer]); this.oApp.exec("ADD_APP_PROPERTY", ["welEditingAreaContainer", jindo.$Element(this.elEditingAreaContainer)]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingAreaHeight", jindo.$Fn(this.getEditingAreaHeight, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingAreaWidth", jindo.$Fn(this.getEditingAreaWidth, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getRawContents", jindo.$Fn(this.getRawContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getContents", jindo.$Fn(this.getContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getIR", jindo.$Fn(this.getIR, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["setContents", this.setContents]); this.oApp.exec("ADD_APP_PROPERTY", ["setIR", this.setIR]); this.oApp.exec("ADD_APP_PROPERTY", ["getEditingMode", jindo.$Fn(this.getEditingMode, this).bind()]); }, $ON_MSG_APP_READY : function(){ this.htOptions = this.oApp.htOptions[this.name] || {}; this.sDefaultEditingMode = this.htOptions["sDefaultEditingMode"] || this.sDefaultEditingMode; this.iframeWindow = this.oApp.getWYSIWYGWindow(); this.oApp.exec("REGISTER_CONVERTERS", []); this.oApp.exec("CHANGE_EDITING_MODE", [this.sDefaultEditingMode, true]); this.oApp.exec("LOAD_CONTENTS_FIELD", [false]); if(!!this.fOnBeforeUnload){ window.onbeforeunload = this.fOnBeforeUnload; }else{ window.onbeforeunload = jindo.$Fn(function(){ this.oApp.exec("MSG_BEFOREUNLOAD_FIRED"); //if(this.getContents() != this.elContentsField.value || this.bIsDirty){ if(this.getRawContents() != this.sCurrentRawContents || this.bIsDirty){ return this.oApp.$MSG("SE_EditingAreaManager.onExit"); } }, this).bind(); } }, $AFTER_MSG_APP_READY : function(){ this.oApp.exec("UPDATE_RAW_CONTENTS"); if(!!this.oApp.htOptions[this.name] && this.oApp.htOptions[this.name].bAutoResize){ this.bAutoResize = this.oApp.htOptions[this.name].bAutoResize; } this.startAutoResize(); // [SMARTEDITORSUS-677] 편집영역 자동 확장 옵션이 TRUE이면 자동확장 시작 }, $ON_LOAD_CONTENTS_FIELD : function(bDontAddUndo){ var sContentsFieldValue = this.elContentsField.value; // [SMARTEDITORSUS-177] [IE9] 글 쓰기, 수정 시에 elContentsField 에 들어간 공백을 제거 // [SMARTEDITORSUS-312] [FF4] 인용구 첫번째,두번째 디자인 1회 선택 시 에디터에 적용되지 않음 sContentsFieldValue = sContentsFieldValue.replace(/^\s+/, ""); this.oApp.exec("SET_CONTENTS", [sContentsFieldValue, bDontAddUndo]); }, // 현재 contents를 form의 textarea에 세팅 해 줌. // form submit 전에 이 부분을 실행시켜야 됨. $ON_UPDATE_CONTENTS_FIELD : function(){ //this.oIRField.value = this.oApp.getIR(); this.elContentsField.value = this.oApp.getContents(); this.oApp.exec("UPDATE_RAW_CONTENTS"); //this.sCurrentRawContents = this.elContentsField.value; }, // 에디터의 현재 상태를 기억해 둠. 페이지를 떠날 때 이 값이 변경 됐는지 확인 해서 내용이 변경 됐다는 경고창을 띄움 // RawContents 대신 contents를 이용해도 되지만, contents 획득을 위해서는 변환기를 실행해야 되기 때문에 RawContents 이용 $ON_UPDATE_RAW_CONTENTS : function(){ this.sCurrentRawContents = this.oApp.getRawContents(); }, $BEFORE_CHANGE_EDITING_MODE : function(sMode){ if(!this.oEditingMode[sMode]){ return false; } this.stopAutoResize(); // [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 중지함 this._oPrevActivePlugin = this.oActivePlugin; this.oActivePlugin = this.oEditingMode[sMode]; }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(this._oPrevActivePlugin){ var sIR = this._oPrevActivePlugin.getIR(); this.oApp.exec("SET_IR", [sIR]); //this.oApp.exec("ENABLE_UI", [this._oPrevActivePlugin.sMode]); this._setEditingAreaDimension(); } //this.oApp.exec("DISABLE_UI", [this.oActivePlugin.sMode]); this.startAutoResize(); // [SMARTEDITORSUS-677] 변경된 편집 모드에서의 자동확장을 시작 if(!bNoFocus){ this.oApp.delayedExec("FOCUS", [], 0); } }, /** * 페이지를 떠날 때 alert을 표시할지 여부를 셋팅하는 함수. */ $ON_SET_IS_DIRTY : function(bIsDirty){ this.bIsDirty = bIsDirty; }, $ON_FOCUS : function(){ if(!this.oActivePlugin || typeof this.oActivePlugin.setIR != "function"){ return; } // [SMARTEDITORSUS-599] ipad 대응 이슈. // ios5에서는 this.iframe.contentWindow focus가 없어서 생긴 이슈. // document가 아닌 window에 focus() 주어야만 본문에 focus가 가고 입력이됨. if(!!this.oNavigator.msafari && !!this.iframeWindow && !this.iframeWindow.document.hasFocus()){ this.iframeWindow.focus(); } this.oActivePlugin.focus(); }, $ON_IE_FOCUS : function(){ if(!this.oApp.oNavigator.ie){ return; } this.oApp.exec("FOCUS"); }, $ON_SET_CONTENTS : function(sContents, bDontAddUndoHistory){ this.setContents(sContents, bDontAddUndoHistory); }, $BEFORE_SET_IR : function(sIR, bDontAddUndoHistory){ bDontAddUndoHistory = bDontAddUndoHistory || false; if(!bDontAddUndoHistory){ this.oApp.exec("RECORD_UNDO_ACTION", ["BEFORE SET CONTENTS", {sSaveTarget:"BODY"}]); } }, $ON_SET_IR : function(sIR){ if(!this.oActivePlugin || typeof this.oActivePlugin.setIR != "function"){ return; } this.oActivePlugin.setIR(sIR); }, $AFTER_SET_IR : function(sIR, bDontAddUndoHistory){ bDontAddUndoHistory = bDontAddUndoHistory || false; if(!bDontAddUndoHistory){ this.oApp.exec("RECORD_UNDO_ACTION", ["AFTER SET CONTENTS", {sSaveTarget:"BODY"}]); } }, $ON_REGISTER_EDITING_AREA : function(oEditingAreaPlugin){ this.oEditingMode[oEditingAreaPlugin.sMode] = oEditingAreaPlugin; this.attachDocumentEvents(oEditingAreaPlugin.oEditingArea); this._setEditingAreaDimension(oEditingAreaPlugin); }, $ON_MSG_EDITING_AREA_RESIZE_STARTED : function(){ this._fitElementInEditingArea(this.elEditingAreaContainer); this.oApp.exec("STOP_AUTORESIZE_EDITING_AREA"); // [SMARTEDITORSUS-677] 사용자가 편집영역 사이즈를 변경하면 자동확장 기능 중지 this.oApp.exec("SHOW_EDITING_AREA_COVER"); this.elEditingAreaContainer.style.overflow = "hidden"; // this.elResizingBoard.style.display = "block"; this.iStartingHeight = parseInt(this.elEditingAreaContainer.style.height, 10); }, /** * [SMARTEDITORSUS-677] 편집영역 자동확장 기능을 중지함 */ $ON_STOP_AUTORESIZE_EDITING_AREA : function(){ if(!this.bAutoResize){ return; } this.stopAutoResize(); this.bAutoResize = false; }, /** * [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 시작함 */ startAutoResize : function(){ if(!this.bAutoResize || !this.oActivePlugin || typeof this.oActivePlugin.startAutoResize != "function"){ return; } this.oActivePlugin.startAutoResize(); }, /** * [SMARTEDITORSUS-677] 해당 편집 모드에서의 자동확장을 중지함 */ stopAutoResize : function(){ if(!this.bAutoResize || !this.oActivePlugin || typeof this.oActivePlugin.stopAutoResize != "function"){ return; } this.oActivePlugin.stopAutoResize(); }, $ON_RESIZE_EDITING_AREA: function(ipNewWidth, ipNewHeight){ if(ipNewWidth !== null && typeof ipNewWidth !== "undefined"){ this._resizeWidth(ipNewWidth, "px"); } if(ipNewHeight !== null && typeof ipNewHeight !== "undefined"){ this._resizeHeight(ipNewHeight, "px"); } this._fitElementInEditingArea(this.elResizingBoard); this._setEditingAreaDimension(); }, _resizeWidth : function(ipNewWidth, sUnit){ var iNewWidth = parseInt(ipNewWidth, 10); if(iNewWidth < this.nMinWidth){ iNewWidth = this.nMinWidth; } if(ipNewWidth){ this.elEditingAreaContainer.style.width = iNewWidth + sUnit; } }, _resizeHeight : function(ipNewHeight, sUnit){ var iNewHeight = parseInt(ipNewHeight, 10); if(iNewHeight < this.nMinHeight){ iNewHeight = this.nMinHeight; } if(ipNewHeight){ this.elEditingAreaContainer.style.height = iNewHeight + sUnit; } }, $ON_RESIZE_EDITING_AREA_BY : function(ipWidthChange, ipHeightChange){ var iWidthChange = parseInt(ipWidthChange, 10); var iHeightChange = parseInt(ipHeightChange, 10); var iWidth; var iHeight; if(ipWidthChange !== 0 && this.elEditingAreaContainer.style.width.indexOf("%") === -1){ iWidth = this.elEditingAreaContainer.style.width?parseInt(this.elEditingAreaContainer.style.width, 10)+iWidthChange:null; } if(iHeightChange !== 0){ iHeight = this.elEditingAreaContainer.style.height?this.iStartingHeight+iHeightChange:null; } if(!ipWidthChange && !iHeightChange){ return; } this.oApp.exec("RESIZE_EDITING_AREA", [iWidth, iHeight]); }, $ON_MSG_EDITING_AREA_RESIZE_ENDED : function(FnMouseDown, FnMouseMove, FnMouseUp){ this.oApp.exec("HIDE_EDITING_AREA_COVER"); this.elEditingAreaContainer.style.overflow = ""; // this.elResizingBoard.style.display = "none"; this._setEditingAreaDimension(); }, $ON_SHOW_EDITING_AREA_COVER : function(){ // this.elEditingAreaContainer.style.overflow = "hidden"; if(!this.elResizingBoard){ this.createCoverDiv(); } this.elResizingBoard.style.display = "block"; }, $ON_HIDE_EDITING_AREA_COVER : function(){ // this.elEditingAreaContainer.style.overflow = ""; if(!this.elResizingBoard){ return; } this.elResizingBoard.style.display = "none"; }, $ON_KEEP_WITHIN_EDITINGAREA : function(elLayer, nHeight){ var nTop = parseInt(elLayer.style.top, 10); if(nTop + elLayer.offsetHeight > this.oApp.elEditingAreaContainer.offsetHeight){ if(typeof nHeight == "number"){ elLayer.style.top = nTop - elLayer.offsetHeight - nHeight + "px"; }else{ elLayer.style.top = this.oApp.elEditingAreaContainer.offsetHeight - elLayer.offsetHeight + "px"; } } var nLeft = parseInt(elLayer.style.left, 10); if(nLeft + elLayer.offsetWidth > this.oApp.elEditingAreaContainer.offsetWidth){ elLayer.style.left = this.oApp.elEditingAreaContainer.offsetWidth - elLayer.offsetWidth + "px"; } }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_EVENT_EDITING_AREA_MOUSEDOWN : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, $ON_EVENT_EDITING_AREA_SCROLL : function(){ this.oApp.exec("HIDE_ACTIVE_LAYER", []); }, _setEditingAreaDimension : function(oEditingAreaPlugin){ oEditingAreaPlugin = oEditingAreaPlugin || this.oActivePlugin; this._fitElementInEditingArea(oEditingAreaPlugin.elEditingArea); }, _fitElementInEditingArea : function(el){ el.style.height = this.elEditingAreaContainer.offsetHeight+"px"; // el.style.width = this.elEditingAreaContainer.offsetWidth+"px"; // el.style.width = this.elEditingAreaContainer.style.width || (this.elEditingAreaContainer.offsetWidth+"px"); }, attachDocumentEvents : function(doc){ this.oApp.registerBrowserEvent(doc, "click", "EVENT_EDITING_AREA_CLICK"); this.oApp.registerBrowserEvent(doc, "dblclick", "EVENT_EDITING_AREA_DBLCLICK"); this.oApp.registerBrowserEvent(doc, "mousedown", "EVENT_EDITING_AREA_MOUSEDOWN"); this.oApp.registerBrowserEvent(doc, "mousemove", "EVENT_EDITING_AREA_MOUSEMOVE"); this.oApp.registerBrowserEvent(doc, "mouseup", "EVENT_EDITING_AREA_MOUSEUP"); this.oApp.registerBrowserEvent(doc, "mouseout", "EVENT_EDITING_AREA_MOUSEOUT"); this.oApp.registerBrowserEvent(doc, "mousewheel", "EVENT_EDITING_AREA_MOUSEWHEEL"); this.oApp.registerBrowserEvent(doc, "keydown", "EVENT_EDITING_AREA_KEYDOWN"); this.oApp.registerBrowserEvent(doc, "keypress", "EVENT_EDITING_AREA_KEYPRESS"); this.oApp.registerBrowserEvent(doc, "keyup", "EVENT_EDITING_AREA_KEYUP"); this.oApp.registerBrowserEvent(doc, "scroll", "EVENT_EDITING_AREA_SCROLL"); }, createCoverDiv : function(){ this.elResizingBoard = document.createElement("DIV"); this.elEditingAreaContainer.insertBefore(this.elResizingBoard, this.elEditingAreaContainer.firstChild); this.elResizingBoard.style.position = "absolute"; this.elResizingBoard.style.background = "#000000"; this.elResizingBoard.style.zIndex=100; this.elResizingBoard.style.border=1; this.elResizingBoard.style["opacity"] = 0.0; this.elResizingBoard.style.filter="alpha(opacity=0.0)"; this.elResizingBoard.style["MozOpacity"]=0.0; this.elResizingBoard.style["-moz-opacity"] = 0.0; this.elResizingBoard.style["-khtml-opacity"] = 0.0; this._fitElementInEditingArea(this.elResizingBoard); this.elResizingBoard.style.width = this.elEditingAreaContainer.offsetWidth+"px"; this.elResizingBoard.style.display = "none"; }, $ON_GET_COVER_DIV : function(sAttr,oReturn){ if(!!this.elResizingBoard) { oReturn[sAttr] = this.elResizingBoard; } }, getIR : function(){ if(!this.oActivePlugin){ return ""; } return this.oActivePlugin.getIR(); }, setIR : function(sIR, bDontAddUndo){ this.oApp.exec("SET_IR", [sIR, bDontAddUndo]); }, getRawContents : function(){ if(!this.oActivePlugin){ return ""; } return this.oActivePlugin.getRawContents(); }, getContents : function(){ var sIR = this.oApp.getIR(); var sContents; if(this.oApp.applyConverter){ sContents = this.oApp.applyConverter("IR_TO_DB", sIR, this.oApp.getWYSIWYGDocument()); }else{ sContents = sIR; } sContents = this._cleanContents(sContents); return sContents; }, _cleanContents : function(sContents){ return sContents.replace(new RegExp("(<img [^>]*>)"+unescape("%uFEFF")+"", "ig"), "$1"); }, setContents : function(sContents, bDontAddUndo){ var sIR; if(this.oApp.applyConverter){ sIR = this.oApp.applyConverter("DB_TO_IR", sContents, this.oApp.getWYSIWYGDocument()); }else{ sIR = sContents; } this.oApp.exec("SET_IR", [sIR, bDontAddUndo]); }, getEditingMode : function(){ return this.oActivePlugin.sMode; }, getEditingAreaWidth : function(){ return this.elEditingAreaContainer.offsetWidth; }, getEditingAreaHeight : function(){ return this.elEditingAreaContainer.offsetHeight; } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the editing mode using a Button element * @name hp_SE2M_EditingModeChanger.js */ nhn.husky.SE2M_EditingModeChanger = jindo.$Class({ name : "SE2M_EditingModeChanger", $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ elAppContainer = jindo.$(elAppContainer) || document; //@ec[ this.elWYSIWYGButton = jindo.$$.getSingle("BUTTON.se2_to_editor", elAppContainer); this.elHTMLSrcButton = jindo.$$.getSingle("BUTTON.se2_to_html", elAppContainer); this.elTEXTButton = jindo.$$.getSingle("BUTTON.se2_to_text", elAppContainer); //@ec] this.welWYSIWYGButtonLi = jindo.$Element(this.elWYSIWYGButton.parentNode); this.welHTMLSrcButtonLi = jindo.$Element(this.elHTMLSrcButton.parentNode); this.welTEXTButtonLi = jindo.$Element(this.elTEXTButton.parentNode); }, $ON_MSG_APP_READY : function(){ this.oApp.registerBrowserEvent(this.elWYSIWYGButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["WYSIWYG"]); this.oApp.registerBrowserEvent(this.elHTMLSrcButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["HTMLSrc"]); this.oApp.registerBrowserEvent(this.elTEXTButton, "click", "EVENT_CHANGE_EDITING_MODE_CLICKED", ["TEXT", false]); }, $ON_EVENT_CHANGE_EDITING_MODE_CLICKED : function(sMode, bNoAlertMsg){ if (sMode == 'TEXT') { //에디터 영역 내에 모든 내용 가져옴. var sContent = this.oApp.getIR(); // 내용이 있으면 경고창 띄우기 if (sContent.length > 0 && !bNoAlertMsg) { if ( !confirm(this.oApp.$MSG("SE2M_EditingModeChanger.confirmTextMode")) ) { return false; } } this.oApp.exec("CHANGE_EDITING_MODE", [sMode]); }else{ this.oApp.exec("CHANGE_EDITING_MODE", [sMode]); } if ('HTMLSrc' == sMode) { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['htmlmode']); } else if ('TEXT' == sMode) { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['textmode']); } else { this.oApp.exec('MSG_NOTIFY_CLICKCR', ['editormode']); } }, $ON_DISABLE_ALL_UI : function(htOptions){ htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); if(waExceptions.has("mode_switcher")){ return; } if(this.oApp.getEditingMode() == "WYSIWYG"){ this.welWYSIWYGButtonLi.removeClass("active"); this.elHTMLSrcButton.disabled = true; this.elTEXTButton.disabled = true; } else if (this.oApp.getEditingMode() == 'TEXT') { this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elHTMLSrcButton.disabled = true; }else{ this.welHTMLSrcButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elTEXTButton.disabled = true; } }, $ON_ENABLE_ALL_UI : function(){ if(this.oApp.getEditingMode() == "WYSIWYG"){ this.welWYSIWYGButtonLi.addClass("active"); this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = false; } else if (this.oApp.getEditingMode() == 'TEXT') { this.welTEXTButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = false; }else{ this.welHTMLSrcButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elTEXTButton.disabled = false; } }, $ON_CHANGE_EDITING_MODE : function(sMode){ if(sMode == "HTMLSrc"){ this.welWYSIWYGButtonLi.removeClass("active"); this.welHTMLSrcButtonLi.addClass("active"); this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = true; this.elTEXTButton.disabled = false; this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("DISABLE_ALL_UI", [{aExceptions:["mode_switcher"]}]); } else if (sMode == 'TEXT') { this.welWYSIWYGButtonLi.removeClass("active"); this.welHTMLSrcButtonLi.removeClass("active"); this.welTEXTButtonLi.addClass("active"); this.elWYSIWYGButton.disabled = false; this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = true; this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("DISABLE_ALL_UI", [{aExceptions:["mode_switcher"]}]); }else{ this.welWYSIWYGButtonLi.addClass("active"); this.welHTMLSrcButtonLi.removeClass("active"); this.welTEXTButtonLi.removeClass("active"); this.elWYSIWYGButton.disabled = true; this.elHTMLSrcButton.disabled = false; this.elTEXTButton.disabled = false; this.oApp.exec("RESET_STYLE_STATUS"); this.oApp.exec("ENABLE_ALL_UI", []); } } }); //}
JavaScript
/** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to editing the HTML source code using Textarea element * @name hp_SE_EditingArea_TEXT.js * @required SE_EditingAreaManager */ nhn.husky.SE_EditingArea_TEXT = jindo.$Class({ name : "SE_EditingArea_TEXT", sMode : "TEXT", sRxConverter : '@[0-9]+@', bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 $init : function(sTextArea) { this.elEditingArea = jindo.$(sTextArea); }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); this.oApp.exec("REGISTER_EDITING_AREA", [this]); this.oApp.exec("ADD_APP_PROPERTY", ["getTextAreaContents", jindo.$Fn(this.getRawContents, this).bind()]); }, $ON_MSG_APP_READY : function() { if(!!this.oApp.getEditingAreaHeight){ this.nMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 자동 확장 처리를 할 때 사용 } }, $ON_REGISTER_CONVERTERS : function() { this.oApp.exec("ADD_CONVERTER", ["IR_TO_TEXT", jindo.$Fn(this.irToText, this).bind()]); this.oApp.exec("ADD_CONVERTER", ["TEXT_TO_IR", jindo.$Fn(this.textToIr, this).bind()]); }, $ON_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { this.elEditingArea.style.display = "block"; } else { this.elEditingArea.style.display = "none"; } }, $AFTER_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { var o = new TextRange(this.elEditingArea); o.setSelection(0, 0); } //모바일 textarea에서는 직접 클릭을해야만 키보드가 먹히기 때문에 우선은 커서가 안보이게 해서 사용자가 직접 클릭을 유도. if(!!this.oNavigator.msafari){ this.elEditingArea.blur(); } }, irToText : function(sHtml) { var sContent = sHtml, nIdx = 0; var aTemp = sContent.match(new RegExp(this.sRxConverter)); // applyConverter에서 추가한 sTmpStr를 잠시 제거해준다. if (aTemp !== null) { sContent = sContent.replace(new RegExp(this.sRxConverter), ""); } //0.안보이는 값들에 대한 정리. (에디터 모드에 view와 text모드의 view를 동일하게 해주기 위해서) sContent = sContent.replace(/\r/g, '');// MS엑셀 테이블에서 tr별로 분리해주는 역할이\r이기 때문에 text모드로 변경시에 가독성을 위해 \r 제거하는 것은 임시 보류. - 11.01.28 by cielo sContent = sContent.replace(/[\n|\t]/g, ''); // 개행문자, 안보이는 공백 제거 sContent = sContent.replace(/[\v|\f]/g, ''); // 개행문자, 안보이는 공백 제거 //1. 먼저, 빈 라인 처리 . sContent = sContent.replace(/<p><br><\/p>/gi, '\n'); sContent = sContent.replace(/<P>&nbsp;<\/P>/gi, '\n'); //2. 빈 라인 이외에 linebreak 처리. sContent = sContent.replace(/<br(\s)*\/?>/gi, '\n'); // br 태그를 개행문자로 sContent = sContent.replace(/<br(\s[^\/]*)?>/gi, '\n'); // br 태그를 개행문자로 sContent = sContent.replace(/<\/p(\s[^\/]*)?>/gi, '\n'); // p 태그를 개행문자로 sContent = sContent.replace(/<\/li(\s[^\/]*)?>/gi, '\n'); // li 태그를 개행문자로 [SMARTEDITORSUS-107]개행 추가 sContent = sContent.replace(/<\/tr(\s[^\/]*)?>/gi, '\n'); // tr 태그를 개행문자로 [SMARTEDITORSUS-107]개행 추가 // 마지막 \n은 로직상 불필요한 linebreak를 제공하므로 제거해준다. nIdx = sContent.lastIndexOf('\n'); if (nIdx > -1 && sContent.substring(nIdx) == '\n') { sContent = sContent.substring(0, nIdx); } sContent = jindo.$S(sContent).stripTags().toString(); sContent = this.unhtmlSpecialChars(sContent); if (aTemp !== null) { // 제거했던sTmpStr를 추가해준다. sContent = aTemp[0] + sContent; } return sContent; }, textToIr : function(sHtml) { if (!sHtml) { return; } var sContent = sHtml, aTemp = null; // applyConverter에서 추가한 sTmpStr를 잠시 제거해준다. sTmpStr도 하나의 string으로 인식하는 경우가 있기 때문. aTemp = sContent.match(new RegExp(this.sRxConverter)); if (aTemp !== null) { sContent = sContent.replace(aTemp[0], ""); } sContent = this.htmlSpecialChars(sContent); sContent = this._addLineBreaker(sContent); if (aTemp !== null) { sContent = aTemp[0] + sContent; } return sContent; }, _addLineBreaker : function(sContent){ if(this.oApp.sLineBreaker === "BR"){ return sContent.replace(/\r?\n/g, "<BR>"); } var oContent = new StringBuffer(), aContent = sContent.split('\n'), // \n을 기준으로 블럭을 나눈다. aContentLng = aContent.length, sTemp = ""; for (var i = 0; i < aContentLng; i++) { sTemp = jindo.$S(aContent[i]).trim().$value(); if (i === aContentLng -1 && sTemp === "") { break; } if (sTemp !== null && sTemp !== "") { oContent.append('<P>'); oContent.append(aContent[i]); oContent.append('</P>'); } else { if (!jindo.$Agent().navigator().ie) { oContent.append('<P><BR></P>'); } else { oContent.append('<P>&nbsp;<\/P>'); } } } return oContent.toString(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ var htOption = { nMinHeight : this.nMinHeight, wfnCallback : jindo.$Fn(this.oApp.checkResizeGripPosition, this).bind() }; this.bAutoResize = true; this.AutoResizer = new nhn.husky.AutoResizer(this.elEditingArea, htOption); this.AutoResizer.bind(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.AutoResizer.unbind(); }, getIR : function() { var sIR = this.getRawContents(); if (this.oApp.applyConverter) { sIR = this.oApp.applyConverter(this.sMode + "_TO_IR", sIR, this.oApp.getWYSIWYGDocument()); } return sIR; }, setIR : function(sIR) { var sContent = sIR; if (this.oApp.applyConverter) { sContent = this.oApp.applyConverter("IR_TO_" + this.sMode, sContent, this.oApp.getWYSIWYGDocument()); } this.setRawContents(sContent); }, setRawContents : function(sContent) { if (typeof sContent !== 'undefined') { this.elEditingArea.value = sContent; } }, getRawContents : function() { return this.elEditingArea.value; }, focus : function() { this.elEditingArea.focus(); }, /** * HTML 태그에 해당하는 글자가 먹히지 않도록 바꿔주기 * * 동작) & 를 &amp; 로, < 를 &lt; 로, > 를 &gt; 로 바꿔준다 * * @param {String} sText * @return {String} */ htmlSpecialChars : function(sText) { return sText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;'); }, /** * htmlSpecialChars 의 반대 기능의 함수 * * 동작) &amp, &lt, &gt, &nbsp 를 각각 &, <, >, 빈칸으로 바꿔준다 * * @param {String} sText * @return {String} */ unhtmlSpecialChars : function(sText) { return sText.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&'); } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to editing the HTML source code using Textarea element * @name hp_SE_EditingArea_HTMLSrc.js * @required SE_EditingAreaManager */ nhn.husky.SE_EditingArea_HTMLSrc = jindo.$Class({ name : "SE_EditingArea_HTMLSrc", sMode : "HTMLSrc", bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 $init : function(sTextArea) { this.elEditingArea = jindo.$(sTextArea); }, $BEFORE_MSG_APP_READY : function() { this.oNavigator = jindo.$Agent().navigator(); this.oApp.exec("REGISTER_EDITING_AREA", [this]); }, $ON_MSG_APP_READY : function() { if(!!this.oApp.getEditingAreaHeight){ this.nMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 자동 확장 처리를 할 때 사용 } }, $ON_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { this.elEditingArea.style.display = "block"; } else { this.elEditingArea.style.display = "none"; } }, $AFTER_CHANGE_EDITING_MODE : function(sMode) { if (sMode == this.sMode) { var o = new TextRange(this.elEditingArea); o.setSelection(0, 0); //모바일 textarea에서는 직접 클릭을해야만 키보드가 먹히기 때문에 우선은 커서가 안보이게 해서 사용자가 직접 클릭을 유도. if(!!this.oNavigator.msafari){ this.elEditingArea.blur(); } } }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ var htOption = { nMinHeight : this.nMinHeight, wfnCallback : jindo.$Fn(this.oApp.checkResizeGripPosition, this).bind() }; this.bAutoResize = true; this.AutoResizer = new nhn.husky.AutoResizer(this.elEditingArea, htOption); this.AutoResizer.bind(); }, /** * [SMARTEDITORSUS-677] HTML 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.AutoResizer.unbind(); }, getIR : function() { var sIR = this.getRawContents(); if (this.oApp.applyConverter) { sIR = this.oApp.applyConverter(this.sMode + "_TO_IR", sIR, this.oApp.getWYSIWYGDocument()); } return sIR; }, setIR : function(sIR) { if(sIR.toLowerCase() === "<br>" || sIR.toLowerCase() === "<p>&nbsp;</p>" || sIR.toLowerCase() === "<p><br></p>"){ sIR=""; } var sContent = sIR; if (this.oApp.applyConverter) { sContent = this.oApp.applyConverter("IR_TO_" + this.sMode, sContent, this.oApp.getWYSIWYGDocument()); } this.setRawContents(sContent); }, setRawContents : function(sContent) { if (typeof sContent !== 'undefined') { this.elEditingArea.value = sContent; } }, getRawContents : function() { return this.elEditingArea.value; }, focus : function() { this.elEditingArea.focus(); } }); /** * Selection for textfield * @author hooriza */ if (typeof window.TextRange == 'undefined') { window.TextRange = {}; } TextRange = function(oEl, oDoc) { this._o = oEl; this._oDoc = (oDoc || document); }; TextRange.prototype.getSelection = function() { var obj = this._o; var ret = [-1, -1]; if(isNaN(this._o.selectionStart)) { obj.focus(); // textarea support added by nagoon97 var range = this._oDoc.body.createTextRange(); var rangeField = null; rangeField = this._oDoc.selection.createRange().duplicate(); range.moveToElementText(obj); rangeField.collapse(true); range.setEndPoint("EndToEnd", rangeField); ret[0] = range.text.length; rangeField = this._oDoc.selection.createRange().duplicate(); range.moveToElementText(obj); rangeField.collapse(false); range.setEndPoint("EndToEnd", rangeField); ret[1] = range.text.length; obj.blur(); } else { ret[0] = obj.selectionStart; ret[1] = obj.selectionEnd; } return ret; }; TextRange.prototype.setSelection = function(start, end) { var obj = this._o; if (typeof end == 'undefined') { end = start; } if (obj.setSelectionRange) { obj.setSelectionRange(start, end); } else if (obj.createTextRange) { var range = obj.createTextRange(); range.collapse(true); range.moveStart("character", start); range.moveEnd("character", end - start); range.select(); obj.blur(); } }; TextRange.prototype.copy = function() { var r = this.getSelection(); return this._o.value.substring(r[0], r[1]); }; TextRange.prototype.paste = function(sStr) { var obj = this._o; var sel = this.getSelection(); var value = obj.value; var pre = value.substr(0, sel[0]); var post = value.substr(sel[1]); value = pre + sStr + post; obj.value = value; var n = 0; if (typeof this._oDoc.body.style.maxHeight == "undefined") { var a = pre.match(/\n/gi); n = ( a !== null ? a.length : 0 ); } this.setSelection(sel[0] + sStr.length - n); }; TextRange.prototype.cut = function() { var r = this.copy(); this.paste(''); return r; }; //}
JavaScript
/** * @pluginDesc Enter키 입력시에 현재 줄을 P 태그로 감거나 <br> 태그를 삽입한다. */ nhn.husky.SE_WYSIWYGEnterKey = jindo.$Class({ name : "SE_WYSIWYGEnterKey", $init : function(sLineBreaker){ if(sLineBreaker == "BR"){ this.sLineBreaker = "BR"; }else{ this.sLineBreaker = "P"; } this.htBrowser = jindo.$Agent().navigator(); // [SMARTEDITORSUS-227] IE 인 경우에도 에디터 Enter 처리 로직을 사용하도록 수정 if(this.htBrowser.opera && this.sLineBreaker == "P"){ this.$ON_MSG_APP_READY = function(){}; } /** * [SMARTEDITORSUS-230] 밑줄+색상변경 후, 엔터치면 스크립트 오류 * [SMARTEDITORSUS-180] [IE9] 배경색 적용 후, 엔터키 2회이상 입력시 커서위치가 다음 라인으로 이동하지 않음 * 오류 현상 : IE9 에서 엔터 후 생성된 P 태그가 "빈 SPAN 태그만 가지는 경우" P 태그 영역이 보이지 않거나 포커스가 위로 올라가 보임 * 해결 방법 : 커서 홀더로 IE 이외에서는 <br> 을 사용 * - IE 에서는 렌더링 시 <br> 부분에서 비정상적인 P 태그가 생성되어 [SMARTEDITORSUS-230] 오류 발생 * unescape("%uFEFF") (BOM) 을 추가 * - IE9 표준모드에서 [SMARTEDITORSUS-180] 의 문제가 발생함 * (unescape("%u2028") (Line separator) 를 사용하면 P 가 보여지나 사이드이펙트가 우려되어 사용하지 않음) * IE 브라우저에서 Enter 처리 시, &nbsp; 를 넣어주므로 해당 방식을 그대로 사용하도록 수정함 */ if(this.htBrowser.ie){ this._addCursorHolder = this._addCursorHolderSpace; if(this.htBrowser.nativeVersion < 9 || document.documentMode < 9){ this._addExtraCursorHolder = function(){}; this._addBlankTextAllSpan = function(){}; } }else{ this._addExtraCursorHolder = function(){}; this._addBlankText = function(){}; this._addBlankTextAllSpan = function(){}; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["sLineBreaker", this.sLineBreaker]); this.oSelection = this.oApp.getEmptySelection(); this.tmpTextNode = this.oSelection._document.createTextNode(unescape("%u00A0")); // 공백(&nbsp;) 추가 시 사용할 노드 jindo.$Fn(this._onKeyDown, this).attach(this.oApp.getWYSIWYGDocument(), "keydown"); }, _onKeyDown : function(oEvent){ var oKeyInfo = oEvent.key(); if(oKeyInfo.shift){ return; } if(oKeyInfo.enter){ if(this.sLineBreaker == "BR"){ this._insertBR(oEvent); }else{ this._wrapBlock(oEvent); } } }, /** * [SMARTEDITORSUS-950] 에디터 적용 페이지의 Compatible meta IE=edge 설정 시 줄간격 벌어짐 이슈 (<BR>) */ $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER", ["IR_TO_DB", jindo.$Fn(this.onIrToDB, this).bind()]); }, /** * IR_TO_DB 변환기 처리 * Chrome, FireFox인 경우에만 아래와 같은 처리를 합니다. * : 저장 시 본문 영역에서 P 아래의 모든 하위 태그 중 가장 마지막 childNode가 BR인 경우를 탐색하여 이를 &nbsp;로 변경해 줍니다. */ onIrToDB : function(sHTML){ var sContents = sHTML, rxRegEx = /<br(\s[^>]*)?\/?>((?:<\/span>)?<\/p>)/gi; if(this.htBrowser.chrome || this.htBrowser.firefox){ if(rxRegEx.test(sContents)){ sContents = sContents.replace(rxRegEx, "&nbsp;$2"); } } return sContents; }, // [IE] Selection 내의 노드를 가져와 빈 노드에 unescape("%uFEFF") (BOM) 을 추가 _addBlankText : function(oSelection){ var oNodes = oSelection.getNodes(), i, nLen, oNode, oNodeChild, tmpTextNode; for(i=0, nLen=oNodes.length; i<nLen; i++){ oNode = oNodes[i]; if(oNode.nodeType !== 1 || oNode.tagName !== "SPAN"){ continue; } if(oNode.id.indexOf(oSelection.HUSKY_BOOMARK_START_ID_PREFIX) > -1 || oNode.id.indexOf(oSelection.HUSKY_BOOMARK_END_ID_PREFIX) > -1){ continue; } oNodeChild = oNode.firstChild; if(!oNodeChild || (oNodeChild.nodeType == 3 && nhn.husky.SE2M_Utils.isBlankTextNode(oNodeChild)) || (oNodeChild.nodeType == 1 && oNode.childNodes.length == 1 && (oNodeChild.id.indexOf(oSelection.HUSKY_BOOMARK_START_ID_PREFIX) > -1 || oNodeChild.id.indexOf(oSelection.HUSKY_BOOMARK_END_ID_PREFIX) > -1))){ tmpTextNode = oSelection._document.createTextNode(unescape("%uFEFF")); oNode.appendChild(tmpTextNode); } } }, // [IE 이외] 빈 노드 내에 커서를 표시하기 위한 처리 _addCursorHolder : function(elWrapper){ var elStyleOnlyNode = elWrapper; if(elWrapper.innerHTML == "" || (elStyleOnlyNode = this._getStyleOnlyNode(elWrapper))){ elStyleOnlyNode.innerHTML = "<br>"; } if(!elStyleOnlyNode){ elStyleOnlyNode = this._getStyleNode(elWrapper); } return elStyleOnlyNode; }, // [IE] 빈 노드 내에 커서를 표시하기 위한 처리 (_addSpace 사용) _addCursorHolderSpace : function(elWrapper){ var elNode; this._addSpace(elWrapper); elNode = this._getStyleNode(elWrapper); if(elNode.innerHTML == ""){ elNode.innerHTML = unescape("%uFEFF"); } return elNode; }, _wrapBlock : function(oEvent, sWrapperTagName){ var oSelection = this.oApp.getSelection(), sBM = oSelection.placeStringBookmark(), oLineInfo = oSelection.getLineInfo(), oStart = oLineInfo.oStart, oEnd = oLineInfo.oEnd, oSWrapper, oEWrapper, elStyleOnlyNode; // line broke by sibling // or // the parent line breaker is just a block container if(!oStart.bParentBreak || oSelection.rxBlockContainer.test(oStart.oLineBreaker.tagName)){ oEvent.stop(); // 선택된 내용은 삭제 oSelection.deleteContents(); if(!!oStart.oNode.parentNode && oStart.oNode.parentNode.nodeType !== 11){ // LineBreaker 로 감싸서 분리 oSWrapper = this.oApp.getWYSIWYGDocument().createElement(this.sLineBreaker); oSelection.moveToBookmark(sBM); //oSelection.moveToStringBookmark(sBM, true); oSelection.setStartBefore(oStart.oNode); this._addBlankText(oSelection); oSelection.surroundContents(oSWrapper); oSelection.collapseToEnd(); oEWrapper = this.oApp.getWYSIWYGDocument().createElement(this.sLineBreaker); oSelection.setEndAfter(oEnd.oNode); this._addBlankText(oSelection); oSelection.surroundContents(oEWrapper); oSelection.moveToStringBookmark(sBM, true); // [SMARTEDITORSUS-180] 포커스 리셋 oSelection.collapseToEnd(); // [SMARTEDITORSUS-180] 포커스 리셋 oSelection.removeStringBookmark(sBM); oSelection.select(); // Cursor Holder 추가 // insert a cursor holder(br) if there's an empty-styling-only-tag surrounding current cursor elStyleOnlyNode = this._addCursorHolder(oSWrapper); if(oEWrapper.lastChild !== null && oEWrapper.lastChild.tagName == "BR"){ oEWrapper.removeChild(oEWrapper.lastChild); } elStyleOnlyNode = this._addCursorHolder(oEWrapper); if(oEWrapper.nextSibling && oEWrapper.nextSibling.tagName == "BR"){ oEWrapper.parentNode.removeChild(oEWrapper.nextSibling); } oSelection.selectNodeContents(elStyleOnlyNode); oSelection.collapseToStart(); oSelection.select(); this.oApp.exec("CHECK_STYLE_CHANGE", []); sBM = oSelection.placeStringBookmark(); setTimeout(jindo.$Fn(function(sBM){ var elBookmark = oSelection.getStringBookmark(sBM); if(!elBookmark){return;} oSelection.moveToStringBookmark(sBM); oSelection.select(); oSelection.removeStringBookmark(sBM); }, this).bind(sBM), 0); return; } } var elBookmark; // 아래는 기본적으로 브라우저 기본 기능에 맡겨서 처리함 if(this.htBrowser.firefox){ elBookmark = oSelection.getStringBookmark(sBM, true); if(elBookmark && elBookmark.nextSibling && elBookmark.nextSibling.tagName == "IFRAME"){ setTimeout(jindo.$Fn(function(sBM){ var elBookmark = oSelection.getStringBookmark(sBM); if(!elBookmark){return;} oSelection.moveToStringBookmark(sBM); oSelection.select(); oSelection.removeStringBookmark(sBM); }, this).bind(sBM), 0); }else{ oSelection.removeStringBookmark(sBM); } }else if(this.htBrowser.ie){ elBookmark = oSelection.getStringBookmark(sBM, true); var elParentNode = elBookmark.parentNode, bAddUnderline = false, bAddLineThrough = false; if(!elBookmark || !elParentNode){// || elBookmark.nextSibling){ oSelection.removeStringBookmark(sBM); return; } oSelection.removeStringBookmark(sBM); bAddUnderline = (elParentNode.tagName === "U" || nhn.husky.SE2M_Utils.findAncestorByTagName("U", elParentNode) !== null); bAddLineThrough = (elParentNode.tagName === "S" || elParentNode.tagName === "STRIKE" || (nhn.husky.SE2M_Utils.findAncestorByTagName("S", elParentNode) !== null && nhn.husky.SE2M_Utils.findAncestorByTagName("STRIKE", elParentNode) !== null)); // [SMARTEDITORSUS-26] Enter 후에 밑줄/취소선이 복사되지 않는 문제를 처리 (브라우저 Enter 처리 후 실행되도록 setTimeout 사용) if(bAddUnderline || bAddLineThrough){ setTimeout(jindo.$Fn(this._addTextDecorationTag, this).bind(bAddUnderline, bAddLineThrough), 0); return; } // [SMARTEDITORSUS-180] 빈 SPAN 태그에 의해 엔터 후 엔터가 되지 않은 것으로 보이는 문제 (브라우저 Enter 처리 후 실행되도록 setTimeout 사용) setTimeout(jindo.$Fn(this._addExtraCursorHolder, this).bind(elParentNode), 0); }else{ oSelection.removeStringBookmark(sBM); } }, // [IE9 standard mode] 엔터 후의 상/하단 P 태그를 확인하여 BOM, 공백(&nbsp;) 추가 _addExtraCursorHolder : function(elUpperNode){ var oNodeChild, oPrevChild, elHtml; elUpperNode = this._getStyleOnlyNode(elUpperNode); // 엔터 후의 상단 SPAN 노드에 BOM 추가 //if(!!elUpperNode && /^(B|EM|I|LABEL|SPAN|STRONG|SUB|SUP|U|STRIKE)$/.test(elUpperNode.tagName) === false){ if(!!elUpperNode && elUpperNode.tagName === "SPAN"){ // SPAN 인 경우에만 발생함 oNodeChild = elUpperNode.lastChild; while(!!oNodeChild){ // 빈 Text 제거 oPrevChild = oNodeChild.previousSibling; if(oNodeChild.nodeType !== 3){ oNodeChild = oPrevChild; continue; } if(nhn.husky.SE2M_Utils.isBlankTextNode(oNodeChild)){ oNodeChild.parentNode.removeChild(oNodeChild); } oNodeChild = oPrevChild; } elHtml = elUpperNode.innerHTML; if(elHtml === "" || elHtml.replace(unescape("%uFEFF"), '') === ""){ elUpperNode.innerHTML = unescape("%uFEFF"); } } // 엔터 후에 비어있는 하단 SPAN 노드에 BOM 추가 var oSelection = this.oApp.getSelection(), sBM, elLowerNode, elParent; if(!oSelection.collapsed){ return; } oSelection.fixCommonAncestorContainer(); elLowerNode = oSelection.commonAncestorContainer; if(!elLowerNode){ return; } elLowerNode = oSelection._getVeryFirstRealChild(elLowerNode); if(elLowerNode.nodeType === 3){ elLowerNode = elLowerNode.parentNode; } if(!elLowerNode || elLowerNode.tagName !== "SPAN"){ return; } elHtml = elLowerNode.innerHTML; if(elHtml === "" || elHtml.replace(unescape("%uFEFF"), '') === ""){ elLowerNode.innerHTML = unescape("%uFEFF"); } elParent = nhn.husky.SE2M_Utils.findAncestorByTagName("P", elLowerNode); oSelection.selectNodeContents(elLowerNode); sBM = oSelection.placeStringBookmark(); this._addSpace(elParent.previousSibling); // 상단 P 노드에 공백문자 추가 this._addSpace(elParent); // 하단 P 노드에 공백문자 추가 oSelection.moveToBookmark(sBM); oSelection.selectNodeContents(elLowerNode); oSelection.collapseToStart(); oSelection.select(); oSelection.removeStringBookmark(sBM); }, // [IE] P 태그 가장 뒤 자식노드로 공백(&nbsp;)을 값으로 하는 텍스트 노드를 추가 _addSpace : function(elNode){ var tmpTextNode, sInnerHTML, elChild, elNextChild, bHasNBSP, aImgChild, elLastImg; if(!elNode){ return; } if(elNode.nodeType === 3){ return elNode.parentNode; } if(elNode.tagName !== "P"){ return elNode; } aImgChild = jindo.$Element(elNode).child(function(v){ return (v.$value().nodeType === 1 && v.$value().tagName === "IMG"); }, 1); if(aImgChild.length > 0){ elLastImg = aImgChild[aImgChild.length - 1].$value(); elChild = elLastImg.nextSibling; while(elChild){ elNextChild = elChild.nextSibling; if (elChild.nodeType === 3 && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0"))) { elNode.removeChild(elChild); } elChild = elNextChild; } return elNode; } sInnerHTML = elNode.innerHTML; elChild = elNode.firstChild; elNextChild = elChild; bHasNBSP = false; while(elChild){ // &nbsp;를 붙일꺼니까 P 바로 아래의 "%uFEFF"는 제거함 elNextChild = elChild.nextSibling; if(elChild.nodeType === 3){ if(elChild.nodeValue === unescape("%uFEFF")){ elNode.removeChild(elChild); } if(!bHasNBSP && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0"))){ bHasNBSP = true; } } elChild = elNextChild; } if(!bHasNBSP){ tmpTextNode = this.tmpTextNode.cloneNode(); elNode.appendChild(tmpTextNode); } return elNode; // [SMARTEDITORSUS-418] return 엘리먼트 추가 }, // [IE] 엔터 후에 취소선/밑줄 태그를 임의로 추가 (취소선/밑줄에 색상을 표시하기 위함) _addTextDecorationTag : function(bAddUnderline, bAddLineThrough){ var oTargetNode, oNewNode, oSelection = this.oApp.getSelection(); if(!oSelection.collapsed){ return; } oTargetNode = oSelection.startContainer; while(oTargetNode){ if(oTargetNode.nodeType === 3){ oTargetNode = nhn.DOMFix.parentNode(oTargetNode); break; } if(!oTargetNode.childNodes || oTargetNode.childNodes.length === 0){ oTargetNode.innerHTML = unescape("%uFEFF"); break; } oTargetNode = oTargetNode.firstChild; } if(!oTargetNode){ return; } if(oTargetNode.tagName === "U" || oTargetNode.tagName === "S" || oTargetNode.tagName === "STRIKE"){ return; } var elStyleOnlyNode; if(oTargetNode.innerHTML == "" || (elStyleOnlyNode = this._getStyleOnlyNode(oTargetNode))){ this._addSpace(elStyleOnlyNode, oTargetNode); } if(bAddUnderline){ oNewNode = oSelection._document.createElement("U"); oTargetNode.appendChild(oNewNode); oTargetNode = oNewNode; } if(bAddLineThrough){ oNewNode = oSelection._document.createElement("STRIKE"); oTargetNode.appendChild(oNewNode); } oNewNode.innerHTML = unescape("%uFEFF"); oSelection.selectNodeContents(oNewNode); oSelection.collapseToEnd(); // End 로 해야 새로 생성된 노드 안으로 Selection 이 들어감 oSelection.select(); }, // [IE9 standard mode] _getStyleOnlyNode 에서 노드를 검색하 때 빈 노드가 있으면 BOM 추가 _addBlankTextAllSpan : function(elNode){ var aSpanList, nSpanLen, sInnerHtml, i; if(!elNode){ return; } aSpanList = jindo.$Element(elNode).child(function(v){ return (v.$value().nodeType === 1 && v.$value().tagName === "SPAN"); }); nSpanLen = aSpanList.length; for(i=0; i<nSpanLen; i++){ sInnerHtml = aSpanList[i].html(); if(sInnerHtml === ""){ aSpanList[i].html(unescape("%uFEFF")); } } }, // returns inner-most styling node // -> returns span3 from <span1><span2><span3>aaa</span></span></span> _getStyleNode : function(elNode){ while(elNode.firstChild && this.oSelection._isBlankTextNode(elNode.firstChild)){ elNode.removeChild(elNode.firstChild); } var elFirstChild = elNode.firstChild; if(!elFirstChild){ return elNode; } if(elFirstChild.nodeType === 3 || (elFirstChild.nodeType === 1 && (elFirstChild.tagName == "IMG" || elFirstChild.tagName == "BR" || elFirstChild.tagName == "HR" || elFirstChild.tagName == "IFRAME"))){ return elNode; } return this._getStyleNode(elNode.firstChild); }, // returns inner-most styling only node if there's any. // -> returns span3 from <span1><span2><span3></span></span></span> _getStyleOnlyNode : function(elNode){ if(!elNode){ return null; } // the final styling node must allow appending children // -> this doesn't seem to work for FF if(!elNode.insertBefore){ return null; } if(elNode.tagName == "IMG" || elNode.tagName == "BR" || elNode.tagName == "HR" || elNode.tagName == "IFRAME"){ return null; } while(elNode.firstChild && this.oSelection._isBlankTextNode(elNode.firstChild)){ elNode.removeChild(elNode.firstChild); } if(elNode.childNodes.length>1){ return null; } if(!elNode.firstChild){ return elNode; } // [SMARTEDITORSUS-227] TEXT_NODE 가 return 되는 문제를 수정함. IE 에서 TEXT_NODE 의 innrHTML 에 접근하면 오류 발생 if(elNode.firstChild.nodeType === 3){ return nhn.husky.SE2M_Utils.isBlankTextNode(elNode.firstChild) ? elNode : null; //return (elNode.firstChild.textContents === null || elNode.firstChild.textContents === "") ? elNode : null; } return this._getStyleOnlyNode(elNode.firstChild); }, _insertBR : function(oEvent){ oEvent.stop(); var oSelection = this.oApp.getSelection(); var elBR = this.oApp.getWYSIWYGDocument().createElement("BR"); oSelection.insertNode(elBR); oSelection.selectNode(elBR); oSelection.collapseToEnd(); if(!this.htBrowser.ie){ var oLineInfo = oSelection.getLineInfo(); var oEnd = oLineInfo.oEnd; // line break by Parent // <div> 1234<br></div>인경우, FF에서는 다음 라인으로 커서 이동이 안 일어남. // 그래서 <div> 1234<br><br type='_moz'/></div> 이와 같이 생성해주어야 에디터 상에 2줄로 되어 보임. if(oEnd.bParentBreak){ while(oEnd.oNode && oEnd.oNode.nodeType == 3 && oEnd.oNode.nodeValue == ""){ oEnd.oNode = oEnd.oNode.previousSibling; } var nTmp = 1; if(oEnd.oNode == elBR || oEnd.oNode.nextSibling == elBR){ nTmp = 0; } if(nTmp === 0){ oSelection.pasteHTML("<br type='_moz'/>"); oSelection.collapseToEnd(); } } } // the text cursor won't move to the next line without this oSelection.insertNode(this.oApp.getWYSIWYGDocument().createTextNode("")); oSelection.select(); } }); //}
JavaScript
/*[ * REFRESH_WYSIWYG * * (FF전용) WYSIWYG 모드를 비활성화 후 다시 활성화 시킨다. FF에서 WYSIWYG 모드가 일부 비활성화 되는 문제용 * 주의] REFRESH_WYSIWYG후에는 본문의 selection이 깨져서 커서 제일 앞으로 가는 현상이 있음. (stringbookmark로 처리해야함.) * * none * ---------------------------------------------------------------------------]*/ /*[ * ENABLE_WYSIWYG * * 비활성화된 WYSIWYG 편집 영역을 활성화 시킨다. * * none * ---------------------------------------------------------------------------]*/ /*[ * DISABLE_WYSIWYG * * WYSIWYG 편집 영역을 비활성화 시킨다. * * none * ---------------------------------------------------------------------------]*/ /*[ * PASTE_HTML * * HTML을 편집 영역에 삽입한다. * * sHTML string 삽입할 HTML * oPSelection object 붙여 넣기 할 영역, 생략시 현재 커서 위치 * ---------------------------------------------------------------------------]*/ /*[ * RESTORE_IE_SELECTION * * (IE전용) 에디터에서 포커스가 나가는 시점에 기억해둔 포커스를 복구한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc WYSIWYG 모드를 제공하는 플러그인 */ nhn.husky.SE_EditingArea_WYSIWYG = jindo.$Class({ name : "SE_EditingArea_WYSIWYG", status : nhn.husky.PLUGIN_STATUS.NOT_READY, sMode : "WYSIWYG", iframe : null, doc : null, bStopCheckingBodyHeight : false, bAutoResize : false, // [SMARTEDITORSUS-677] 해당 편집모드의 자동확장 기능 On/Off 여부 nBodyMinHeight : 0, nScrollbarWidth : 0, iLastUndoRecorded : 0, // iMinUndoInterval : 50, _nIFrameReadyCount : 50, bWYSIWYGEnabled : false, $init : function(iframe){ this.iframe = jindo.$(iframe); var oAgent = jindo.$Agent().navigator(); // IE에서 에디터 초기화 시에 임의적으로 iframe에 포커스를 반쯤(IME 입력 안되고 커서만 깜박이는 상태) 주는 현상을 막기 위해서 일단 iframe을 숨겨 뒀다가 CHANGE_EDITING_MODE에서 위지윅 전환 시 보여준다. // 이런 현상이 다양한 요소에 의해서 발생하며 발견된 몇가지 경우는, // - frameset으로 페이지를 구성한 후에 한개의 frame안에 버튼을 두어 에디터로 링크 할 경우 // - iframe과 동일 페이지에 존재하는 text field에 값을 할당 할 경우 if(oAgent.ie){ this.iframe.style.display = "none"; } // IE8 : 찾기/바꾸기에서 글자 일부에 스타일이 적용된 경우 찾기가 안되는 브라우저 버그로 인해 EmulateIE7 파일을 사용 // <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> this.sBlankPageURL = "smart_editor2_inputarea.html"; this.sBlankPageURL_EmulateIE7 = "smart_editor2_inputarea_ie8.html"; this.aAddtionalEmulateIE7 = []; this.htOptions = nhn.husky.SE2M_Configuration.SE_EditingAreaManager; if (this.htOptions) { this.sBlankPageURL = this.htOptions.sBlankPageURL || this.sBlankPageURL; this.sBlankPageURL_EmulateIE7 = this.htOptions.sBlankPageURL_EmulateIE7 || this.sBlankPageURL_EmulateIE7; this.aAddtionalEmulateIE7 = this.htOptions.aAddtionalEmulateIE7 || this.aAddtionalEmulateIE7; } this.aAddtionalEmulateIE7.push(8); // IE8은 Default 사용 this.sIFrameSrc = this.sBlankPageURL; if(oAgent.ie && jindo.$A(this.aAddtionalEmulateIE7).has(oAgent.nativeVersion)) { this.sIFrameSrc = this.sBlankPageURL_EmulateIE7; } this.iframe.src = this.sIFrameSrc; this.initIframe(); this.elEditingArea = iframe; }, $BEFORE_MSG_APP_READY : function(){ this.oEditingArea = this.iframe.contentWindow.document; this.oApp.exec("REGISTER_EDITING_AREA", [this]); this.oApp.exec("ADD_APP_PROPERTY", ["getWYSIWYGWindow", jindo.$Fn(this.getWindow, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getWYSIWYGDocument", jindo.$Fn(this.getDocument, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["isWYSIWYGEnabled", jindo.$Fn(this.isWYSIWYGEnabled, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getRawHTMLContents", jindo.$Fn(this.getRawHTMLContents, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["setRawHTMLContents", jindo.$Fn(this.setRawHTMLContents, this).bind()]); if (!!this.isWYSIWYGEnabled()) { this.oApp.exec('ENABLE_WYSIWYG_RULER', []); } this.oApp.registerBrowserEvent(this.getDocument().body, 'paste', 'EVENT_EDITING_AREA_PASTE'); }, $ON_MSG_APP_READY : function(){ if(!this.oApp.hasOwnProperty("saveSnapShot")){ this.$ON_EVENT_EDITING_AREA_MOUSEUP = function(){}; this._recordUndo = function(){}; } // uncomment this line if you wish to use the IE-style cursor in FF // this.getDocument().body.style.cursor = "text"; // Do not update this._oIERange until the document is actually clicked (focus was given by mousedown->mouseup) // Without this, iframe cannot be re-selected(by RESTORE_IE_SELECTION) if the document hasn't been clicked // mousedown on iframe -> focus goes into the iframe doc -> beforedeactivate is fired -> empty selection is saved by the plugin -> empty selection is recovered in RESTORE_IE_SELECTION this._bIERangeReset = true; if(jindo.$Agent().navigator().ie){ jindo.$Fn( function(weEvent){ if(this.iframe.contentWindow.document.selection.type.toLowerCase() === 'control' && weEvent.key().keyCode === 8){ this.oApp.exec("EXECCOMMAND", ['delete', false, false]); weEvent.stop(); } this._bIERangeReset = false; }, this ).attach(this.iframe.contentWindow.document, "keydown"); jindo.$Fn( function(weEvent){ this._oIERange = null; this._bIERangeReset = true; }, this ).attach(this.iframe.contentWindow.document.body, "mousedown"); jindo.$Fn(this._onIEBeforeDeactivate, this).attach(this.iframe.contentWindow.document.body, "beforedeactivate"); jindo.$Fn( function(weEvent){ this._bIERangeReset = false; }, this ).attach(this.iframe.contentWindow.document.body, "mouseup"); }else{ //this.getDocument().execCommand('useCSS', false, false); //this.getDocument().execCommand('styleWithCSS', false, false); //this.document.execCommand("insertBrOnReturn", false, false); } // DTD가 quirks가 아닐 경우 body 높이 100%가 제대로 동작하지 않아서 타임아웃을 돌며 높이를 수동으로 계속 할당 해 줌 // body 높이가 제대로 설정 되지 않을 경우, 보기에는 이상없어 보이나 마우스로 텍스트 선택이 잘 안된다든지 하는 이슈가 있음 this.fnSetBodyHeight = jindo.$Fn(this._setBodyHeight, this).bind(); this.fnCheckBodyChange = jindo.$Fn(this._checkBodyChange, this).bind(); this.fnSetBodyHeight(); this._setScrollbarWidth(); }, /** * 스크롤바의 사이즈 측정하여 설정 */ _setScrollbarWidth : function(){ var oDocument = this.getDocument(), elScrollDiv = oDocument.createElement("div"); elScrollDiv.style.width = "100px"; elScrollDiv.style.height = "100px"; elScrollDiv.style.overflow = "scroll"; elScrollDiv.style.position = "absolute"; elScrollDiv.style.top = "-9999px"; oDocument.body.appendChild(elScrollDiv); this.nScrollbarWidth = elScrollDiv.offsetWidth - elScrollDiv.clientWidth; oDocument.body.removeChild(elScrollDiv); }, /** * [SMARTEDITORSUS-677] 붙여넣기나 내용 입력에 대한 편집영역 자동 확장 처리 */ $AFTER_EVENT_EDITING_AREA_KEYUP : function(oEvent){ if(!this.bAutoResize){ return; } var oKeyInfo = oEvent.key(); if((oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40) || oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode === 16){ return; } this._setAutoResize(); }, /** * [SMARTEDITORSUS-677] 붙여넣기나 내용 입력에 대한 편집영역 자동 확장 처리 */ $AFTER_PASTE_HTML : function(){ if(!this.bAutoResize){ return; } this._setAutoResize(); }, /** * [SMARTEDITORSUS-677] WYSIWYG 편집 영역 자동 확장 처리 시작 */ startAutoResize : function(){ this.oApp.exec("STOP_CHECKING_BODY_HEIGHT"); this.bAutoResize = true; var oBrowser = this.oApp.oNavigator; // [SMARTEDITORSUS-887] [블로그 1단] 자동확장 모드에서 에디터 가로사이즈보다 큰 사진을 추가했을 때 가로스크롤이 안생기는 문제 if(oBrowser.ie && oBrowser.version < 9){ jindo.$Element(this.getDocument().body).css({ "overflow" : "visible" }); // { "overflowX" : "visible", "overflowY" : "hidden" } 으로 설정하면 세로 스크롤 뿐 아니라 가로 스크롤도 보이지 않는 문제가 있어 // { "overflow" : "visible" } 로 처리하고 에디터의 container 사이즈를 늘려 세로 스크롤이 보이지 않도록 처리해야 함 // [한계] 자동 확장 모드에서 내용이 늘어날 때 세로 스크롤이 보였다가 없어지는 문제 }else{ jindo.$Element(this.getDocument().body).css({ "overflowX" : "visible", "overflowY" : "hidden" }); } this._setAutoResize(); this.nCheckBodyInterval = setInterval(this.fnCheckBodyChange, 500); this.oApp.exec("START_FLOAT_TOOLBAR"); // set scroll event }, /** * [SMARTEDITORSUS-677] WYSIWYG 편집 영역 자동 확장 처리 종료 */ stopAutoResize : function(){ this.bAutoResize = false; clearInterval(this.nCheckBodyInterval); this.oApp.exec("STOP_FLOAT_TOOLBAR"); // remove scroll event jindo.$Element(this.getDocument().body).css({ "overflow" : "visible", "overflowY" : "visible" }); this.oApp.exec("START_CHECKING_BODY_HEIGHT"); }, /** * [SMARTEDITORSUS-677] 편집 영역 Body가 변경되었는지 주기적으로 확인 */ _checkBodyChange : function(){ if(!this.bAutoResize){ return; } var nBodyLength = this.getDocument().body.innerHTML.length; if(nBodyLength !== this.nBodyLength){ this.nBodyLength = nBodyLength; this._setAutoResize(); } }, /** * [SMARTEDITORSUS-677] 자동 확장 처리에서 적용할 Resize Body Height를 구함 */ _getResizeHeight : function(){ var elBody = this.getDocument().body, welBody, nBodyHeight, aCopyStyle = ['width', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'lineHeight', 'letterSpacing', 'textTransform', 'wordSpacing'], oCss, i; if(!this.oApp.oNavigator.firefox && !this.oApp.oNavigator.safari){ if(this.oApp.oNavigator.ie && this.oApp.oNavigator.version === 8 && document.documentMode === 8){ jindo.$Element(elBody).css("height", "0px"); } nBodyHeight = parseInt(elBody.scrollHeight, 10); if(nBodyHeight < this.nBodyMinHeight){ nBodyHeight = this.nBodyMinHeight; } return nBodyHeight; } // Firefox && Safari if(!this.elDummy){ this.elDummy = document.createElement('div'); this.elDummy.className = "se2_input_wysiwyg"; this.oApp.elEditingAreaContainer.appendChild(this.elDummy); this.elDummy.style.cssText = 'position:absolute !important; left:-9999px !important; top:-9999px !important; z-index: -9999 !important; overflow: auto !important;'; this.elDummy.style.height = this.nBodyMinHeight + "px"; } welBody = jindo.$Element(elBody); i = aCopyStyle.length; oCss = {}; while(i--){ oCss[aCopyStyle[i]] = welBody.css(aCopyStyle[i]); } if(oCss.lineHeight.indexOf("px") > -1){ oCss.lineHeight = (parseInt(oCss.lineHeight, 10)/parseInt(oCss.fontSize, 10)); } jindo.$Element(this.elDummy).css(oCss); this.elDummy.innerHTML = elBody.innerHTML; nBodyHeight = this.elDummy.scrollHeight; return nBodyHeight; }, /** * [SMARTEDITORSUS-677] WYSIWYG 자동 확장 처리 */ _setAutoResize : function(){ var elBody = this.getDocument().body, welBody = jindo.$Element(elBody), nBodyHeight, nContainerHeight, oCurrentStyle, nStyleSize, bExpand = false, oBrowser = this.oApp.oNavigator; this.nTopBottomMargin = this.nTopBottomMargin || (parseInt(welBody.css("marginTop"), 10) + parseInt(welBody.css("marginBottom"), 10)); this.nBodyMinHeight = this.nBodyMinHeight || (this.oApp.getEditingAreaHeight() - this.nTopBottomMargin); if((oBrowser.ie && oBrowser.nativeVersion >= 9) || oBrowser.chrome){ // 내용이 줄어도 scrollHeight가 줄어들지 않음 welBody.css("height", "0px"); this.iframe.style.height = "0px"; } nBodyHeight = this._getResizeHeight(); if(oBrowser.ie){ // 내용 뒤로 공간이 남아 보일 수 있으나 추가로 Container높이를 더하지 않으면 // 내용 가장 뒤에서 Enter를 하는 경우 아래위로 흔들려 보이는 문제가 발생 if(nBodyHeight > this.nBodyMinHeight){ oCurrentStyle = this.oApp.getCurrentStyle(); nStyleSize = parseInt(oCurrentStyle.fontSize, 10) * oCurrentStyle.lineHeight; if(nStyleSize < this.nTopBottomMargin){ nStyleSize = this.nTopBottomMargin; } nContainerHeight = nBodyHeight + nStyleSize; nContainerHeight += 18; bExpand = true; }else{ nBodyHeight = this.nBodyMinHeight; nContainerHeight = this.nBodyMinHeight + this.nTopBottomMargin; } // }else if(oBrowser.safari){ // -- 사파리에서 내용이 줄어들지 않는 문제가 있어 Firefox 방식으로 변경함 // // [Chrome/Safari] 크롬이나 사파리에서는 Body와 iframe높이서 서로 연관되어 늘어나므로, // // nContainerHeight를 추가로 더하는 경우 setTimeout 시 무한 증식되는 문제가 발생할 수 있음 // nBodyHeight = nBodyHeight > this.nBodyMinHeight ? nBodyHeight - this.nTopBottomMargin : this.nBodyMinHeight; // nContainerHeight = nBodyHeight + this.nTopBottomMargin; }else{ // [FF] nContainerHeight를 추가로 더하였음. setTimeout 시 무한 증식되는 문제가 발생할 수 있음 if(nBodyHeight > this.nBodyMinHeight){ oCurrentStyle = this.oApp.getCurrentStyle(); nStyleSize = parseInt(oCurrentStyle.fontSize, 10) * oCurrentStyle.lineHeight; if(nStyleSize < this.nTopBottomMargin){ nStyleSize = this.nTopBottomMargin; } nContainerHeight = nBodyHeight + nStyleSize; bExpand = true; }else{ nBodyHeight = this.nBodyMinHeight; nContainerHeight = this.nBodyMinHeight + this.nTopBottomMargin; } } if(!oBrowser.firefox){ welBody.css("height", nBodyHeight + "px"); } this.iframe.style.height = nContainerHeight + "px"; // 편집영역 IFRAME의 높이 변경 this.oApp.welEditingAreaContainer.height(nContainerHeight); // 편집영역 IFRAME을 감싸는 DIV 높이 변경 this.oApp.checkResizeGripPosition(bExpand); }, /** * 스크롤 처리를 위해 편집영역 Body의 사이즈를 확인하고 설정함 * 편집영역 자동확장 기능이 Off인 경우에 주기적으로 실행됨 */ _setBodyHeight : function(){ if( this.bStopCheckingBodyHeight ){ // 멈춰야 하는 경우 true, 계속 체크해야 하면 false // 위지윅 모드에서 다른 모드로 변경할 때 "document는 css를 사용 할수 없습니다." 라는 error 가 발생. // 그래서 on_change_mode에서 bStopCheckingBodyHeight 를 true로 변경시켜줘야 함. return; } var elBody = this.getDocument().body, welBody = jindo.$Element(elBody), nMarginTopBottom = parseInt(welBody.css("marginTop"), 10) + parseInt(welBody.css("marginBottom"), 10), nContainerOffset = this.oApp.getEditingAreaHeight(), nMinBodyHeight = nContainerOffset - nMarginTopBottom, nBodyHeight = welBody.height(), nScrollHeight, nNewBodyHeight; this.nTopBottomMargin = nMarginTopBottom; if(nBodyHeight === 0){ // [SMARTEDITORSUS-144] height 가 0 이고 내용이 없으면 크롬10 에서 캐럿이 보이지 않음 welBody.css("height", nMinBodyHeight + "px"); setTimeout(this.fnSetBodyHeight, 500); return; } welBody.css("height", "0px"); // [SMARTEDITORSUS-257] IE9, 크롬에서 내용을 삭제해도 스크롤이 남아있는 문제 처리 // body 에 내용이 없어져도 scrollHeight 가 줄어들지 않아 height 를 강제로 0 으로 설정 nScrollHeight = parseInt(elBody.scrollHeight, 10); nNewBodyHeight = (nScrollHeight > nContainerOffset ? nScrollHeight - nMarginTopBottom : nMinBodyHeight); // nMarginTopBottom 을 빼지 않으면 스크롤이 계속 늘어나는 경우가 있음 (참고 [BLOGSUS-17421]) if(this._isHorizontalScrollbarVisible()){ nNewBodyHeight -= this.nScrollbarWidth; } welBody.css("height", nNewBodyHeight + "px"); setTimeout(this.fnSetBodyHeight, 500); }, /** * 가로 스크롤바 생성 확인 */ _isHorizontalScrollbarVisible : function(){ var oDocument = this.getDocument(); if(oDocument.documentElement.clientWidth < oDocument.documentElement.scrollWidth){ //oDocument.body.clientWidth < oDocument.body.scrollWidth || return true; } return false; }, /** * body의 offset체크를 멈추게 하는 함수. */ $ON_STOP_CHECKING_BODY_HEIGHT :function(){ if(!this.bStopCheckingBodyHeight){ this.bStopCheckingBodyHeight = true; } }, /** * body의 offset체크를 계속 진행. */ $ON_START_CHECKING_BODY_HEIGHT :function(){ if(this.bStopCheckingBodyHeight){ this.bStopCheckingBodyHeight = false; this.fnSetBodyHeight(); } }, $ON_IE_CHECK_EXCEPTION_FOR_SELECTION_PRESERVATION : function(){ // 현재 선택된 앨리먼트가 iframe이라면, 셀렉션을 따로 기억 해 두지 않아도 유지 됨으로 RESTORE_IE_SELECTION을 타지 않도록 this._oIERange을 지워준다. // (필요 없을 뿐더러 저장 시 문제 발생) if(this.getDocument().selection.type === "Control"){ this._oIERange = null; } /* // [SMARTEDITORSUS-978] HuskyRange.js 의 [SMARTEDITORSUS-888] 이슈 수정과 관련 var tmpSelection = this.getDocument().selection, oRange, elNode; if(tmpSelection.type === "Control"){ oRange = tmpSelection.createRange(); elNode = oRange.item(0); if(elNode && elNode.tagName === "IFRAME"){ this._oIERange = null; } } */ }, _onIEBeforeDeactivate : function(wev){ var tmpSelection, tmpRange; this.oApp.delayedExec("IE_CHECK_EXCEPTION_FOR_SELECTION_PRESERVATION", [], 0); if(this._oIERange){ return; } // without this, cursor won't make it inside a table. // mousedown(_oIERange gets reset) -> beforedeactivate(gets fired for table) -> RESTORE_IE_SELECTION if(this._bIERangeReset){ return; } this._oIERange = this.oApp.getSelection().cloneRange(); /* [SMARTEDITORSUS-978] HuskyRange.js 의 [SMARTEDITORSUS-888] 이슈 수정과 관련 tmpSelection = this.getDocument().selection; tmpRange = tmpSelection.createRange(); // Control range does not have parentElement if(tmpRange.parentElement && tmpRange.parentElement() && tmpRange.parentElement().tagName === "INPUT"){ this._oIERange = this._oPrevIERange; }else{ this._oIERange = tmpRange; } */ }, $ON_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ if(sMode === this.sMode){ this.iframe.style.display = "block"; this.oApp.exec("REFRESH_WYSIWYG", []); this.oApp.exec("SET_EDITING_WINDOW", [this.getWindow()]); this.oApp.exec("START_CHECKING_BODY_HEIGHT"); }else{ this.iframe.style.display = "none"; this.oApp.exec("STOP_CHECKING_BODY_HEIGHT"); } }, $AFTER_CHANGE_EDITING_MODE : function(sMode, bNoFocus){ this._oIERange = null; }, $ON_REFRESH_WYSIWYG : function(){ if(!jindo.$Agent().navigator().firefox){ return; } this._disableWYSIWYG(); this._enableWYSIWYG(); }, $ON_ENABLE_WYSIWYG : function(){ this._enableWYSIWYG(); }, $ON_DISABLE_WYSIWYG : function(){ this._disableWYSIWYG(); }, $ON_IE_HIDE_CURSOR : function(){ if(!this.oApp.oNavigator.ie){ return; } this._onIEBeforeDeactivate(); // De-select the default selection. // [SMARTEDITORSUS-978] IE9에서 removeAllRanges로 제거되지 않아 // 이전 IE와 동일하게 empty 방식을 사용하도록 하였으나 doc.selection.type이 None인 경우 에러 // Range를 재설정 해주어 selectNone 으로 처리되도록 예외처리 if(this.oApp.getWYSIWYGDocument().selection.createRange){ try{ this.oApp.getWYSIWYGDocument().selection.empty(); }catch(e){ // [SMARTEDITORSUS-1003] IE9 / doc.selection.type === "None" var oSelection = this.oApp.getSelection(); oSelection.select(); oSelection.oBrowserSelection.selectNone(); } }else{ this.oApp.getEmptySelection().oBrowserSelection.selectNone(); } }, $AFTER_SHOW_ACTIVE_LAYER : function(){ this.oApp.exec("IE_HIDE_CURSOR",[]); this.bActiveLayerShown = true; }, $BEFORE_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ this._bKeyDown = true; }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ if(this.oApp.getEditingMode() !== this.sMode){ return; } var oKeyInfo = oEvent.key(); if(this.oApp.oNavigator.ie){ //var oKeyInfo = oEvent.key(); switch(oKeyInfo.keyCode){ case 33: this._pageUp(oEvent); break; case 34: this._pageDown(oEvent); break; case 8: // [SMARTEDITORSUS-495][SMARTEDITORSUS-548] IE에서 표가 삭제되지 않는 문제 this._backspaceTable(oEvent); break; default: } }else if(this.oApp.oNavigator.firefox){ // [SMARTEDITORSUS-151] FF 에서 표가 삭제되지 않는 문제 if(oKeyInfo.keyCode === 8){ // backspace this._backspaceTable(oEvent); } } this._recordUndo(oKeyInfo); // 첫번째 Delete 키 입력 전의 상태가 저장되도록 KEYDOWN 시점에 저장 }, _backspaceTable : function(weEvent){ var oSelection = this.oApp.getSelection(), preNode = null; if(!oSelection.collapsed){ return; } preNode = oSelection.getNodeAroundRange(true, false); if(preNode && preNode.nodeType === 3 && /^[\n]*$/.test(preNode.nodeValue)){ preNode = preNode.previousSibling; } if(!!preNode && preNode.nodeType === 1 && preNode.tagName === "TABLE"){ jindo.$Element(preNode).leave(); weEvent.stop(jindo.$Event.CANCEL_ALL); } }, $BEFORE_EVENT_EDITING_AREA_KEYUP : function(oEvent){ // IE(6) sometimes fires keyup events when it should not and when it happens the keyup event gets fired without a keydown event if(!this._bKeyDown){ return false; } this._bKeyDown = false; }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(oEvent){ this.oApp.saveSnapShot(); }, $BEFORE_PASTE_HTML : function(){ if(this.oApp.getEditingMode() !== this.sMode){ this.oApp.exec("CHANGE_EDITING_MODE", [this.sMode]); } }, $ON_PASTE_HTML : function(sHTML, oPSelection, bNoUndo){ var oSelection, oNavigator, sTmpBookmark, oStartContainer, aImgChild, elLastImg, elChild, elNextChild; if(this.oApp.getEditingMode() !== this.sMode){ return; } if(!bNoUndo){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["PASTE HTML"]); } oNavigator = jindo.$Agent().navigator(); oSelection = oPSelection || this.oApp.getSelection(); //[SMARTEDITORSUS-888] 브라우저 별 테스트 후 아래 부분이 불필요하여 제거함 // - [SMARTEDITORSUS-387] IE9 표준모드에서 엘리먼트 뒤에 어떠한 엘리먼트도 없는 상태에서 커서가 안들어가는 현상. // if(oNavigator.ie && oNavigator.nativeVersion >= 9 && document.documentMode >= 9){ // sHTML = sHTML + unescape("%uFEFF"); // } if(oNavigator.ie && oNavigator.nativeVersion == 8 && document.documentMode == 8){ sHTML = sHTML + unescape("%uFEFF"); } oSelection.pasteHTML(sHTML); // every browser except for IE may modify the innerHTML when it is inserted if(!oNavigator.ie){ sTmpBookmark = oSelection.placeStringBookmark(); this.oApp.getWYSIWYGDocument().body.innerHTML = this.oApp.getWYSIWYGDocument().body.innerHTML; oSelection.moveToBookmark(sTmpBookmark); oSelection.collapseToEnd(); oSelection.select(); oSelection.removeStringBookmark(sTmpBookmark); // [SMARTEDITORSUS-56] 사진을 연속으로 첨부할 경우 연이어 삽입되지 않는 현상으로 이슈를 발견하게 되었습니다. // 그러나 이는 비단 '다수의 사진을 첨부할 경우'에만 발생하는 문제는 아니었고, // 원인 확인 결과 컨텐츠 삽입 후 기존 Bookmark 삭제 시 갱신된 Selection 이 제대로 반영되지 않는 점이 있었습니다. // 이에, Selection 을 갱신하는 코드를 추가하였습니다. oSelection = this.oApp.getSelection(); //[SMARTEDITORSUS-831] 비IE 계열 브라우저에서 스크롤바가 생기게 문자입력 후 엔터 클릭하지 않은 상태에서 //이미지 하나 삽입 시 이미지에 포커싱이 놓이지 않습니다. //원인 : parameter로 넘겨 받은 oPSelecion에 변경된 값을 복사해 주지 않아서 발생 //해결 : parameter로 넘겨 받은 oPSelecion에 변경된 값을 복사해준다 // call by reference로 넘겨 받았으므로 직접 객체 안의 인자 값을 바꿔주는 setRange 함수 사용 if(!!oPSelection){ oPSelection.setRange(oSelection); } }else{ // [SMARTEDITORSUS-428] [IE9.0] IE9에서 포스트 쓰기에 접근하여 맨위에 임의의 글감 첨부 후 엔터를 클릭 시 글감이 사라짐 // PASTE_HTML 후에 IFRAME 부분이 선택된 상태여서 Enter 시 내용이 제거되어 발생한 문제 oSelection.collapseToEnd(); oSelection.select(); this._oIERange = null; this._bIERangeReset = false; } // [SMARTEDITORSUS-639] 사진 첨부 후 이미지 뒤의 공백으로 인해 스크롤이 생기는 문제 if(sHTML.indexOf("<img") > -1){ oStartContainer = oSelection.startContainer; if(oStartContainer.nodeType === 1 && oStartContainer.tagName === "P"){ aImgChild = jindo.$Element(oStartContainer).child(function(v){ return (v.$value().nodeType === 1 && v.$value().tagName === "IMG"); }, 1); if(aImgChild.length > 0){ elLastImg = aImgChild[aImgChild.length - 1].$value(); elChild = elLastImg.nextSibling; while(elChild){ elNextChild = elChild.nextSibling; if (elChild.nodeType === 3 && (elChild.nodeValue === "&nbsp;" || elChild.nodeValue === unescape("%u00A0"))) { oStartContainer.removeChild(elChild); } elChild = elNextChild; } } } } if(!bNoUndo){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["PASTE HTML"]); } }, /** * [SMARTEDITORSUS-344]사진/동영상/지도 연속첨부시 포커싱 개선이슈로 추가되 함수. */ $ON_FOCUS_N_CURSOR : function (bEndCursor, sId){ //지도 추가 후 포커싱을 주기 위해서 bEndCursor = bEndCursor || true; var oSelection = this.oApp.getSelection(); if(jindo.$Agent().navigator().ie && !oSelection.collapsed){ if(bEndCursor){ oSelection.collapseToEnd(); } else { oSelection.collapseToStart(); } oSelection.select(); }else if(!!oSelection.collapsed && !sId) { this.oApp.exec("FOCUS"); }else if(!!sId){ setTimeout(jindo.$Fn(function(el){ this._scrollIntoView(el); this.oApp.exec("FOCUS"); }, this).bind(this.getDocument().getElementById(sId)), 300); } }, /* * 엘리먼트의 top, bottom 값을 반환 */ _getElementVerticalPosition : function(el){ var nTop = 0, elParent = el, htPos = {nTop : 0, nBottom : 0}; if(!el){ return htPos; } while(elParent) { nTop += elParent.offsetTop; elParent = elParent.offsetParent; } htPos.nTop = nTop; htPos.nBottom = nTop + jindo.$Element(el).height(); return htPos; }, /* * Window에서 현재 보여지는 영역의 top, bottom 값을 반환 */ _getVisibleVerticalPosition : function(){ var oWindow, oDocument, nVisibleHeight, htPos = {nTop : 0, nBottom : 0}; oWindow = this.getWindow(); oDocument = this.getDocument(); nVisibleHeight = oWindow.innerHeight ? oWindow.innerHeight : oDocument.documentElement.clientHeight || oDocument.body.clientHeight; htPos.nTop = oWindow.pageYOffset || oDocument.documentElement.scrollTop; htPos.nBottom = htPos.nTop + nVisibleHeight; return htPos; }, /* * 엘리먼트가 WYSIWYG Window의 Visible 부분에서 완전히 보이는 상태인지 확인 (일부만 보이면 false) */ _isElementVisible : function(htElementPos, htVisiblePos){ return (htElementPos.nTop >= htVisiblePos.nTop && htElementPos.nBottom <= htVisiblePos.nBottom); }, /* * [SMARTEDITORSUS-824] [SMARTEDITORSUS-828] 자동 스크롤 처리 */ _scrollIntoView : function(el){ var htElementPos = this._getElementVerticalPosition(el), htVisiblePos = this._getVisibleVerticalPosition(), nScroll = 0; if(this._isElementVisible(htElementPos, htVisiblePos)){ return; } if((nScroll = htElementPos.nBottom - htVisiblePos.nBottom) > 0){ this.getWindow().scrollTo(0, htVisiblePos.nTop + nScroll); // Scroll Down return; } this.getWindow().scrollTo(0, htElementPos.nTop); // Scroll Up }, $BEFORE_MSG_EDITING_AREA_RESIZE_STARTED : function(){ // FF에서 Height조정 시에 본문의 _fitElementInEditingArea()함수 부분에서 selection이 깨지는 현상을 잡기 위해서 // StringBookmark를 사용해서 위치를 저장해둠. (step1) if(!jindo.$Agent().navigator().ie){ var oSelection = null; oSelection = this.oApp.getSelection(); this.sBM = oSelection.placeStringBookmark(); } }, $AFTER_MSG_EDITING_AREA_RESIZE_ENDED : function(FnMouseDown, FnMouseMove, FnMouseUp){ if(this.oApp.getEditingMode() !== this.sMode){ return; } this.oApp.exec("REFRESH_WYSIWYG", []); // bts.nhncorp.com/nhnbts/browse/COM-1042 // $BEFORE_MSG_EDITING_AREA_RESIZE_STARTED에서 저장한 StringBookmark를 셋팅해주고 삭제함.(step2) if(!jindo.$Agent().navigator().ie){ var oSelection = this.oApp.getEmptySelection(); oSelection.moveToBookmark(this.sBM); oSelection.select(); oSelection.removeStringBookmark(this.sBM); } }, $ON_CLEAR_IE_BACKUP_SELECTION : function(){ this._oIERange = null; }, $ON_RESTORE_IE_SELECTION : function(){ if(this._oIERange){ // changing the visibility of the iframe can cause an exception try{ this._oIERange.select(); this._oPrevIERange = this._oIERange; this._oIERange = null; }catch(e){} } }, /** * EVENT_EDITING_AREA_PASTE 의 ON 메시지 핸들러 * 위지윅 모드에서 에디터 본문의 paste 이벤트에 대한 메시지를 처리한다. * paste 시에 내용이 붙여진 본문의 내용을 바로 가져올 수 없어 delay 를 준다. */ $ON_EVENT_EDITING_AREA_PASTE : function(oEvent){ this.oApp.delayedExec('EVENT_EDITING_AREA_PASTE_DELAY', [oEvent], 0); }, $ON_EVENT_EDITING_AREA_PASTE_DELAY : function(weEvent) { this._replaceBlankToNbsp(weEvent.element); }, // [SMARTEDITORSUS-855] IE에서 특정 블로그 글을 복사하여 붙여넣기 했을 때 개행이 제거되는 문제 _replaceBlankToNbsp : function(el){ var oNavigator = this.oApp.oNavigator; if(!oNavigator.ie){ return; } if(oNavigator.nativeVersion !== 9 || document.documentMode !== 7) { // IE9 호환모드에서만 발생 return; } if(el.nodeType !== 1){ return; } if(el.tagName === "BR"){ return; } var aEl = jindo.$$("p:empty()", this.oApp.getWYSIWYGDocument().body, { oneTimeOffCache:true }); jindo.$A(aEl).forEach(function(value, index, array) { value.innerHTML = "&nbsp;"; }); }, _pageUp : function(we){ var nEditorHeight = this._getEditorHeight(), htPos = jindo.$Document(this.oApp.getWYSIWYGDocument()).scrollPosition(), nNewTop; if(htPos.top <= nEditorHeight){ nNewTop = 0; }else{ nNewTop = htPos.top - nEditorHeight; } this.oApp.getWYSIWYGWindow().scrollTo(0, nNewTop); we.stop(); }, _pageDown : function(we){ var nEditorHeight = this._getEditorHeight(), htPos = jindo.$Document(this.oApp.getWYSIWYGDocument()).scrollPosition(), nBodyHeight = this._getBodyHeight(), nNewTop; if(htPos.top+nEditorHeight >= nBodyHeight){ nNewTop = nBodyHeight - nEditorHeight; }else{ nNewTop = htPos.top + nEditorHeight; } this.oApp.getWYSIWYGWindow().scrollTo(0, nNewTop); we.stop(); }, _getEditorHeight : function(){ return this.oApp.elEditingAreaContainer.offsetHeight - this.nTopBottomMargin; }, _getBodyHeight : function(){ return parseInt(this.getDocument().body.scrollHeight, 10); }, tidyNbsp : function(){ var i, pNodes; if(!this.oApp.oNavigator.ie) { return; } pNodes = this.oApp.getWYSIWYGDocument().body.getElementsByTagName("P"); for(i=0; i<pNodes.length; i++){ if(pNodes[i].childNodes.length === 1 && pNodes[i].innerHTML === "&nbsp;"){ pNodes[i].innerHTML = ''; } } }, initIframe : function(){ try { if (!this.iframe.contentWindow.document || !this.iframe.contentWindow.document.body || this.iframe.contentWindow.document.location.href === 'about:blank'){ throw new Error('Access denied'); } this._enableWYSIWYG(); this.status = nhn.husky.PLUGIN_STATUS.READY; } catch(e) { if(this._nIFrameReadyCount-- > 0){ setTimeout(jindo.$Fn(this.initIframe, this).bind(), 100); }else{ throw("iframe for WYSIWYG editing mode can't be initialized. Please check if the iframe document exists and is also accessable(cross-domain issues). "); } } }, getIR : function(){ var sContent = this.iframe.contentWindow.document.body.innerHTML, sIR; if(this.oApp.applyConverter){ sIR = this.oApp.applyConverter(this.sMode+"_TO_IR", sContent, this.oApp.getWYSIWYGDocument()); }else{ sIR = sContent; } return sIR; }, setIR : function(sIR){ var sContent, oNavigator = jindo.$Agent().navigator(); if(this.oApp.applyConverter){ sContent = this.oApp.applyConverter("IR_TO_"+this.sMode, sIR, this.oApp.getWYSIWYGDocument()); }else{ sContent = sIR; } if(oNavigator.ie && oNavigator.nativeVersion >= 9 && document.documentMode >= 9){ // [SMARTEDITORSUS-704] \r\n이 있는 경우 IE9 표준모드에서 정렬 시 브라우저가 <p>를 추가하는 문제 sContent = sContent.replace(/[\r\n]/g,""); } this.iframe.contentWindow.document.body.innerHTML = sContent; if(!oNavigator.ie){ if((this.iframe.contentWindow.document.body.innerHTML).replace(/[\r\n\t\s]*/,"") === ""){ this.iframe.contentWindow.document.body.innerHTML = "<br>"; } }else{ if(this.oApp.getEditingMode() === this.sMode){ this.tidyNbsp(); } } }, getRawContents : function(){ return this.iframe.contentWindow.document.body.innerHTML; }, getRawHTMLContents : function(){ return this.getRawContents(); }, setRawHTMLContents : function(sContents){ this.iframe.contentWindow.document.body.innerHTML = sContents; }, getWindow : function(){ return this.iframe.contentWindow; }, getDocument : function(){ return this.iframe.contentWindow.document; }, focus : function(){ //this.getWindow().focus(); this.getDocument().body.focus(); this.oApp.exec("RESTORE_IE_SELECTION", []); }, _recordUndo : function(oKeyInfo){ /** * 229: Korean/Eng * 16: shift * 33,34: page up/down * 35,36: end/home * 37,38,39,40: left, up, right, down * 32: space * 46: delete * 8: bksp */ if(oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40){ // record snapshot this.oApp.saveSnapShot(); return; } if(oKeyInfo.alt || oKeyInfo.ctrl || oKeyInfo.keyCode === 16){ return; } if(this.oApp.getLastKey() === oKeyInfo.keyCode){ return; } this.oApp.setLastKey(oKeyInfo.keyCode); // && oKeyInfo.keyCode != 32 // 속도 문제로 인하여 Space 는 제외함 if(!oKeyInfo.enter && oKeyInfo.keyCode !== 46 && oKeyInfo.keyCode !== 8){ return; } this.oApp.exec("RECORD_UNDO_ACTION", ["KEYPRESS(" + oKeyInfo.keyCode + ")", {bMustBlockContainer:true}]); }, _enableWYSIWYG : function(){ //if (this.iframe.contentWindow.document.body.hasOwnProperty("contentEditable")){ if (this.iframe.contentWindow.document.body.contentEditable !== null) { this.iframe.contentWindow.document.body.contentEditable = true; } else { this.iframe.contentWindow.document.designMode = "on"; } this.bWYSIWYGEnabled = true; if(jindo.$Agent().navigator().firefox){ setTimeout(jindo.$Fn(function(){ //enableInlineTableEditing : Enables or disables the table row and column insertion and deletion controls. this.iframe.contentWindow.document.execCommand('enableInlineTableEditing', false, false); }, this).bind(), 0); } }, _disableWYSIWYG : function(){ //if (this.iframe.contentWindow.document.body.hasOwnProperty("contentEditable")){ if (this.iframe.contentWindow.document.body.contentEditable !== null){ this.iframe.contentWindow.document.body.contentEditable = false; } else { this.iframe.contentWindow.document.designMode = "off"; } this.bWYSIWYGEnabled = false; }, isWYSIWYGEnabled : function(){ return this.bWYSIWYGEnabled; } }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to resizing the editing area vertically * @name hp_SE_EditingAreaVerticalResizer.js */ nhn.husky.SE_EditingAreaVerticalResizer = jindo.$Class({ name : "SE_EditingAreaVerticalResizer", oResizeGrip : null, sCookieNotice : "bHideResizeNotice", nEditingAreaMinHeight : null, // [SMARTEDITORSUS-677] 편집 영역의 최소 높이 $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, $ON_MSG_APP_READY : function(){ this.$FnMouseDown = jindo.$Fn(this._mousedown, this); this.$FnMouseMove = jindo.$Fn(this._mousemove, this); this.$FnMouseUp = jindo.$Fn(this._mouseup, this); this.$FnMouseOver = jindo.$Fn(this._mouseover, this); this.$FnMouseOut = jindo.$Fn(this._mouseout, this); this.$FnMouseDown.attach(this.oResizeGrip, "mousedown"); this.$FnMouseOver.attach(this.oResizeGrip, "mouseover"); this.$FnMouseOut.attach(this.oResizeGrip, "mouseout"); jindo.$Fn(this._closeNotice, this).attach(this.elCloseLayerBtn, "click"); this.oApp.exec("REGISTER_HOTKEY", ["shift+esc", "FOCUS_RESIZER"]); this.oApp.exec("ADD_APP_PROPERTY", ["checkResizeGripPosition", jindo.$Fn(this.checkResizeGripPosition, this).bind()]); // [SMARTEDITORSUS-677] if(!!this.welNoticeLayer && !Number(jindo.$Cookie().get(this.sCookieNotice))){ this.welNoticeLayer.show(); } if(!!this.oApp.getEditingAreaHeight){ this.nEditingAreaMinHeight = this.oApp.getEditingAreaHeight(); // [SMARTEDITORSUS-677] 편집 영역의 최소 높이를 가져와 Gap 처리 시 사용 } }, /** * [SMARTEDITORSUS-677] [에디터 자동확장 ON인 경우] * 입력창 크기 조절 바의 위치를 확인하여 브라우저 하단에 위치한 경우 자동확장을 멈춤 */ checkResizeGripPosition : function(bExpand){ var oDocument = jindo.$Document(); var nGap = (jindo.$Element(this.oResizeGrip).offset().top - oDocument.scrollPosition().top + 25) - oDocument.clientSize().height; if(nGap <= 0){ return; } if(bExpand){ if(this.nEditingAreaMinHeight > this.oApp.getEditingAreaHeight() - nGap){ // [SMARTEDITORSUS-822] 수정 모드인 경우에 대비 nGap = (-1) * (this.nEditingAreaMinHeight - this.oApp.getEditingAreaHeight()); } // Gap 만큼 편집영역 사이즈를 조절하여 // 사진 첨부나 붙여넣기 등의 사이즈가 큰 내용 추가가 있었을 때 입력창 크기 조절 바가 숨겨지지 않도록 함 this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED"); this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, (-1) * nGap]); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED"); } this.oApp.exec("STOP_AUTORESIZE_EDITING_AREA"); }, $ON_FOCUS_RESIZER : function(){ this.oApp.exec("IE_HIDE_CURSOR"); this.oResizeGrip.focus(); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.oResizeGrip = jindo.$$.getSingle("BUTTON.husky_seditor_editingArea_verticalResizer", elAppContainer); this.elNoticeLayer = jindo.$$.getSingle("DIV.husky_seditor_resize_notice", elAppContainer); //@ec] this.welConversionMode = jindo.$Element(this.oResizeGrip.parentNode); if(!!this.elNoticeLayer){ this.welNoticeLayer = jindo.$Element(this.elNoticeLayer); this.elCloseLayerBtn = jindo.$$.getSingle("BUTTON.bt_clse", this.elNoticeLayer); } }, _mouseover : function(oEvent){ oEvent.stopBubble(); this.welConversionMode.addClass("controller_on"); }, _mouseout : function(oEvent){ oEvent.stopBubble(); this.welConversionMode.removeClass("controller_on"); }, _mousedown : function(oEvent){ this.iStartHeight = oEvent.pos().clientY; this.iStartHeightOffset = oEvent.pos().layerY; this.$FnMouseMove.attach(document, "mousemove"); this.$FnMouseUp.attach(document, "mouseup"); this.iStartHeight = oEvent.pos().clientY; this.oApp.exec("HIDE_ACTIVE_LAYER"); this.oApp.exec("HIDE_ALL_DIALOG_LAYER"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_STARTED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _mousemove : function(oEvent){ var iHeightChange = oEvent.pos().clientY - this.iStartHeight; this.oApp.exec("RESIZE_EDITING_AREA_BY", [0, iHeightChange]); }, _mouseup : function(oEvent){ this.$FnMouseMove.detach(document, "mousemove"); this.$FnMouseUp.detach(document, "mouseup"); this.oApp.exec("MSG_EDITING_AREA_RESIZE_ENDED", [this.$FnMouseDown, this.$FnMouseMove, this.$FnMouseUp]); }, _closeNotice : function(){ this.welNoticeLayer.hide(); jindo.$Cookie().set(this.sCookieNotice, 1, 365*10); } }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of changing the background color * @name hp_SE2M_BGColor.js */ nhn.husky.SE2M_BGColor = jindo.$Class({ name : "SE2M_BGColor", rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elLastUsed = jindo.$$.getSingle("BUTTON.husky_se2m_BGColor_lastUsed", elAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_BGColor_layer", elAppContainer); this.elBGColorList = jindo.$$.getSingle("UL.husky_se2m_bgcolor_list", elAppContainer); this.elPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_BGColor_paletteHolder", this.elDropdownLayer); //@ec] this._setLastUsedBGColor("#777777"); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["BGColorA", "click", "APPLY_LAST_USED_BGCOLOR"]); this.oApp.exec("REGISTER_UI_EVENT", ["BGColorB", "click", "TOGGLE_BGCOLOR_LAYER"]); this.oApp.registerBrowserEvent(this.elBGColorList, "click", "EVENT_APPLY_BGCOLOR", []); }, //@lazyload_js APPLY_LAST_USED_BGCOLOR,TOGGLE_BGCOLOR_LAYER[ $ON_TOGGLE_BGCOLOR_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "BGCOLOR_LAYER_SHOWN", [], "BGCOLOR_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['bgcolor']); }, $ON_BGCOLOR_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["BGColorB"]); this.oApp.exec("SHOW_COLOR_PALETTE", ["APPLY_BGCOLOR", this.elPaletteHolder]); }, $ON_BGCOLOR_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["BGColorB"]); this.oApp.exec("RESET_COLOR_PALETTE", []); }, $ON_EVENT_APPLY_BGCOLOR : function(weEvent){ var elButton = weEvent.element; // Safari/Chrome/Opera may capture the event on Span while(elButton.tagName == "SPAN"){elButton = elButton.parentNode;} if(elButton.tagName != "BUTTON"){return;} var sBGColor, sFontColor; sBGColor = elButton.style.backgroundColor; sFontColor = elButton.style.color; this.oApp.exec("APPLY_BGCOLOR", [sBGColor, sFontColor]); }, $ON_APPLY_LAST_USED_BGCOLOR : function(){ this.oApp.exec("APPLY_BGCOLOR", [this.sLastUsedColor]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['bgcolor']); }, $ON_APPLY_BGCOLOR : function(sBGColor, sFontColor){ if(!this.rxColorPattern.test(sBGColor)){ alert(this.oApp.$MSG("SE_Color.invalidColorCode")); return; } this._setLastUsedBGColor(sBGColor); var oStyle = {"backgroundColor": sBGColor}; if(sFontColor){oStyle.color = sFontColor;} this.oApp.exec("SET_WYSIWYG_STYLE", [oStyle]); this.oApp.exec("HIDE_ACTIVE_LAYER"); }, //@lazyload_js] _setLastUsedBGColor : function(sBGColor){ this.sLastUsedColor = sBGColor; this.elLastUsed.style.backgroundColor = this.sLastUsedColor; } }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to hyperlink * @name hp_SE_Hyperlink.js */ nhn.husky.SE2M_Hyperlink = jindo.$Class({ name : "SE2M_Hyperlink", sATagMarker : "HTTP://HUSKY_TMP.MARKER/", _assignHTMLElements : function(elAppContainer){ this.oHyperlinkButton = jindo.$$.getSingle("li.husky_seditor_ui_hyperlink", elAppContainer); this.oHyperlinkLayer = jindo.$$.getSingle("div.se2_layer", this.oHyperlinkButton); this.oLinkInput = jindo.$$.getSingle("INPUT[type=text]", this.oHyperlinkLayer); this.oBtnConfirm = jindo.$$.getSingle("button.se2_apply", this.oHyperlinkLayer); this.oBtnCancel = jindo.$$.getSingle("button.se2_cancel", this.oHyperlinkLayer); //this.oCbNewWin = jindo.$$.getSingle("INPUT[type=checkbox]", this.oHyperlinkLayer) || null; }, _generateAutoLink : function(sAll, sBreaker, sURL, sWWWURL, sHTTPURL) { sBreaker = sBreaker || ""; var sResult; if (sWWWURL){ sResult = '<a href="http://'+sWWWURL+'">'+sURL+'</a>'; } else { sResult = '<a href="'+sHTTPURL+'">'+sURL+'</a>'; } return sBreaker+sResult; }, $ON_MSG_APP_READY : function(){ this.bLayerShown = false; this.oApp.exec("REGISTER_UI_EVENT", ["hyperlink", "click", "TOGGLE_HYPERLINK_LAYER"]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+k", "TOGGLE_HYPERLINK_LAYER", []]); }, $ON_REGISTER_CONVERTERS : function(){ this.oApp.exec("ADD_CONVERTER_DOM", ["IR_TO_DB", jindo.$Fn(function(oTmpNode){ //저장 시점에 자동 링크를 위한 함수. var oTmpRange = this.oApp.getEmptySelection(); var elFirstNode = oTmpRange._getFirstRealChild(oTmpNode); var elLastNode = oTmpRange._getLastRealChild(oTmpNode); var waAllNodes = jindo.$A(oTmpRange._getNodesBetween(elFirstNode, elLastNode)); var aAllTextNodes = waAllNodes.filter(function(elNode){return (elNode && elNode.nodeType === 3);}).$value(); var a = aAllTextNodes; /* // 텍스트 검색이 용이 하도록 끊어진 텍스트 노드가 있으면 합쳐줌. (화면상으로 ABC라고 보이나 상황에 따라 실제 2개의 텍스트 A, BC로 이루어져 있을 수 있음. 이를 ABC 하나의 노드로 만들어 줌.) // 문제 발생 가능성에 비해서 퍼포먼스나 사이드 이펙트 가능성 높아 일단 주석 var aCleanTextNodes = []; for(var i=0, nLen=aAllTextNodes.length; i<nLen; i++){ if(a[i].nextSibling && a[i].nextSibling.nodeType === 3){ a[i].nextSibling.nodeValue += a[i].nodeValue; a[i].parentNode.removeChild(a[i]); }else{ aCleanTextNodes[aCleanTextNodes.length] = a[i]; } } */ var aCleanTextNodes = aAllTextNodes; // IE에서 PRE를 제외한 다른 태그 하위에 있는 텍스트 노드는 줄바꿈 등의 값을 변질시킴 var elTmpDiv = this.oApp.getWYSIWYGDocument().createElement("DIV"); var elParent, bAnchorFound; var sTmpStr = "@"+(new Date()).getTime()+"@"; var rxTmpStr = new RegExp(sTmpStr, "g"); for(var i=0, nLen=aAllTextNodes.length; i<nLen; i++){ // Anchor가 이미 걸려 있는 텍스트이면 링크를 다시 걸지 않음. elParent = a[i].parentNode; bAnchorFound = false; while(elParent){ if(elParent.tagName === "A" || elParent.tagName === "PRE"){ bAnchorFound = true; break; } elParent = elParent.parentNode; } if(bAnchorFound){ continue; } // www.또는 http://으로 시작하는 텍스트에 링크 걸어 줌 // IE에서 텍스트 노드 앞쪽의 스페이스나 주석등이 사라지는 현상이 있어 sTmpStr을 앞에 붙여줌. elTmpDiv.innerHTML = ""; elTmpDiv.appendChild(a[i].cloneNode(true)); // IE에서 innerHTML를 이용 해 직접 텍스트 노드 값을 할당 할 경우 줄바꿈등이 깨질 수 있어, 텍스트 노드로 만들어서 이를 바로 append 시켜줌 elTmpDiv.innerHTML = (sTmpStr+elTmpDiv.innerHTML).replace(/(&nbsp|\s)?(((?!http:\/\/)www\.(?:(?!\&nbsp;|\s|"|').)+)|(http:\/\/(?:(?!&nbsp;|\s|"|').)+))/ig, this._generateAutoLink); // innerHTML 내에 텍스트가 있을 경우 insert 시에 주변 텍스트 노드와 합쳐지는 현상이 있어 div로 위치를 먼저 잡고 하나씩 삽입 a[i].parentNode.insertBefore(elTmpDiv, a[i]); a[i].parentNode.removeChild(a[i]); while(elTmpDiv.firstChild){ elTmpDiv.parentNode.insertBefore(elTmpDiv.firstChild, elTmpDiv); } elTmpDiv.parentNode.removeChild(elTmpDiv); // alert(a[i].nodeValue); } oTmpNode.innerHTML = oTmpNode.innerHTML.replace(rxTmpStr, ""); //alert(oTmpNode.innerHTML); }, this).bind()]); }, $LOCAL_BEFORE_FIRST : function(sMsg){ if(!!sMsg.match(/(REGISTER_CONVERTERS)/)){ this.oApp.acceptLocalBeforeFirstAgain(this, true); return true; } this._assignHTMLElements(this.oApp.htOptions.elAppContainer); this.sRXATagMarker = this.sATagMarker.replace(/\//g, "\\/").replace(/\./g, "\\."); this.oApp.registerBrowserEvent(this.oBtnConfirm, "click", "APPLY_HYPERLINK"); this.oApp.registerBrowserEvent(this.oBtnCancel, "click", "HIDE_ACTIVE_LAYER"); this.oApp.registerBrowserEvent(this.oLinkInput, "keydown", "EVENT_HYPERLINK_KEYDOWN"); }, //@lazyload_js TOGGLE_HYPERLINK_LAYER,APPLY_HYPERLINK[ $ON_TOGGLE_HYPERLINK_LAYER : function(){ if(!this.bLayerShown){ this.oApp.exec("IE_FOCUS", []); this.oSelection = this.oApp.getSelection(); } // hotkey may close the layer right away so delay here this.oApp.delayedExec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oHyperlinkLayer, null, "MSG_HYPERLINK_LAYER_SHOWN", [], "MSG_HYPERLINK_LAYER_HIDDEN", [""]], 0); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['hyperlink']); }, $ON_MSG_HYPERLINK_LAYER_SHOWN : function(){ this.bLayerShown = true; var oAnchor = this.oSelection.findAncestorByTagName("A"); if (!oAnchor) { oAnchor = this._getSelectedNode(); } //this.oCbNewWin.checked = false; if(oAnchor && !this.oSelection.collapsed){ this.oSelection.selectNode(oAnchor); this.oSelection.select(); var sTarget = oAnchor.target; //if(sTarget && sTarget == "_blank"){this.oCbNewWin.checked = true;} // href속성에 문제가 있을 경우, 예: href="http://na&nbsp;&nbsp; ver.com", IE에서 oAnchor.href 접근 시에 알수 없는 오류를 발생시킴 try{ var sHref = oAnchor.getAttribute("href"); this.oLinkInput.value = sHref && sHref.indexOf("#") == -1 ? sHref : "http://"; }catch(e){ this.oLinkInput.value = "http://"; } this.bModify = true; }else{ this.oLinkInput.value = "http://"; this.bModify = false; } this.oApp.delayedExec("SELECT_UI", ["hyperlink"], 0); this.oLinkInput.focus(); this.oLinkInput.value = this.oLinkInput.value; this.oLinkInput.select(); }, $ON_MSG_HYPERLINK_LAYER_HIDDEN : function(){ this.bLayerShown = false; this.oApp.exec("DESELECT_UI", ["hyperlink"]); }, $ON_APPLY_HYPERLINK : function(){ var sURL = this.oLinkInput.value; if(!/^((http|https|ftp|mailto):(?:\/\/)?)/.test(sURL)){ sURL = "http://"+sURL; } sURL = sURL.replace(/\s+$/, ""); var oAgent = jindo.$Agent().navigator(); var sBlank = ""; this.oApp.exec("IE_FOCUS", []); if(oAgent.ie){sBlank = "<span style=\"text-decoration:none;\">&nbsp;</span>";} if(this._validateURL(sURL)){ //if(this.oCbNewWin.checked){ if(false){ sTarget = "_blank"; }else{ sTarget = "_self"; } this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["HYPERLINK", {sSaveTarget:(this.bModify ? "A" : null)}]); var sBM; if(this.oSelection.collapsed){ var str = "<a href='" + sURL + "' target="+sTarget+">" + sURL + "</a>" + sBlank; this.oSelection.pasteHTML(str); sBM = this.oSelection.placeStringBookmark(); }else{ // 브라우저에서 제공하는 execcommand에 createLink로는 타겟을 지정할 수가 없다. // 그렇기 때문에, 더미 URL을 createLink에 넘겨서 링크를 먼저 걸고, 이후에 loop을 돌면서 더미 URL을 가진 A태그를 찾아서 정상 URL 및 타겟을 세팅 해 준다. sBM = this.oSelection.placeStringBookmark(); this.oSelection.select(); // [SMARTEDITORSUS-61] TD 안에 있는 텍스트를 전체 선택하여 URL 변경하면 수정되지 않음 (only IE8) // SE_EditingArea_WYSIWYG 에서는 IE인 경우, beforedeactivate 이벤트가 발생하면 현재의 Range를 저장하고, RESTORE_IE_SELECTION 메시지가 발생하면 저장된 Range를 적용한다. // IE8 또는 IE7 호환모드이고 TD 안의 텍스트 전체를 선택한 경우 Bookmark 생성 후의 select()를 처리할 때 // HuskyRange 에서 호출되는 this._oSelection.empty(); 에서 beforedeactivate 가 발생하여 empty 처리된 selection 이 저장되는 문제가 있어 링크가 적용되지 않음. // 올바른 selection 이 저장되어 EXECCOMMAND에서 링크가 적용될 수 있도록 함 if(oAgent.ie && (oAgent.version === 8 || oAgent.nativeVersion === 8)){ // nativeVersion 으로 IE7 호환모드인 경우 확인 this.oApp.exec("IE_FOCUS", []); this.oSelection.moveToBookmark(sBM); this.oSelection.select(); } // createLink 이후에 이번에 생성된 A 태그를 찾을 수 있도록 nSession을 포함하는 더미 링크를 만든다. var nSession = Math.ceil(Math.random()*10000); if(sURL == ""){ // unlink this.oApp.exec("EXECCOMMAND", ["unlink"]); }else{ // createLink if(this._isExceptional()){ this.oApp.exec("EXECCOMMAND", ["unlink", false, "", {bDontAddUndoHistory: true}]); var sTempUrl = "<a href='" + sURL + "' target="+sTarget+">"; jindo.$A(this.oSelection.getNodes(true)).forEach(function(value, index, array){ var oEmptySelection = this.oApp.getEmptySelection(); if(value.nodeType === 3){ oEmptySelection.selectNode(value); oEmptySelection.pasteHTML(sTempUrl + value.nodeValue + "</a>"); }else if(value.nodeType === 1 && value.tagName === "IMG"){ oEmptySelection.selectNode(value); oEmptySelection.pasteHTML(sTempUrl + jindo.$Element(value).outerHTML() + "</a>"); } }, this); }else{ this.oApp.exec("EXECCOMMAND", ["createLink", false, this.sATagMarker+nSession+encodeURIComponent(sURL), {bDontAddUndoHistory: true}]); } } var oDoc = this.oApp.getWYSIWYGDocument(); var aATags = oDoc.body.getElementsByTagName("A"); var nLen = aATags.length; var rxMarker = new RegExp(this.sRXATagMarker+nSession, "gi"); var elATag; for(var i=0; i<nLen; i++){ elATag = aATags[i]; var sHref = ""; try{ sHref = elATag.getAttribute("href"); }catch(e){} if (sHref && sHref.match(rxMarker)) { var sNewHref = sHref.replace(rxMarker, ""); var sDecodeHref = decodeURIComponent(sNewHref); if(oAgent.ie){ jindo.$Element(elATag).attr({ "href" : sDecodeHref, "target" : sTarget }); //}else if(oAgent.firefox){ }else{ var sAContent = jindo.$Element(elATag).html(); jindo.$Element(elATag).attr({ "href" : sDecodeHref, "target" : sTarget }); if(this._validateURL(sAContent)){ jindo.$Element(elATag).html(jindo.$Element(elATag).attr("href")); } } /*else{ elATag.href = sDecodeHref; } */ } } } this.oApp.exec("HIDE_ACTIVE_LAYER"); setTimeout(jindo.$Fn(function(){ var oSelection = this.oApp.getEmptySelection(); oSelection.moveToBookmark(sBM); oSelection.collapseToEnd(); oSelection.select(); oSelection.removeStringBookmark(sBM); this.oApp.exec("FOCUS"); this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["HYPERLINK", {sSaveTarget:(this.bModify ? "A" : null)}]); }, this).bind(), 17); }else{ alert(this.oApp.$MSG("SE_Hyperlink.invalidURL")); this.oLinkInput.focus(); } }, _isExceptional : function(){ var oNavigator = jindo.$Agent().navigator(), bImg = false, bEmail = false; if(!oNavigator.ie){ return false; } // [SMARTEDITORSUS-612] 이미지 선택 후 링크 추가했을 때 링크가 걸리지 않는 문제 if(this.oApp.getWYSIWYGDocument().selection.type === "None"){ bImg = jindo.$A(this.oSelection.getNodes()).some(function(value, index, array){ if(value.nodeType === 1 && value.tagName === "IMG"){ return true; } }, this); if(bImg){ return true; } } if(oNavigator.nativeVersion > 8){ // version? nativeVersion? return false; } // [SMARTEDITORSUS-579] IE8 이하에서 E-mail 패턴 문자열에 URL 링크 못거는 이슈 bEmail = jindo.$A(this.oSelection.getTextNodes()).some(function(value, index, array){ if(value.nodeValue.indexOf("@") >= 1){ return true; } }, this); if(bEmail){ return true; } return false; }, //@lazyload_js] $ON_EVENT_HYPERLINK_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.oApp.exec("APPLY_HYPERLINK"); oEvent.stop(); } }, _getSelectedNode : function(){ var aNodes = this.oSelection.getNodes(); for (var i = 0; i < aNodes.length; i++) { if (aNodes[i].tagName && aNodes[i].tagName == "A") { return aNodes[i]; } } }, _validateURL : function(sURL){ if(!sURL){return false;} // escape 불가능한 %가 들어있나 확인 try{ var aURLParts = sURL.split("?"); aURLParts[0] = aURLParts[0].replace(/%[a-z0-9]{2}/gi, "U"); decodeURIComponent(aURLParts[0]); }catch(e){ return false; } return /^(http|https|ftp|mailto):(\/\/)?(([-가-힣]|\w)+(?:[\/\.:@]([-가-힣]|\w)+)+)\/?(.*)?\s*$/i.test(sURL); } }); //}
JavaScript
/** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font name using Select element * @name SE2M_FontNameWithLayerUI.js * @trigger MSG_STYLE_CHANGED,SE2M_TOGGLE_FONTNAME_LAYER */ nhn.husky.SE2M_FontNameWithLayerUI = jindo.$Class({ name : "SE2M_FontNameWithLayerUI", $init : function(elAppContainer){ this.elLastHover = null; this._assignHTMLElements(elAppContainer); this.htBrowser = jindo.$Agent().navigator(); }, addAllFonts : function(){ var aDefaultFontList, aFontList, htMainFont, aFontInUse, i; // family name -> display name 매핑 (웹폰트는 두개가 다름) this.htFamilyName2DisplayName = {}; this.htAllFonts = {}; this.aBaseFontList = []; this.aDefaultFontList = []; this.aTempSavedFontList = []; this.htOptions = this.oApp.htOptions.SE2M_FontName; if(this.htOptions){ aDefaultFontList = this.htOptions.aDefaultFontList || []; aFontList = this.htOptions.aFontList; htMainFont = this.htOptions.htMainFont; aFontInUse = this.htOptions.aFontInUse; //add Font if(this.oApp.oNavigator.ie && aFontList){ for(i=0; i<aFontList.length; i++){ this.addFont(aFontList[i].id, aFontList[i].name, aFontList[i].size, aFontList[i].url, aFontList[i].cssUrl); } } for(i=0; i<aDefaultFontList.length; i++){ this.addFont(aDefaultFontList[i][0], aDefaultFontList[i][1], 0, "", "", 1); } //set Main Font //if(mainFontSelected=='true') { if(htMainFont && htMainFont.id) { //this.setMainFont(mainFontId, mainFontName, mainFontSize, mainFontUrl, mainFontCssUrl); this.setMainFont(htMainFont.id, htMainFont.name, htMainFont.size, htMainFont.url, htMainFont.cssUrl); } // add font in use if(this.oApp.oNavigator.ie && aFontInUse){ for(i=0; i<aFontInUse.length; i++){ this.addFontInUse(aFontInUse[i].id, aFontInUse[i].name, aFontInUse[i].size, aFontInUse[i].url, aFontInUse[i].cssUrl); } } } // [SMARTEDITORSUS-245] 서비스 적용 시 글꼴정보를 넘기지 않으면 기본 글꼴 목록이 보이지 않는 오류 if(!this.htOptions || !this.htOptions.aDefaultFontList || this.htOptions.aDefaultFontList.length === 0){ this.addFont("돋움,Dotum", "돋움", 0, "", "", 1); this.addFont("돋움체,DotumChe", "돋움체", 0, "", "", 1); this.addFont("굴림,Gulim", "굴림", 0, "", "", 1); this.addFont("굴림체,GulimChe", "굴림체", 0, "", "", 1); this.addFont("바탕,Batang", "바탕", 0, "", "", 1); this.addFont("바탕체,BatangChe", "바탕체", 0, "", "", 1); this.addFont("궁서,Gungsuh", "궁서", 0, "", "", 1); this.addFont('Arial', 'Arial', 0, "", "", 1); this.addFont('Tahoma', 'Tahoma', 0, "", "", 1, "abcd"); this.addFont('Times New Roman', 'Times New Roman', 0, "", "", 1, "abcd"); this.addFont('Verdana', 'Verdana', 0, "", "", 1, "abcd"); } }, $ON_MSG_APP_READY : function(){ this.bDoNotRecordUndo = false; this.oApp.exec("ADD_APP_PROPERTY", ["addFont", jindo.$Fn(this.addFont, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["addFontInUse", jindo.$Fn(this.addFontInUse, this).bind()]); // 블로그등 팩토리 폰트 포함 용 this.oApp.exec("ADD_APP_PROPERTY", ["setMainFont", jindo.$Fn(this.setMainFont, this).bind()]); // 메일등 단순 폰트 지정 용 this.oApp.exec("ADD_APP_PROPERTY", ["setDefaultFont", jindo.$Fn(this.setDefaultFont, this).bind()]); this.oApp.exec("REGISTER_UI_EVENT", ["fontName", "click", "SE2M_TOGGLE_FONTNAME_LAYER"]); }, $AFTER_MSG_APP_READY : function(){ this._initFontName(); this._attachIEEvent(); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se_fontName_layer", elAppContainer); this.elFontNameLabel = jindo.$$.getSingle("SPAN.husky_se2m_current_fontName", elAppContainer); this.elFontNameList = jindo.$$.getSingle("UL", this.oDropdownLayer); this.elInnerLayer = this.elFontNameList.parentNode; this.elFontItemTemplate = jindo.$$.getSingle("LI", this.oDropdownLayer); this.aLIFontNames = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild !== null);})._array; this.elSeparator = jindo.$$.getSingle("LI.husky_seditor_font_separator", this.oDropdownLayer); this.elNanumgothic = jindo.$$.getSingle("LI.husky_seditor_font_nanumgothic", this.oDropdownLayer); this.elNanummyeongjo = jindo.$$.getSingle("LI.husky_seditor_font_nanummyeongjo", this.oDropdownLayer); //@ec] this.sDefaultText = this.elFontNameLabel.innerHTML; }, //$LOCAL_BEFORE_FIRST : function(){ _initFontName : function(){ this._addNanumFont(); this.addAllFonts(); this.oApp.registerBrowserEvent(this.oDropdownLayer, "mouseover", "EVENT_FONTNAME_LAYER_MOUSEOVER", []); this.oApp.registerBrowserEvent(this.oDropdownLayer, "click", "EVENT_FONTNAME_LAYER_CLICKED", []); }, _addNanumFont : function(){ var bUseSeparator = false; var nanum_gothic = unescape("%uB098%uB214%uACE0%uB515"); var nanum_myungjo = unescape("%uB098%uB214%uBA85%uC870"); if(jindo.$Agent().os().mac){ nanum_gothic = "NanumGothic"; nanum_myungjo = "NanumMyeongjo"; } if(!!this.elNanumgothic){ if(IsInstalledFont(nanum_gothic)){ bUseSeparator = true; this.elNanumgothic.style.display = "block"; }else{ this.elNanumgothic.style.display = "none"; } } if(!!this.elNanummyeongjo){ if(IsInstalledFont(nanum_myungjo)){ bUseSeparator = true; this.elNanummyeongjo.style.display = "block"; }else{ this.elNanummyeongjo.style.display = "none"; } } if(!!this.elSeparator){ this.elSeparator.style.display = bUseSeparator ? "block" : "none"; } }, _attachIEEvent : function(){ if(!this.htBrowser.ie){ return; } if(this.htBrowser.nativeVersion < 9){ // [SMARTEDITORSUS-187] [< IE9] 최초 paste 시점에 웹폰트 파일을 로드 this._wfOnPasteWYSIWYGBody = jindo.$Fn(this._onPasteWYSIWYGBody, this); this._wfOnPasteWYSIWYGBody.attach(this.oApp.getWYSIWYGDocument().body, "paste"); return; } if(document.documentMode < 9){ // [SMARTEDITORSUS-169] [>= IE9] 최초 포커스 시점에 웹폰트 로드 this._wfOnFocusWYSIWYGBody = jindo.$Fn(this._onFocusWYSIWYGBody, this); this._wfOnFocusWYSIWYGBody.attach(this.oApp.getWYSIWYGDocument().body, "focus"); return; } // documentMode === 9 // http://blogs.msdn.com/b/ie/archive/2010/08/17/ie9-opacity-and-alpha.aspx // opacity:0.0; this.welEditingAreaCover = jindo.$Element('<DIV style="width:100%; height:100%; position:absolute; top:0px; left:0px; z-index:1000;"></DIV>'); this.oApp.welEditingAreaContainer.prepend(this.welEditingAreaCover); jindo.$Fn(this._onMouseupCover, this).attach(this.welEditingAreaCover.$value(), "mouseup"); }, _onFocusWYSIWYGBody : function(e){ this._wfOnFocusWYSIWYGBody.detach(this.oApp.getWYSIWYGDocument().body, "focus"); this._loadAllBaseFont(); }, _onPasteWYSIWYGBody : function(e){ this._wfOnPasteWYSIWYGBody.detach(this.oApp.getWYSIWYGDocument().body, "paste"); this._loadAllBaseFont(); }, _onMouseupCover : function(e){ e.stop(); this.welEditingAreaCover.leave(); var oMouse = e.mouse(), elBody = this.oApp.getWYSIWYGDocument().body, welBody = jindo.$Element(elBody), oSelection = this.oApp.getEmptySelection(); // [SMARTEDITORSUS-363] 강제로 Selection 을 주도록 처리함 oSelection.selectNode(elBody); oSelection.collapseToStart(); oSelection.select(); welBody.fireEvent("mousedown", {left : oMouse.left, middle : oMouse.middle, right : oMouse.right}); welBody.fireEvent("mouseup", {left : oMouse.left, middle : oMouse.middle, right : oMouse.right}); }, $ON_EVENT_TOOLBAR_MOUSEDOWN : function(){ if(this.htBrowser.nativeVersion < 9 || document.documentMode < 9){ return; } this.welEditingAreaCover.leave(); }, _loadAllBaseFont : function(){ var i, nFontLen; if(!this.htBrowser.ie){ return; } if(this.htBrowser.nativeVersion < 9){ for(i=0, nFontLen=this.aBaseFontList.length; i<nFontLen; i++){ this.aBaseFontList[i].loadCSS(this.oApp.getWYSIWYGDocument()); } }else if(document.documentMode < 9){ for(i=0, nFontLen=this.aBaseFontList.length; i<nFontLen; i++){ this.aBaseFontList[i].loadCSSToMenu(); } } this._loadAllBaseFont = function(){}; }, _addFontToMenu: function(sDisplayName, sFontFamily, sSampleText){ var elItem = document.createElement("LI"); elItem.innerHTML = this.elFontItemTemplate.innerHTML.replace("@DisplayName@", sDisplayName).replace("FontFamily", sFontFamily).replace("@SampleText@", sSampleText); this.elFontNameList.insertBefore(elItem, this.elFontItemTemplate); this.aLIFontNames[this.aLIFontNames.length] = elItem; if(this.aLIFontNames.length > 20){ this.oDropdownLayer.style.overflowX = 'hidden'; this.oDropdownLayer.style.overflowY = 'auto'; this.oDropdownLayer.style.height = '400px'; this.oDropdownLayer.style.width = '204px'; // [SMARTEDITORSUS-155] 스크롤을 포함하여 206px 이 되도록 처리 } }, $ON_EVENT_FONTNAME_LAYER_MOUSEOVER : function(wev){ var elTmp = this._findLI(wev.element); if(!elTmp){ return; } this._clearLastHover(); elTmp.className = "hover"; this.elLastHover = elTmp; }, $ON_EVENT_FONTNAME_LAYER_CLICKED : function(wev){ var elTmp = this._findLI(wev.element); if(!elTmp){ return; } var sFontFamily = this._getFontFamilyFromLI(elTmp); // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 var htFontInfo = this.htAllFonts[sFontFamily.replace(/\"/g, nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS)]; var nDefaultFontSize; if(htFontInfo){ nDefaultFontSize = htFontInfo.defaultSize+"pt"; }else{ nDefaultFontSize = 0; } this.oApp.exec("SET_FONTFAMILY", [sFontFamily, nDefaultFontSize]); }, _findLI : function(elTmp){ while(elTmp.tagName != "LI"){ if(!elTmp || elTmp === this.oDropdownLayer){ return null; } elTmp = elTmp.parentNode; } if(/husky_seditor_font_separator/.test(elTmp.className)){ return null; } return elTmp; }, _clearLastHover : function(){ if(this.elLastHover){ this.elLastHover.className = ""; } }, $ON_SE2M_TOGGLE_FONTNAME_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "MSG_FONTNAME_LAYER_OPENED", [], "MSG_FONTNAME_LAYER_CLOSED", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['font']); }, $ON_MSG_FONTNAME_LAYER_OPENED : function(){ this.oApp.exec("SELECT_UI", ["fontName"]); }, $ON_MSG_FONTNAME_LAYER_CLOSED : function(){ this._clearLastHover(); this.oApp.exec("DESELECT_UI", ["fontName"]); }, $ON_MSG_STYLE_CHANGED : function(sAttributeName, sAttributeValue){ if(sAttributeName == "fontFamily"){ sAttributeValue = sAttributeValue.replace(/["']/g, ""); var elLi = this._getMatchingLI(sAttributeValue); this._clearFontNameSelection(); if(elLi){ this.elFontNameLabel.innerHTML = this._getFontNameLabelFromLI(elLi); jindo.$Element(elLi).addClass("active"); }else{ //var sDisplayName = this.htFamilyName2DisplayName[sAttributeValue] || sAttributeValue; var sDisplayName = this.sDefaultText; this.elFontNameLabel.innerHTML = sDisplayName; } } }, $BEFORE_RECORD_UNDO_BEFORE_ACTION : function(){ return !this.bDoNotRecordUndo; }, $BEFORE_RECORD_UNDO_AFTER_ACTION : function(){ return !this.bDoNotRecordUndo; }, $BEFORE_RECORD_UNDO_ACTION : function(){ return !this.bDoNotRecordUndo; }, $ON_SET_FONTFAMILY : function(sFontFamily, sDefaultSize){ if(!sFontFamily){return;} // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 var oFontInfo = this.htAllFonts[sFontFamily.replace(/\"/g, nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS)]; if(!!oFontInfo){ oFontInfo.loadCSS(this.oApp.getWYSIWYGDocument()); } // fontFamily와 fontSize 두개의 액션을 하나로 묶어서 undo history 저장 this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["SET FONTFAMILY", {bMustBlockElement:true}]); this.bDoNotRecordUndo = true; if(parseInt(sDefaultSize, 10) > 0){ this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontSize":sDefaultSize}]); } this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontFamily":sFontFamily}]); this.bDoNotRecordUndo = false; this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["SET FONTFAMILY", {bMustBlockElement:true}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getMatchingLI : function(sFontName){ sFontName = sFontName.toLowerCase(); var elLi, aFontFamily; for(var i=0; i<this.aLIFontNames.length; i++){ elLi = this.aLIFontNames[i]; aFontFamily = this._getFontFamilyFromLI(elLi).split(","); for(var h=0; h < aFontFamily.length;h++){ if( !!aFontFamily[h] && jindo.$S(aFontFamily[h].replace(/['"]/ig, "")).trim().$value() == sFontName){ return elLi; } } } return null; }, _getFontFamilyFromLI : function(elLi){ //return elLi.childNodes[1].innerHTML.toLowerCase(); // <li><button type="button"><span>돋음</span>(</span><em style="font-family:'돋음',Dotum,'굴림',Gulim,Helvetica,Sans-serif;">돋음</em><span>)</span></span></button></li> return (elLi.getElementsByTagName("EM")[0]).style.fontFamily; }, _getFontNameLabelFromLI : function(elLi){ return elLi.firstChild.firstChild.firstChild.nodeValue; }, _clearFontNameSelection : function(elLi){ for(var i=0; i<this.aLIFontNames.length; i++){ jindo.$Element(this.aLIFontNames[i]).removeClass("active"); } }, // Add the font to the list // fontType == null, custom font (sent from the server) // fontType == 1, default font // fontType == 2, tempSavedFont addFont : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType, sSampleText) { // custom font feature only available in IE if(!this.oApp.oNavigator.ie && fontCSSURL){ return null; } fontId = fontId.toLowerCase(); var newFont = new fontProperty(fontId, fontName, defaultSize, fontURL, fontCSSURL); var sFontFamily; var sDisplayName; if(defaultSize>0){ sFontFamily = fontId+"_"+defaultSize; sDisplayName = fontName+"_"+defaultSize; }else{ sFontFamily = fontId; sDisplayName = fontName; } if(!fontType){ sFontFamily = nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS + sFontFamily + nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS; } if(this.htAllFonts[sFontFamily]){ return this.htAllFonts[sFontFamily]; } this.htAllFonts[sFontFamily] = newFont; /* // do not add again, if the font is already in the list for(var i=0; i<this._allFontList.length; i++){ if(newFont.fontFamily == this._allFontList[i].fontFamily){ return this._allFontList[i]; } } this._allFontList[this._allFontList.length] = newFont; */ // [SMARTEDITORSUS-169] [IE9] 웹폰트A 선택>웹폰트B 선택>웹폰트 A를 다시 선택하면 웹폰트 A가 적용되지 않는 문제가 발생 // // [원인] // - IE9의 웹폰트 로드/언로드 시점 // 웹폰트 로드 시점: StyleSheet 의 @font-face 구문이 해석된 이후, DOM Tree 상에서 해당 웹폰트가 최초로 사용된 시점 // 웹폰트 언로드 시점: StyleSheet 의 @font-face 구문이 해석된 이후, DOM Tree 상에서 해당 웬폰트가 더이상 사용되지 않는 시점 // - 메뉴 리스트에 적용되는 스타일은 @font-face 이전에 처리되는 것이어서 언로드에 영향을 미치지 않음 // // 스마트에디터의 경우, 웹폰트를 선택할 때마다 SPAN 이 새로 추가되는 것이 아닌 선택된 SPAN 의 fontFamily 를 변경하여 처리하므로 // fontFamily 변경 후 DOM Tree 상에서 더이상 사용되지 않는 것으로 브라우저 판단하여 언로드 해버림. // [해결] // 언로드가 발생하지 않도록 메뉴 리스트에 스타일을 적용하는 것을 @font-face 이후로 하도록 처리하여 DOM Tree 상에 항상 적용될 수 있도록 함 // // [SMARTEDITORSUS-969] [IE10] 웹폰트를 사용하여 글을 등록하고, 수정모드로 들어갔을 때 웹폰트가 적용되지 않는 문제 // - IE10에서도 웹폰트 언로드가 발생하지 않도록 조건을 수정함 // -> 기존 : nativeVersion === 9 && documentMode === 9 // -> 수정 : nativeVersion >= 9 && documentMode >= 9 if(this.htBrowser.ie && this.htBrowser.nativeVersion >= 9 && document.documentMode >= 9) { newFont.loadCSSToMenu(); } this.htFamilyName2DisplayName[sFontFamily] = fontName; sSampleText = sSampleText || this.oApp.$MSG('SE2M_FontNameWithLayerUI.sSampleText'); this._addFontToMenu(sDisplayName, sFontFamily, sSampleText); if(!fontType){ this.aBaseFontList[this.aBaseFontList.length] = newFont; }else{ if(fontType == 1){ this.aDefaultFontList[this.aDefaultFontList.length] = newFont; }else{ this.aTempSavedFontList[this.aTempSavedFontList.length] = newFont; } } return newFont; }, // Add the font AND load it right away addFontInUse : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType) { var newFont = this.addFont(fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType); if(!newFont){ return null; } newFont.loadCSS(this.oApp.getWYSIWYGDocument()); return newFont; }, // Add the font AND load it right away AND THEN set it as the default font setMainFont : function (fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType) { var newFont = this.addFontInUse(fontId, fontName, defaultSize, fontURL, fontCSSURL, fontType); if(!newFont){ return null; } this.setDefaultFont(newFont.fontFamily, defaultSize); return newFont; }, setDefaultFont : function(sFontFamily, nFontSize){ var elBody = this.oApp.getWYSIWYGDocument().body; elBody.style.fontFamily = sFontFamily; if(nFontSize>0){elBody.style.fontSize = nFontSize + 'pt';} } }); nhn.husky.SE2M_FontNameWithLayerUI.CUSTOM_FONT_MARKS = "'"; // [SMARTEDITORSUS-169] 웹폰트의 경우 fontFamily 에 ' 을 붙여주는 처리를 함 // property function for all fonts - including the default fonts and the custom fonts // non-custom fonts will have the defaultSize of 0 and empty string for fontURL/fontCSSURL function fontProperty(fontId, fontName, defaultSize, fontURL, fontCSSURL){ this.fontId = fontId; this.fontName = fontName; this.defaultSize = defaultSize; this.fontURL = fontURL; this.fontCSSURL = fontCSSURL; this.displayName = fontName; this.isLoaded = true; this.fontFamily = this.fontId; // it is custom font if(this.fontCSSURL != ""){ this.displayName += '' + defaultSize; this.fontFamily += '_' + defaultSize; // custom fonts requires css loading this.isLoaded = false; // load the css that loads the custom font this.loadCSS = function(doc){ // if the font is loaded already, return if(this.isLoaded){ return; } this._importCSS(doc); this.isLoaded = true; }; // [SMARTEDITORSUS-169] [IE9] // addImport 후에 처음 적용된 DOM-Tree 가 iframe 내부인 경우 (setMainFont || addFontInUse 에서 호출된 경우) // 해당 폰트에 대한 언로드 문제가 계속 발생하여 IE9에서 addFont 에서 호출하는 loadCSS 의 경우에는 isLoaded를 true 로 변경하지 않음. this.loadCSSToMenu = function(){ this._importCSS(document); }; this._importCSS = function(doc){ var nStyleSheet = doc.styleSheets.length; var oStyleSheet = doc.styleSheets[nStyleSheet - 1]; if(nStyleSheet === 0 || oStyleSheet.imports.length == 30){ // imports limit oStyleSheet = doc.createStyleSheet(); } oStyleSheet.addImport(this.fontCSSURL); }; }else{ this.loadCSS = function(){}; this.loadCSSToMenu = function(){}; } this.toStruct = function(){ return {fontId:this.fontId, fontName:this.fontName, defaultSize:this.defaultSize, fontURL:this.fontURL, fontCSSURL:this.fontCSSURL}; }; }
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font size using Select element * @name SE2M_FontSizeWithLayerUI.js */ nhn.husky.SE2M_FontSizeWithLayerUI = jindo.$Class({ name : "SE2M_FontSizeWithLayerUI", $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); // this hash table is required for Firefox this.mapPX2PT = {}; this.mapPX2PT["8"] = "6"; this.mapPX2PT["9"] = "7"; this.mapPX2PT["10"] = "7.5"; this.mapPX2PT["11"] = "8"; this.mapPX2PT["12"] = "9"; this.mapPX2PT["13"] = "10"; this.mapPX2PT["14"] = "10.5"; this.mapPX2PT["15"] = "11"; this.mapPX2PT["16"] = "12"; this.mapPX2PT["17"] = "13"; this.mapPX2PT["18"] = "13.5"; this.mapPX2PT["19"] = "14"; this.mapPX2PT["20"] = "14.5"; this.mapPX2PT["21"] = "15"; this.mapPX2PT["22"] = "16"; this.mapPX2PT["23"] = "17"; this.mapPX2PT["24"] = "18"; this.mapPX2PT["26"] = "20"; this.mapPX2PT["29"] = "22"; this.mapPX2PT["32"] = "24"; this.mapPX2PT["35"] = "26"; this.mapPX2PT["36"] = "27"; this.mapPX2PT["37"] = "28"; this.mapPX2PT["38"] = "29"; this.mapPX2PT["40"] = "30"; this.mapPX2PT["42"] = "32"; this.mapPX2PT["45"] = "34"; this.mapPX2PT["48"] = "36"; }, _assignHTMLElements : function(elAppContainer){ //@ec this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se_fontSize_layer", elAppContainer); //@ec[ this.elFontSizeLabel = jindo.$$.getSingle("SPAN.husky_se2m_current_fontSize", elAppContainer); this.aLIFontSizes = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild != null);})._array; //@ec] this.sDefaultText = this.elFontSizeLabel.innerHTML; }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["fontSize", "click", "SE2M_TOGGLE_FONTSIZE_LAYER"]); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aLIFontSizes]); for(var i=0; i<this.aLIFontSizes.length; i++){ this.oApp.registerBrowserEvent(this.aLIFontSizes[i], "click", "SET_FONTSIZE", [this._getFontSizeFromLI(this.aLIFontSizes[i])]); } }, $ON_SE2M_TOGGLE_FONTSIZE_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "SELECT_UI", ["fontSize"], "DESELECT_UI", ["fontSize"]]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['size']); }, $ON_MSG_STYLE_CHANGED : function(sAttributeName, sAttributeValue){ if(sAttributeName == "fontSize"){ if(sAttributeValue.match(/px$/)){ var num = parseFloat(sAttributeValue.replace("px", "")).toFixed(0); if(this.mapPX2PT[num]){ sAttributeValue = this.mapPX2PT[num] + "pt"; }else{ if(sAttributeValue > 0){ sAttributeValue = num + "px"; }else{ sAttributeValue = this.sDefaultText; } } } if(!sAttributeValue){ sAttributeValue = this.sDefaultText; } var elLi = this._getMatchingLI(sAttributeValue); this._clearFontSizeSelection(); if(elLi){ this.elFontSizeLabel.innerHTML = sAttributeValue; jindo.$Element(elLi).addClass("active"); }else{ this.elFontSizeLabel.innerHTML = sAttributeValue; } } }, $ON_SET_FONTSIZE : function(sFontSize){ if(!sFontSize){return;} this.oApp.exec("SET_WYSIWYG_STYLE", [{"fontSize":sFontSize}]); this.oApp.exec("HIDE_ACTIVE_LAYER", []); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getMatchingLI : function(sFontSize){ var elLi; sFontSize = sFontSize.toLowerCase(); for(var i=0; i<this.aLIFontSizes.length; i++){ elLi = this.aLIFontSizes[i]; if(this._getFontSizeFromLI(elLi).toLowerCase() == sFontSize){return elLi;} } return null; }, _getFontSizeFromLI : function(elLi){ return elLi.firstChild.firstChild.style.fontSize; }, _clearFontSizeSelection : function(elLi){ for(var i=0; i<this.aLIFontSizes.length; i++){ jindo.$Element(this.aLIFontSizes[i]).removeClass("active"); } } });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the basic editor commands * @name hp_SE_ExecCommand.js */ nhn.husky.SE2M_ExecCommand = jindo.$Class({ name : "SE2M_ExecCommand", oEditingArea : null, oUndoOption : null, $init : function(oEditingArea){ this.oEditingArea = oEditingArea; this.nIndentSpacing = 40; this.rxClickCr = new RegExp('^bold|underline|italic|strikethrough|justifyleft|justifycenter|justifyright|justifyfull|insertorderedlist|insertunorderedlist|outdent|indent$', 'i'); }, $BEFORE_MSG_APP_READY : function(){ // the right document will be available only when the src is completely loaded if(this.oEditingArea && this.oEditingArea.tagName == "IFRAME"){ this.oEditingArea = this.oEditingArea.contentWindow.document; } }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_HOTKEY", ["ctrl+b", "EXECCOMMAND", ["bold", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+u", "EXECCOMMAND", ["underline", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+i", "EXECCOMMAND", ["italic", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["ctrl+d", "EXECCOMMAND", ["strikethrough", false, false]]); this.oApp.exec("REGISTER_HOTKEY", ["tab", "INDENT"]); this.oApp.exec("REGISTER_HOTKEY", ["shift+tab", "OUTDENT"]); //this.oApp.exec("REGISTER_HOTKEY", ["tab", "EXECCOMMAND", ["indent", false, false]]); //this.oApp.exec("REGISTER_HOTKEY", ["shift+tab", "EXECCOMMAND", ["outdent", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["bold", "click", "EXECCOMMAND", ["bold", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["underline", "click", "EXECCOMMAND", ["underline", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["italic", "click", "EXECCOMMAND", ["italic", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["lineThrough", "click", "EXECCOMMAND", ["strikethrough", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["superscript", "click", "EXECCOMMAND", ["superscript", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["subscript", "click", "EXECCOMMAND", ["subscript", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyleft", "click", "EXECCOMMAND", ["justifyleft", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifycenter", "click", "EXECCOMMAND", ["justifycenter", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyright", "click", "EXECCOMMAND", ["justifyright", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["justifyfull", "click", "EXECCOMMAND", ["justifyfull", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["orderedlist", "click", "EXECCOMMAND", ["insertorderedlist", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["unorderedlist", "click", "EXECCOMMAND", ["insertunorderedlist", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["outdent", "click", "EXECCOMMAND", ["outdent", false, false]]); this.oApp.exec("REGISTER_UI_EVENT", ["indent", "click", "EXECCOMMAND", ["indent", false, false]]); // this.oApp.exec("REGISTER_UI_EVENT", ["styleRemover", "click", "EXECCOMMAND", ["RemoveFormat", false, false]]); this.oNavigator = jindo.$Agent().navigator(); if(!this.oNavigator.safari && !this.oNavigator.chrome){ this._getDocumentBR = function(){}; this._fixDocumentBR = function(){}; } if(!this.oNavigator.ie){ this._fixCorruptedBlockQuote = function(){}; if(!this.oNavigator.chrome){ this._insertBlankLine = function(){}; } } if(!this.oNavigator.firefox){ this._extendBlock = function(){}; } }, $ON_INDENT : function(){ this.oApp.delayedExec("EXECCOMMAND", ["indent", false, false], 0); }, $ON_OUTDENT : function(){ this.oApp.delayedExec("EXECCOMMAND", ["outdent", false, false], 0); }, $BEFORE_EXECCOMMAND : function(sCommand, bUserInterface, vValue, htOptions){ var elTmp, oSelection; //본문에 전혀 클릭이 한번도 안 일어난 상태에서 크롬과 IE에서 EXECCOMMAND가 정상적으로 안 먹히는 현상. this.oApp.exec("FOCUS"); this._bOnlyCursorChanged = false; oSelection = this.oApp.getSelection(); if(/^insertorderedlist|insertunorderedlist$/i.test(sCommand)){ this._getDocumentBR(); } if(/^justify*/i.test(sCommand)){ this._removeSpanAlign(); } if(sCommand.match(/^bold|underline|italic|strikethrough|superscript|subscript$/i)){ this.oUndoOption = {bMustBlockElement:true}; if( nhn.CurrentSelection.isCollapsed()){ this._bOnlyCursorChanged = true; //[SMARTEDITORSUS-228] 글꼴 효과를 미리 지정 한 후에 텍스트 입력 시, 색상 변경은 적용되나 굵게 기울임 밑줄 취소선 등의 효과는 적용안됨 if( this.oNavigator.ie ){ if(oSelection.startContainer.tagName == "BODY" && oSelection.startOffset === 0){ elTmp = this.oApp.getWYSIWYGDocument().createElement("SPAN"); elTmp.innerHTML = unescape("%uFEFF"); oSelection.insertNode(elTmp); oSelection.select(); } } } } if(sCommand == "indent" || sCommand == "outdent"){ if(!htOptions){htOptions = {};} htOptions["bDontAddUndoHistory"] = true; } if((!htOptions || !htOptions["bDontAddUndoHistory"]) && !this._bOnlyCursorChanged){ if(/^justify*/i.test(sCommand)){ this.oUndoOption = {sSaveTarget:"BODY"}; }else if(sCommand === "insertorderedlist" || sCommand === "insertunorderedlist"){ this.oUndoOption = {bMustBlockContainer:true}; } this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", [sCommand, this.oUndoOption]); } if(this.oNavigator.ie){ if(this.oApp.getWYSIWYGDocument().selection.type === "Control"){ oSelection = this.oApp.getSelection(); oSelection.select(); } } if(sCommand == "insertorderedlist" || sCommand == "insertunorderedlist"){ this._insertBlankLine(); } }, $ON_EXECCOMMAND : function(sCommand, bUserInterface, vValue){ var bSelectedBlock = false; var htSelectedTDs = {}; var oSelection = this.oApp.getSelection(); bUserInterface = (bUserInterface == "" || bUserInterface)?bUserInterface:false; vValue = (vValue == "" || vValue)?vValue:false; this.oApp.exec("IS_SELECTED_TD_BLOCK",['bIsSelectedTd',htSelectedTDs]); bSelectedBlock = htSelectedTDs.bIsSelectedTd; if( bSelectedBlock){ if(sCommand == "indent"){ this.oApp.exec("SET_LINE_BLOCK_STYLE", [null, jindo.$Fn(this._indentMargin, this).bind()]); }else if(sCommand == "outdent"){ this.oApp.exec("SET_LINE_BLOCK_STYLE", [null, jindo.$Fn(this._outdentMargin, this).bind()]); }else{ this._setBlockExecCommand(sCommand, bUserInterface, vValue); } } else { switch(sCommand){ case "indent": case "outdent": this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", [sCommand]); var sBookmark = oSelection.placeStringBookmark(); if(sCommand === "indent"){ this.oApp.exec("SET_LINE_STYLE", [null, jindo.$Fn(this._indentMargin, this).bind(), {bDoNotSelect : true, bDontAddUndoHistory : true}]); }else{ this.oApp.exec("SET_LINE_STYLE", [null, jindo.$Fn(this._outdentMargin, this).bind(), {bDoNotSelect : true, bDontAddUndoHistory : true}]); } oSelection.moveToStringBookmark(sBookmark); oSelection.select(); oSelection.removeStringBookmark(sBookmark); setTimeout(jindo.$Fn(function(sCommand){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", [sCommand]); }, this).bind(sCommand), 25); break; case "justifyleft": case "justifycenter": case "justifyright": case "justifyfull": var oSelectionClone = this._extendBlock(); // FF this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); if(!!oSelectionClone){ oSelectionClone.select(); } break; default: //if(this.oNavigator.firefox){ //this.oEditingArea.execCommand("styleWithCSS", bUserInterface, false); //} this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); } } this._countClickCr(sCommand); }, $AFTER_EXECCOMMAND : function(sCommand, bUserInterface, vValue, htOptions){ if(this.elP1 && this.elP1.parentNode){ this.elP1.parentNode.removeChild(this.elP1); } if(this.elP2 && this.elP2.parentNode){ this.elP2.parentNode.removeChild(this.elP2); } if(/^insertorderedlist|insertunorderedlist$/i.test(sCommand)){ this._fixDocumentBR(); // Chrome/Safari this._fixCorruptedBlockQuote(sCommand === "insertorderedlist" ? "OL" : "UL"); // IE } if((/^justify*/i.test(sCommand))){ this._fixAlign(sCommand === "justifyfull" ? "justify" : sCommand.substring(7)); } if(sCommand == "indent" || sCommand == "outdent"){ if(!htOptions){htOptions = {};} htOptions["bDontAddUndoHistory"] = true; } if((!htOptions || !htOptions["bDontAddUndoHistory"]) && !this._bOnlyCursorChanged){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", [sCommand, this.oUndoOption]); } this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _removeSpanAlign : function(){ var oSelection = this.oApp.getSelection(), aNodes = oSelection.getNodes(), elNode = null; for(var i=0, nLen=aNodes.length; i<nLen; i++){ elNode = aNodes[i]; // [SMARTEDITORSUS-704] SPAN에서 적용된 Align을 제거 if(elNode.tagName && elNode.tagName === "SPAN"){ elNode.style.textAlign = ""; elNode.removeAttribute("align"); } } }, // [SMARTEDITORSUS-851] align, text-align을 fix해야 할 대상 노드를 찾음 _getAlignNode : function(elNode){ if(elNode.tagName && (elNode.tagName === "P" || elNode.tagName === "DIV")){ return elNode; } elNode = elNode.parentNode; while(elNode && elNode.tagName){ if(elNode.tagName === "P" || elNode.tagName === "DIV"){ return elNode; } elNode = elNode.parentNode; } }, _fixAlign : function(sAlign){ var oSelection = this.oApp.getSelection(), aNodes = [], elNode = null, elParentNode = null; var removeTableAlign = !this.oNavigator.ie ? function(){} : function(elNode){ if(elNode.tagName && elNode.tagName === "TABLE"){ elNode.removeAttribute("align"); return true; } return false; }; if(oSelection.collapsed){ aNodes[0] = oSelection.startContainer; // collapsed인 경우에는 getNodes의 결과는 [] }else{ aNodes = oSelection.getNodes(); } for(var i=0, nLen=aNodes.length; i<nLen; i++){ elNode = aNodes[i]; if(elNode.nodeType === 3){ elNode = elNode.parentNode; } if(elParentNode && (elNode === elParentNode || jindo.$Element(elNode).isChildOf(elParentNode))){ continue; } elParentNode = this._getAlignNode(elNode); if(elParentNode && elParentNode.align !== elParentNode.style.textAlign){ // [SMARTEDITORSUS-704] align 속성과 text-align 속성의 값을 맞춰줌 elParentNode.style.textAlign = sAlign; elParentNode.setAttribute("align", sAlign); } } }, _getDocumentBR : function(){ var i, nLen; // [COM-715] <Chrome/Safari> 요약글 삽입 > 더보기 영역에서 기호매기기, 번호매기기 설정할때마다 요약글 박스가 아래로 이동됨 // ExecCommand를 처리하기 전에 현재의 BR을 저장 this.aBRs = this.oApp.getWYSIWYGDocument().getElementsByTagName("BR"); this.aBeforeBRs = []; for(i=0, nLen=this.aBRs.length; i<nLen; i++){ this.aBeforeBRs[i] = this.aBRs[i]; } }, _fixDocumentBR : function(){ // [COM-715] ExecCommand가 처리된 후에 업데이트된 BR을 처리 전에 저장한 BR과 비교하여 생성된 BR을 제거 if(this.aBeforeBRs.length === this.aBRs.length){ // this.aBRs gets updated automatically when the document is updated return; } var waBeforeBRs = jindo.$A(this.aBeforeBRs), i, iLen = this.aBRs.length; for(i=iLen-1; i>=0; i--){ if(waBeforeBRs.indexOf(this.aBRs[i])<0){ this.aBRs[i].parentNode.removeChild(this.aBRs[i]); } } }, _setBlockExecCommand : function(sCommand, bUserInterface, vValue){ var aNodes, aChildrenNode, htSelectedTDs = {}; this.oSelection = this.oApp.getSelection(); this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ this.oSelection.selectNodeContents(aNodes[j]); this.oSelection.select(); if(this.oNavigator.firefox){ this.oEditingArea.execCommand("styleWithCSS", bUserInterface, false); //styleWithCSS는 ff전용임. } aChildrenNode = this.oSelection.getNodes(); for( var k = 0; k < aChildrenNode.length ; k++ ) { if(aChildrenNode[k].tagName == "UL" || aChildrenNode[k].tagName == "OL" ){ jindo.$Element(aChildrenNode[k]).css("color",vValue); } } this.oEditingArea.execCommand(sCommand, bUserInterface, vValue); } }, _indentMargin : function(elDiv){ var elTmp = elDiv, aAppend, i, nLen, elInsertTarget, elDeleteTarget, nCurMarginLeft; while(elTmp){ if(elTmp.tagName && elTmp.tagName === "LI"){ elDiv = elTmp; break; } elTmp = elTmp.parentNode; } if(elDiv.tagName === "LI"){ //<OL> // <OL> // <LI>22</LI> // </OL> // <LI>33</LI> //</OL> //와 같은 형태라면 33을 들여쓰기 했을 때, 상단의 silbling OL과 합쳐서 아래와 같이 만들어 줌. //<OL> // <OL> // <LI>22</LI> // <LI>33</LI> // </OL> //</OL> if(elDiv.previousSibling && elDiv.previousSibling.tagName && elDiv.previousSibling.tagName === elDiv.parentNode.tagName){ // 하단에 또다른 OL이 있어 아래와 같은 형태라면, //<OL> // <OL> // <LI>22</LI> // </OL> // <LI>33</LI> // <OL> // <LI>44</LI> // </OL> //</OL> //22,33,44를 합쳐서 아래와 같이 만들어 줌. //<OL> // <OL> // <LI>22</LI> // <LI>33</LI> // <LI>44</LI> // </OL> //</OL> if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName === elDiv.parentNode.tagName){ aAppend = [elDiv]; for(i=0, nLen=elDiv.nextSibling.childNodes.length; i<nLen; i++){ aAppend.push(elDiv.nextSibling.childNodes[i]); } elInsertTarget = elDiv.previousSibling; elDeleteTarget = elDiv.nextSibling; for(i=0, nLen=aAppend.length; i<nLen; i++){ elInsertTarget.insertBefore(aAppend[i], null); } elDeleteTarget.parentNode.removeChild(elDeleteTarget); }else{ elDiv.previousSibling.insertBefore(elDiv, null); } return; } //<OL> // <LI>22</LI> // <OL> // <LI>33</LI> // </OL> //</OL> //와 같은 형태라면 22을 들여쓰기 했을 때, 하단의 silbling OL과 합친다. if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName === elDiv.parentNode.tagName){ elDiv.nextSibling.insertBefore(elDiv, elDiv.nextSibling.firstChild); return; } elTmp = elDiv.parentNode.cloneNode(false); elDiv.parentNode.insertBefore(elTmp, elDiv); elTmp.appendChild(elDiv); return; } nCurMarginLeft = parseInt(elDiv.style.marginLeft, 10); if(!nCurMarginLeft){ nCurMarginLeft = 0; } nCurMarginLeft += this.nIndentSpacing; elDiv.style.marginLeft = nCurMarginLeft+"px"; }, _outdentMargin : function(elDiv){ var elTmp = elDiv, elParentNode, elInsertBefore, elNewParent, elInsertParent, oDoc, nCurMarginLeft; while(elTmp){ if(elTmp.tagName && elTmp.tagName === "LI"){ elDiv = elTmp; break; } elTmp = elTmp.parentNode; } if(elDiv.tagName === "LI"){ elParentNode = elDiv.parentNode; elInsertBefore = elDiv.parentNode; // LI를 적절 위치로 이동. // 위에 다른 li/ol/ul가 있는가? if(elDiv.previousSibling && elDiv.previousSibling.tagName && elDiv.previousSibling.tagName.match(/LI|UL|OL/)){ // 위아래로 sibling li/ol/ul가 있다면 ol/ul를 2개로 나누어야됨 if(elDiv.nextSibling && elDiv.nextSibling.tagName && elDiv.nextSibling.tagName.match(/LI|UL|OL/)){ elNewParent = elParentNode.cloneNode(false); while(elDiv.nextSibling){ elNewParent.insertBefore(elDiv.nextSibling, null); } elParentNode.parentNode.insertBefore(elNewParent, elParentNode.nextSibling); elInsertBefore = elNewParent; // 현재 LI가 마지막 LI라면 부모 OL/UL 하단에 삽입 }else{ elInsertBefore = elParentNode.nextSibling; } } elParentNode.parentNode.insertBefore(elDiv, elInsertBefore); // 내어쓰기 한 LI 외에 다른 LI가 존재 하지 않을 경우 부모 노드 지워줌 if(!elParentNode.innerHTML.match(/LI/i)){ elParentNode.parentNode.removeChild(elParentNode); } // OL이나 UL 위로까지 내어쓰기가 된 상태라면 LI를 벗겨냄 if(!elDiv.parentNode.tagName.match(/OL|UL/)){ elInsertParent = elDiv.parentNode; elInsertBefore = elDiv; // 내용물을 P로 감싸기 oDoc = this.oApp.getWYSIWYGDocument(); elInsertParent = oDoc.createElement("P"); elInsertBefore = null; elDiv.parentNode.insertBefore(elInsertParent, elDiv); while(elDiv.firstChild){ elInsertParent.insertBefore(elDiv.firstChild, elInsertBefore); } elDiv.parentNode.removeChild(elDiv); } return; } nCurMarginLeft = parseInt(elDiv.style.marginLeft, 10); if(!nCurMarginLeft){ nCurMarginLeft = 0; } nCurMarginLeft -= this.nIndentSpacing; if(nCurMarginLeft < 0){ nCurMarginLeft = 0; } elDiv.style.marginLeft = nCurMarginLeft+"px"; }, // Fix IE's execcommand bug // When insertorderedlist/insertunorderedlist is executed on a blockquote, the blockquote will "suck in" directly neighboring OL, UL's if there's any. // To prevent this, insert empty P tags right before and after the blockquote and remove them after the execution. // [SMARTEDITORSUS-793] Chrome 에서 동일한 이슈 발생, Chrome 은 빈 P 태그로는 처리되지 않으 &nbsp; 추가 _insertBlankLine : function(){ var oSelection = this.oApp.getSelection(); var elNode = oSelection.commonAncestorContainer; this.elP1 = null; this.elP2 = null; while(elNode){ if(elNode.tagName == "BLOCKQUOTE"){ this.elP1 = jindo.$("<p>&nbsp;</p>", this.oApp.getWYSIWYGDocument()); elNode.parentNode.insertBefore(this.elP1, elNode); this.elP2 = jindo.$("<p>&nbsp;</p>", this.oApp.getWYSIWYGDocument()); elNode.parentNode.insertBefore(this.elP2, elNode.nextSibling); break; } elNode = elNode.parentNode; } }, // Fix IE's execcommand bug // When insertorderedlist/insertunorderedlist is executed on a blockquote with all the child nodes selected, // eg:<blockquote>[selection starts here]blah...[selection ends here]</blockquote> // , IE will change the blockquote with the list tag and create <OL><OL><LI>blah...</LI></OL></OL>. // (two OL's or two UL's depending on which command was executed) // // It can also happen when the cursor is located at bogus positions like // * below blockquote when the blockquote is the last element in the document // // [IE] 인용구 안에서 글머리 기호를 적용했을 때, 인용구 밖에 적용된 번호매기기/글머리 기호가 인용구 안으로 빨려 들어가는 문제 처리 _fixCorruptedBlockQuote : function(sTagName){ var aNodes = this.oApp.getWYSIWYGDocument().getElementsByTagName(sTagName), elCorruptedBlockQuote, elTmpParent, elNewNode, aLists, i, nLen, nPos, el, oSelection; for(i=0, nLen=aNodes.length; i<nLen; i++){ if(aNodes[i].firstChild && aNodes[i].firstChild.tagName == sTagName){ elCorruptedBlockQuote = aNodes[i]; break; } } if(!elCorruptedBlockQuote){return;} elTmpParent = elCorruptedBlockQuote.parentNode; // (1) changing outerHTML will cause loss of the reference to the node, so remember the idx position here nPos = this._getPosIdx(elCorruptedBlockQuote); el = this.oApp.getWYSIWYGDocument().createElement("DIV"); el.innerHTML = elCorruptedBlockQuote.outerHTML.replace("<"+sTagName, "<BLOCKQUOTE"); elCorruptedBlockQuote.parentNode.insertBefore(el.firstChild, elCorruptedBlockQuote); elCorruptedBlockQuote.parentNode.removeChild(elCorruptedBlockQuote); // (2) and retrieve the new node here elNewNode = elTmpParent.childNodes[nPos]; // garbage <OL></OL> or <UL></UL> will be left over after setting the outerHTML, so remove it here. aLists = elNewNode.getElementsByTagName(sTagName); for(i=0, nLen=aLists.length; i<nLen; i++){ if(aLists[i].childNodes.length<1){ aLists[i].parentNode.removeChild(aLists[i]); } } oSelection = this.oApp.getEmptySelection(); oSelection.selectNodeContents(elNewNode); oSelection.collapseToEnd(); oSelection.select(); }, _getPosIdx : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){idx++;} return idx; }, _countClickCr : function(sCommand) { if (!sCommand.match(this.rxClickCr)) { return; } this.oApp.exec('MSG_NOTIFY_CLICKCR', [sCommand.replace(/^insert/i, '')]); }, _extendBlock : function(){ // [SMARTEDITORSUS-663] [FF] block단위로 확장하여 Range를 새로 지정해주는것이 원래 스펙이므로 // 해결을 위해서는 현재 선택된 부분을 Block으로 extend하여 execCommand API가 처리될 수 있도록 함 var oSelection = this.oApp.getSelection(), oStartContainer = oSelection.startContainer, oEndContainer = oSelection.endContainer, aChildImg = [], aSelectedImg = [], oSelectionClone = oSelection.cloneRange(); // <p><img><br/><img><br/><img></p> 일 때 이미지가 일부만 선택되면 발생 // - container 노드는 P 이고 container 노드의 자식노드 중 이미지가 여러개인데 선택된 이미지가 그 중 일부인 경우 if(!(oStartContainer === oEndContainer && oStartContainer.nodeType === 1 && oStartContainer.tagName === "P")){ return; } aChildImg = jindo.$A(oStartContainer.childNodes).filter(function(value, index, array){ return (value.nodeType === 1 && value.tagName === "IMG"); }).$value(); aSelectedImg = jindo.$A(oSelection.getNodes()).filter(function(value, index, array){ return (value.nodeType === 1 && value.tagName === "IMG"); }).$value(); if(aChildImg.length <= aSelectedImg.length){ return; } oSelection.selectNode(oStartContainer); oSelection.select(); return oSelectionClone; } }); //}
JavaScript
/** * ColorPicker Component * @author gony */ nhn.ColorPicker = jindo.$Class({ elem : null, huePanel : null, canvasType : "Canvas", _hsvColor : null, $init : function(oElement, oOptions) { this.elem = jindo.$Element(oElement).empty(); this.huePanel = null; this.cursor = jindo.$Element("<div>").css("overflow", "hidden"); this.canvasType = jindo.$(oElement).filters?"Filter":jindo.$("<canvas>").getContext?"Canvas":null; if(!this.canvasType) { return false; } this.option({ huePanel : null, huePanelType : "horizontal" }); this.option(oOptions); if (this.option("huePanel")) { this.huePanel = jindo.$Element(this.option("huePanel")).empty(); } // rgb this._hsvColor = this._hsv(0,100,100); // #FF0000 // event binding for(var name in this) { if (/^_on[A-Z][a-z]+[A-Z][a-z]+$/.test(name)) { this[name+"Fn"] = jindo.$Fn(this[name], this); } } this._onDownColorFn.attach(this.elem, "mousedown"); if (this.huePanel) { this._onDownHueFn.attach(this.huePanel, "mousedown"); } // paint this.paint(); }, rgb : function(rgb) { this.hsv(this._rgb2hsv(rgb.r, rgb.g, rgb.b)); }, hsv : function(hsv) { if (typeof hsv == "undefined") { return this._hsvColor; } var rgb = null; var w = this.elem.width(); var h = this.elem.height(); var cw = this.cursor.width(); var ch = this.cursor.height(); var x = 0, y = 0; if (this.huePanel) { rgb = this._hsv2rgb(hsv.h, 100, 100); this.elem.css("background", "#"+this._rgb2hex(rgb.r, rgb.g, rgb.b)); x = hsv.s/100 * w; y = (100-hsv.v)/100 * h; } else { var hw = w / 2; if (hsv.v > hsv.s) { hsv.v = 100; x = hsv.s/100 * hw; } else { hsv.s = 100; x = (100-hsv.v)/100 * hw + hw; } y = hsv.h/360 * h; } x = Math.max(Math.min(x-1,w-cw), 1); y = Math.max(Math.min(y-1,h-ch), 1); this.cursor.css({left:x+"px",top:y+"px"}); this._hsvColor = hsv; rgb = this._hsv2rgb(hsv.h, hsv.s, hsv.v); this.fireEvent("colorchange", {type:"colorchange", element:this, currentElement:this, rgbColor:rgb, hexColor:"#"+this._rgb2hex(rgb.r, rgb.g, rgb.b), hsvColor:hsv} ); }, paint : function() { if (this.huePanel) { // paint color panel this["_paintColWith"+this.canvasType](); // paint hue panel this["_paintHueWith"+this.canvasType](); } else { // paint color panel this["_paintOneWith"+this.canvasType](); } // draw cursor this.cursor.appendTo(this.elem); this.cursor.css({position:"absolute",top:"1px",left:"1px",background:"white",border:"1px solid black"}).width(3).height(3); this.hsv(this._hsvColor); }, _paintColWithFilter : function() { // white : left to right jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "100%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#FFFFFFFF',EndColorStr='#00FFFFFF')" }).appendTo(this.elem); // black : down to up jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "100%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#00000000',EndColorStr='#FF000000')" }).appendTo(this.elem); }, _paintColWithCanvas : function() { var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.elem.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var lin = null; var w = cvs.width(); var h = cvs.height(); // white : left to right lin = ctx.createLinearGradient(0,0,w,0); lin.addColorStop(0, "rgba(255,255,255,1)"); lin.addColorStop(1, "rgba(255,255,255,0)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); // black : down to top lin = ctx.createLinearGradient(0,0,0,h); lin.addColorStop(0, "rgba(0,0,0,0)"); lin.addColorStop(1, "rgba(0,0,0,1)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); }, _paintOneWithFilter : function() { var sp, ep, s_rgb, e_rgb, s_hex, e_hex; var h = this.elem.height(); for(var i=1; i < 7; i++) { sp = Math.floor((i-1)/6 * h); ep = Math.floor(i/6 * h); s_rgb = this._hsv2rgb((i-1)/6*360, 100, 100); e_rgb = this._hsv2rgb(i/6*360, 100, 100); s_hex = "#FF"+this._rgb2hex(s_rgb.r, s_rgb.g, s_rgb.b); e_hex = "#FF"+this._rgb2hex(e_rgb.r, e_rgb.g, e_rgb.b); jindo.$Element("<div>").css({ position : "absolute", left : 0, width : "100%", top : sp + "px", height : (ep-sp) + "px", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='"+s_hex+"',EndColorStr='"+e_hex+"')" }).appendTo(this.elem); } // white : left to right jindo.$Element("<div>").css({ position : "absolute", top : 0, left : 0, width : "50%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#FFFFFFFF',EndColorStr='#00FFFFFF')" }).appendTo(this.elem); // black : down to up jindo.$Element("<div>").css({ position : "absolute", top : 0, right : 0, width : "50%", height : "100%", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType=1,StartColorStr='#00000000',EndColorStr='#FF000000')" }).appendTo(this.elem); }, _paintOneWithCanvas : function() { var rgb = {r:0, g:0, b:0}; var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.elem.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var w = cvs.width(); var h = cvs.height(); var lin = ctx.createLinearGradient(0,0,0,h); for(var i=0; i < 7; i++) { rgb = this._hsv2rgb(i/6*360, 100, 100); lin.addColorStop(i/6, "rgb("+rgb.join(",")+")"); } ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); lin = ctx.createLinearGradient(0,0,w,0); lin.addColorStop(0, "rgba(255,255,255,1)"); lin.addColorStop(0.5, "rgba(255,255,255,0)"); lin.addColorStop(0.5, "rgba(0,0,0,0)"); lin.addColorStop(1, "rgba(0,0,0,1)"); ctx.fillStyle = lin; ctx.fillRect(0,0,w,h); }, _paintHueWithFilter : function() { var sp, ep, s_rgb, e_rgb, s_hex, e_hex; var vert = (this.option().huePanelType == "vertical"); var w = this.huePanel.width(); var h = this.huePanel.height(); var elDiv = null; var nPanelBorderWidth = parseInt(this.huePanel.css('borderWidth'), 10); if (!!isNaN(nPanelBorderWidth)) { nPanelBorderWidth = 0; } w -= nPanelBorderWidth * 2; // borderWidth를 제외한 내측 폭을 구함 for(var i=1; i < 7; i++) { sp = Math.floor((i-1)/6 * (vert?h:w)); ep = Math.floor(i/6 * (vert?h:w)); s_rgb = this._hsv2rgb((i-1)/6*360, 100, 100); e_rgb = this._hsv2rgb(i/6*360, 100, 100); s_hex = "#FF"+this._rgb2hex(s_rgb.r, s_rgb.g, s_rgb.b); e_hex = "#FF"+this._rgb2hex(e_rgb.r, e_rgb.g, e_rgb.b); elDiv = jindo.$Element("<div>").css({ position : "absolute", filter : "progid:DXImageTransform.Microsoft.Gradient(GradientType="+(vert?0:1)+",StartColorStr='"+s_hex+"',EndColorStr='"+e_hex+"')" }); var width = (ep - sp) + 1; // IE에서 폭을 넓혀주지 않으면 확대 시 벌어짐, 그래서 1px 보정 elDiv.appendTo(this.huePanel); elDiv.css(vert?"left":"top", 0).css(vert?"width":"height", '100%'); elDiv.css(vert?"top":"left", sp + "px").css(vert?"height":"width", width + "px"); } }, _paintHueWithCanvas : function() { var opt = this.option(), rgb; var vtc = (opt.huePanelType == "vertical"); var cvs = jindo.$Element("<canvas>").css({width:"100%",height:"100%"}); cvs.appendTo(this.huePanel.empty()); var ctx = cvs.attr("width", cvs.width()).attr("height", cvs.height()).$value().getContext("2d"); var lin = ctx.createLinearGradient(0,0,vtc?0:cvs.width(),vtc?cvs.height():0); for(var i=0; i < 7; i++) { rgb = this._hsv2rgb(i/6*360, 100, 100); lin.addColorStop(i/6, "rgb("+rgb.join(",")+")"); } ctx.fillStyle = lin; ctx.fillRect(0,0,cvs.width(),cvs.height()); }, _rgb2hsv : function(r,g,b) { var h = 0, s = 0, v = Math.max(r,g,b), min = Math.min(r,g,b), delta = v - min; s = (v ? delta/v : 0); if (s) { if (r == v) { h = 60 * (g - b) / delta; } else if (g == v) { h = 120 + 60 * (b - r) / delta; } else if (b == v) { h = 240 + 60 * (r - g) / delta; } if (h < 0) { h += 360; } } h = Math.floor(h); s = Math.floor(s * 100); v = Math.floor(v / 255 * 100); return this._hsv(h,s,v); }, _hsv2rgb : function(h,s,v) { h = (h % 360) / 60; s /= 100; v /= 100; var r=0, g=0, b=0; var i = Math.floor(h); var f = h-i; var p = v*(1-s); var q = v*(1-s*f); var t = v*(1-s*(1-f)); switch (i) { case 0: r=v; g=t; b=p; break; case 1: r=q; g=v; b=p; break; case 2: r=p; g=v; b=t; break; case 3: r=p; g=q; b=v; break; case 4: r=t; g=p; b=v; break; case 5: r=v; g=p; b=q;break; case 6: break; } r = Math.floor(r*255); g = Math.floor(g*255); b = Math.floor(b*255); return this._rgb(r,g,b); }, _rgb2hex : function(r,g,b) { r = r.toString(16); if (r.length == 1) { r = '0'+r; } g = g.toString(16); if (g.length==1) { g = '0'+g; } b = b.toString(16); if (b.length==1) { b = '0'+b; } return r+g+b; }, _hex2rgb : function(hex) { var m = hex.match(/#?([0-9a-f]{6}|[0-9a-f]{3})/i); if (m[1].length == 3) { m = m[1].match(/./g).filter(function(c) { return c+c; }); } else { m = m[1].match(/../g); } return { r : Number("0x" + m[0]), g : Number("0x" + m[1]), b : Number("0x" + m[2]) }; }, _rgb : function(r,g,b) { var ret = [r,g,b]; ret.r = r; ret.g = g; ret.b = b; return ret; }, _hsv : function(h,s,v) { var ret = [h,s,v]; ret.h = h; ret.s = s; ret.v = v; return ret; }, _onDownColor : function(e) { if (!e.mouse().left) { return false; } var pos = e.pos(); this._colPagePos = [pos.pageX, pos.pageY]; this._colLayerPos = [pos.layerX, pos.layerY]; this._onUpColorFn.attach(document, "mouseup"); this._onMoveColorFn.attach(document, "mousemove"); this._onMoveColor(e); }, _onUpColor : function(e) { this._onUpColorFn.detach(document, "mouseup"); this._onMoveColorFn.detach(document, "mousemove"); }, _onMoveColor : function(e) { var hsv = this._hsvColor; var pos = e.pos(); var x = this._colLayerPos[0] + (pos.pageX - this._colPagePos[0]); var y = this._colLayerPos[1] + (pos.pageY - this._colPagePos[1]); var w = this.elem.width(); var h = this.elem.height(); x = Math.max(Math.min(x, w), 0); y = Math.max(Math.min(y, h), 0); if (this.huePanel) { hsv.s = hsv[1] = x / w * 100; hsv.v = hsv[2] = (h - y) / h * 100; } else { hsv.h = y/h*360; var hw = w/2; if (x < hw) { hsv.s = x/hw * 100; hsv.v = 100; } else { hsv.s = 100; hsv.v = (w-x)/hw * 100; } } this.hsv(hsv); e.stop(); }, _onDownHue : function(e) { if (!e.mouse().left) { return false; } var pos = e.pos(); this._huePagePos = [pos.pageX, pos.pageY]; this._hueLayerPos = [pos.layerX, pos.layerY]; this._onUpHueFn.attach(document, "mouseup"); this._onMoveHueFn.attach(document, "mousemove"); this._onMoveHue(e); }, _onUpHue : function(e) { this._onUpHueFn.detach(document, "mouseup"); this._onMoveHueFn.detach(document, "mousemove"); }, _onMoveHue : function(e) { var hsv = this._hsvColor; var pos = e.pos(); var cur = 0, len = 0; var x = this._hueLayerPos[0] + (pos.pageX - this._huePagePos[0]); var y = this._hueLayerPos[1] + (pos.pageY - this._huePagePos[1]); if (this.option().huePanelType == "vertical") { cur = y; len = this.huePanel.height(); } else { cur = x; len = this.huePanel.width(); } hsv.h = hsv[0] = (Math.min(Math.max(cur, 0), len)/len * 360)%360; this.hsv(hsv); e.stop(); } }).extend(jindo.Component);
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the font color * @name hp_SE_FontColor.js */ nhn.husky.SE2M_FontColor = jindo.$Class({ name : "SE2M_FontColor", rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, $init : function(elAppContainer){ this._assignHTMLElements(elAppContainer); }, _assignHTMLElements : function(elAppContainer){ //@ec[ this.elLastUsed = jindo.$$.getSingle("BUTTON.husky_se2m_fontColor_lastUsed", elAppContainer); this.elDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_fontcolor_layer", elAppContainer); this.elPaletteHolder = jindo.$$.getSingle("DIV.husky_se2m_fontcolor_paletteHolder", this.elDropdownLayer); //@ec] this._setLastUsedFontColor("#000000"); }, $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["fontColorA", "click", "APPLY_LAST_USED_FONTCOLOR"]); this.oApp.exec("REGISTER_UI_EVENT", ["fontColorB", "click", "TOGGLE_FONTCOLOR_LAYER"]); }, //@lazyload_js APPLY_LAST_USED_FONTCOLOR,TOGGLE_FONTCOLOR_LAYER[ $ON_TOGGLE_FONTCOLOR_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.elDropdownLayer, null, "FONTCOLOR_LAYER_SHOWN", [], "FONTCOLOR_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['fontcolor']); }, $ON_FONTCOLOR_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["fontColorB"]); this.oApp.exec("SHOW_COLOR_PALETTE", ["APPLY_FONTCOLOR", this.elPaletteHolder]); }, $ON_FONTCOLOR_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["fontColorB"]); this.oApp.exec("RESET_COLOR_PALETTE", []); }, $ON_APPLY_LAST_USED_FONTCOLOR : function(){ this.oApp.exec("APPLY_FONTCOLOR", [this.sLastUsedColor]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['fontcolor']); }, $ON_APPLY_FONTCOLOR : function(sFontColor){ if(!this.rxColorPattern.test(sFontColor)){ alert(this.oApp.$MSG("SE_FontColor.invalidColorCode")); return; } this._setLastUsedFontColor(sFontColor); this.oApp.exec("SET_WYSIWYG_STYLE", [{"color":sFontColor}]); // [SMARTEDITORSUS-907] 모든 브라우저에서 SET_WYSIWYG_STYLE로 색상을 설정하도록 변경 // var oAgent = jindo.$Agent().navigator(); // if( oAgent.ie || oAgent.firefox ){ // [SMARTEDITORSUS-658] Firefox 추가 // this.oApp.exec("SET_WYSIWYG_STYLE", [{"color":sFontColor}]); // } else { // var bDontAddUndoHistory = false; // if(this.oApp.getSelection().collapsed){ // bDontAddUndoHistory = true; // } // this.oApp.exec("EXECCOMMAND", ["ForeColor", false, sFontColor, { "bDontAddUndoHistory" : bDontAddUndoHistory }]); // if(bDontAddUndoHistory){ // this.oApp.exec("RECORD_UNDO_ACTION", ["FONT COLOR", {bMustBlockElement : true}]); // } // } this.oApp.exec("HIDE_ACTIVE_LAYER"); }, //@lazyload_js] _setLastUsedFontColor : function(sFontColor){ this.sLastUsedColor = sFontColor; this.elLastUsed.style.backgroundColor = this.sLastUsedColor; } }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to detecting the style change * @name hp_SE_WYSIWYGStyleGetter.js */ nhn.husky.SE_WYSIWYGStyleGetter = jindo.$Class({ name : "SE_WYSIWYGStyleGetter", hKeyUp : null, getStyleInterval : 200, oStyleMap : { fontFamily : { type : "Value", css : "fontFamily" }, fontSize : { type : "Value", css : "fontSize" }, lineHeight : { type : "Value", css : "lineHeight", converter : function(sValue, oStyle){ if(!sValue.match(/px$/)){ return sValue; } return Math.ceil((parseInt(sValue, 10)/parseInt(oStyle.fontSize, 10))*10)/10; } }, bold : { command : "bold" }, underline : { command : "underline" }, italic : { command : "italic" }, lineThrough : { command : "strikethrough" }, superscript : { command : "superscript" }, subscript : { command : "subscript" }, justifyleft : { command : "justifyleft" }, justifycenter : { command : "justifycenter" }, justifyright : { command : "justifyright" }, justifyfull : { command : "justifyfull" }, orderedlist : { command : "insertorderedlist" }, unorderedlist : { command : "insertunorderedlist" } }, $init : function(){ this.oStyle = this._getBlankStyle(); }, $LOCAL_BEFORE_ALL : function(){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_MSG_APP_READY : function(){ this.oDocument = this.oApp.getWYSIWYGDocument(); this.oApp.exec("ADD_APP_PROPERTY", ["getCurrentStyle", jindo.$Fn(this.getCurrentStyle, this).bind()]); if(jindo.$Agent().navigator().safari || jindo.$Agent().navigator().chrome){ this.oStyleMap.textAlign = { type : "Value", css : "textAlign" }; } }, $ON_EVENT_EDITING_AREA_MOUSEUP : function(oEvnet){ /* if(this.hKeyUp){ clearTimeout(this.hKeyUp); } this.oApp.delayedExec("CHECK_STYLE_CHANGE", [], 100); */ this.oApp.exec("CHECK_STYLE_CHANGE"); }, $ON_EVENT_EDITING_AREA_KEYPRESS : function(oEvent){ // ctrl+a in FF triggers keypress event with keyCode 97, other browsers don't throw keypress event for ctrl+a var oKeyInfo; if(this.oApp.oNavigator.firefox){ oKeyInfo = oEvent.key(); if(oKeyInfo.ctrl && oKeyInfo.keyCode == 97){ return; } } if(this.bAllSelected){ this.bAllSelected = false; return; } /* // queryCommandState often fails to return correct result for Korean/Enter. So just ignore them. if(this.oApp.oNavigator.firefox && (oKeyInfo.keyCode == 229 || oKeyInfo.keyCode == 13)){ return; } */ this.oApp.exec("CHECK_STYLE_CHANGE"); //this.oApp.delayedExec("CHECK_STYLE_CHANGE", [], 0); }, $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ var oKeyInfo = oEvent.key(); // ctrl+a if((this.oApp.oNavigator.ie || this.oApp.oNavigator.firefox) && oKeyInfo.ctrl && oKeyInfo.keyCode == 65){ this.oApp.exec("RESET_STYLE_STATUS"); this.bAllSelected = true; return; } /* backspace 8 enter 13 page up 33 page down 34 end 35 home 36 left arrow 37 up arrow 38 right arrow 39 down arrow 40 insert 45 delete 46 */ // other key strokes are taken care by keypress event if(!(oKeyInfo.keyCode == 8 || (oKeyInfo.keyCode >= 33 && oKeyInfo.keyCode <= 40) || oKeyInfo.keyCode == 45 || oKeyInfo.keyCode == 46)) return; // take care of ctrl+a -> delete/bksp sequence if(this.bAllSelected){ // firefox will throw both keydown and keypress events for those input(keydown first), so let keypress take care of them if(this.oApp.oNavigator.firefox){ return; } this.bAllSelected = false; return; } this.oApp.exec("CHECK_STYLE_CHANGE"); }, $ON_CHECK_STYLE_CHANGE : function(){ this._getStyle(); }, $ON_RESET_STYLE_STATUS : function(){ this.oStyle = this._getBlankStyle(); var oBodyStyle = this._getStyleOf(this.oApp.getWYSIWYGDocument().body); this.oStyle.fontFamily = oBodyStyle.fontFamily; this.oStyle.fontSize = oBodyStyle.fontSize; this.oStyle["justifyleft"]="@^"; for(var sAttributeName in this.oStyle){ //this.oApp.exec("SET_STYLE_STATUS", [sAttributeName, this.oStyle[sAttributeName]]); this.oApp.exec("MSG_STYLE_CHANGED", [sAttributeName, this.oStyle[sAttributeName]]); } }, getCurrentStyle : function(){ return this.oStyle; }, _check_style_change : function(){ this.oApp.exec("CHECK_STYLE_CHANGE", []); }, _getBlankStyle : function(){ var oBlankStyle = {}; for(var attributeName in this.oStyleMap){ if(this.oStyleMap[attributeName].type == "Value"){ oBlankStyle[attributeName] = ""; }else{ oBlankStyle[attributeName] = 0; } } return oBlankStyle; }, _getStyle : function(){ var oStyle; if(nhn.CurrentSelection.isCollapsed()){ oStyle = this._getStyleOf(nhn.CurrentSelection.getCommonAncestorContainer()); }else{ var oSelection = this.oApp.getSelection(); var funcFilter = function(oNode){ if (!oNode.childNodes || oNode.childNodes.length == 0) return true; else return false; } var aBottomNodes = oSelection.getNodes(false, funcFilter); if(aBottomNodes.length == 0){ oStyle = this._getStyleOf(oSelection.commonAncestorContainer); }else{ oStyle = this._getStyleOf(aBottomNodes[0]); } } for(attributeName in oStyle){ if(this.oStyleMap[attributeName].converter){ oStyle[attributeName] = this.oStyleMap[attributeName].converter(oStyle[attributeName], oStyle); } if(this.oStyle[attributeName] != oStyle[attributeName]){ this.oApp.exec("MSG_STYLE_CHANGED", [attributeName, oStyle[attributeName]]); } } this.oStyle = oStyle; }, _getStyleOf : function(oNode){ var oStyle = this._getBlankStyle(); // this must not happen if(!oNode){ return oStyle; } if( oNode.nodeType == 3 ){ oNode = oNode.parentNode; }else if( oNode.nodeType == 9 ){ //document에는 css를 적용할 수 없음. oNode = oNode.body; } var welNode = jindo.$Element(oNode); var attribute, cssName; for(var styleName in this.oStyle){ attribute = this.oStyleMap[styleName]; if(attribute.type && attribute.type == "Value"){ try{ if(attribute.css){ var sValue = welNode.css(attribute.css); if(styleName == "fontFamily"){ sValue = sValue.split(/,/)[0]; } oStyle[styleName] = sValue; } else if(attribute.command){ oStyle[styleName] = this.oDocument.queryCommandState(attribute.command); } else { // todo } }catch(e){} }else{ if(attribute.command){ try{ if(this.oDocument.queryCommandState(attribute.command)){ oStyle[styleName] = "@^"; }else{ oStyle[styleName] = "@-"; } }catch(e){} }else{ // todo } } } switch(oStyle["textAlign"]){ case "left": oStyle["justifyleft"]="@^"; break; case "center": oStyle["justifycenter"]="@^"; break; case "right": oStyle["justifyright"]="@^"; break; case "justify": oStyle["justifyfull"]="@^"; break; } // IE에서는 기본 정렬이 queryCommandState로 넘어오지 않아서 정렬이 없다면, 왼쪽 정렬로 가정함 if(oStyle["justifyleft"]=="@-" && oStyle["justifycenter"]=="@-" && oStyle["justifyright"]=="@-" && oStyle["justifyfull"]=="@-"){oStyle["justifyleft"]="@^";} return oStyle; } }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations directly related to the color palette * @name hp_SE2M_ColorPalette.js */ nhn.husky.SE2M_ColorPalette = jindo.$Class({ name : "SE2M_ColorPalette", elAppContainer : null, bUseRecentColor : false, nLimitRecentColor : 17, rxRGBColorPattern : /rgb\((\d+), ?(\d+), ?(\d+)\)/i, rxColorPattern : /^#?[0-9a-fA-F]{6}$|^rgb\(\d+, ?\d+, ?\d+\)$/i, aRecentColor : [], // 최근 사용한 색 목록, 가장 최근에 등록한 색의 index가 가장 작음 URL_COLOR_LIST : "", URL_COLOR_ADD : "", URL_COLOR_UPDATE : "", sRecentColorTemp : "<li><button type=\"button\" title=\"{RGB_CODE}\" style=\"background:{RGB_CODE}\"><span><span>{RGB_CODE}</span></span></button></li>", $init : function(elAppContainer){ this.elAppContainer = elAppContainer; }, $ON_MSG_APP_READY : function(){}, _assignHTMLElements : function(oAppContainer){ var htConfiguration = nhn.husky.SE2M_Configuration.SE2M_ColorPalette; if(htConfiguration){ this.bUseRecentColor = htConfiguration.bUseRecentColor || false; this.URL_COLOR_ADD = htConfiguration.addColorURL || "http://api.se2.naver.com/1/colortable/TextAdd.nhn"; this.URL_COLOR_UPDATE = htConfiguration.updateColorURL || "http://api.se2.naver.com/1/colortable/TextUpdate.nhn"; this.URL_COLOR_LIST = htConfiguration.colorListURL || "http://api.se2.naver.com/1/colortable/TextList.nhn"; } this.elColorPaletteLayer = jindo.$$.getSingle("DIV.husky_se2m_color_palette", oAppContainer); this.elColorPaletteLayerColorPicker = jindo.$$.getSingle("DIV.husky_se2m_color_palette_colorpicker", this.elColorPaletteLayer); this.elRecentColorForm = jindo.$$.getSingle("form", this.elColorPaletteLayerColorPicker); this.elBackgroundColor = jindo.$$.getSingle("ul.husky_se2m_bgcolor_list", oAppContainer); this.elInputColorCode = jindo.$$.getSingle("INPUT.husky_se2m_cp_colorcode", this.elColorPaletteLayerColorPicker); this.elPreview = jindo.$$.getSingle("SPAN.husky_se2m_cp_preview", this.elColorPaletteLayerColorPicker); this.elCP_ColPanel = jindo.$$.getSingle("DIV.husky_se2m_cp_colpanel", this.elColorPaletteLayerColorPicker); this.elCP_HuePanel = jindo.$$.getSingle("DIV.husky_se2m_cp_huepanel", this.elColorPaletteLayerColorPicker); this.elCP_ColPanel.style.position = "relative"; this.elCP_HuePanel.style.position = "relative"; this.elColorPaletteLayerColorPicker.style.display = "none"; this.elMoreBtn = jindo.$$.getSingle("BUTTON.husky_se2m_color_palette_more_btn", this.elColorPaletteLayer); this.welMoreBtn = jindo.$Element(this.elMoreBtn); this.elOkBtn = jindo.$$.getSingle("BUTTON.husky_se2m_color_palette_ok_btn", this.elColorPaletteLayer); if(this.bUseRecentColor){ this.elColorPaletteLayerRecent = jindo.$$.getSingle("DIV.husky_se2m_color_palette_recent", this.elColorPaletteLayer); this.elRecentColor = jindo.$$.getSingle("ul.se2_pick_color", this.elColorPaletteLayerRecent); this.elDummyNode = jindo.$$.getSingle("ul.se2_pick_color > li", this.elColorPaletteLayerRecent) || null; this.elColorPaletteLayerRecent.style.display = "none"; } }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLElements(this.elAppContainer); if(this.elDummyNode){ jindo.$Element(jindo.$$.getSingle("ul.se2_pick_color > li", this.elColorPaletteLayerRecent)).leave(); } if( this.bUseRecentColor ){ this._ajaxRecentColor(this._ajaxRecentColorCallback); } this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "click", "EVENT_CLICK_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elBackgroundColor, "mouseover", "EVENT_MOUSEOVER_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "mouseover", "EVENT_MOUSEOVER_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elBackgroundColor, "mouseout", "EVENT_MOUSEOUT_COLOR_PALETTE"); this.oApp.registerBrowserEvent(this.elColorPaletteLayer, "mouseout", "EVENT_MOUSEOUT_COLOR_PALETTE"); }, $ON_EVENT_MOUSEOVER_COLOR_PALETTE : function(oEvent){ var elHovered = oEvent.element; while(elHovered && elHovered.tagName && elHovered.tagName.toLowerCase() != "li"){ elHovered = elHovered.parentNode; } //조건 추가-by cielo 2010.04.20 if(!elHovered || !elHovered.nodeType || elHovered.nodeType == 9){return;} if(elHovered.className == "" || (!elHovered.className) || typeof(elHovered.className) == 'undefined'){jindo.$Element(elHovered).addClass("hover");} }, $ON_EVENT_MOUSEOUT_COLOR_PALETTE : function(oEvent){ var elHovered = oEvent.element; while(elHovered && elHovered.tagName && elHovered.tagName.toLowerCase() != "li"){ elHovered = elHovered.parentNode; } if(!elHovered){return;} if(elHovered.className == "hover"){jindo.$Element(elHovered).removeClass("hover");} }, $ON_EVENT_CLICK_COLOR_PALETTE : function(oEvent){ var elClicked = oEvent.element; while(elClicked.tagName == "SPAN"){elClicked = elClicked.parentNode;} if(elClicked.tagName && elClicked.tagName == "BUTTON"){ if(elClicked == this.elMoreBtn){ this.oApp.exec("TOGGLE_COLOR_PICKER"); return; } this.oApp.exec("APPLY_COLOR", [elClicked]); } }, $ON_APPLY_COLOR : function(elButton){ var sColorCode = this.elInputColorCode.value, welColorParent = null; if(sColorCode.indexOf("#") == -1){ sColorCode = "#" + sColorCode; this.elInputColorCode.value = sColorCode; } // 입력 버튼인 경우 if(elButton == this.elOkBtn){ if(!this._verifyColorCode(sColorCode)){ this.elInputColorCode.value = ""; alert(this.oApp.$MSG("SE_Color.invalidColorCode")); this.elInputColorCode.focus(); return; } this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode,true]); return; } // 색상 버튼인 경우 welColorParent = jindo.$Element(elButton.parentNode.parentNode.parentNode); sColorCode = elButton.title; if(welColorParent.hasClass("husky_se2m_color_palette")){ // 템플릿 색상 적용 this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode,false]); }else if(welColorParent.hasClass("husky_se2m_color_palette_recent")){ // 최근 색상 적용 this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [sColorCode,true]); } }, $ON_RESET_COLOR_PALETTE : function(){ this._initColor(); }, $ON_TOGGLE_COLOR_PICKER : function(){ if(this.elColorPaletteLayerColorPicker.style.display == "none"){ this.oApp.exec("SHOW_COLOR_PICKER"); }else{ this.oApp.exec("HIDE_COLOR_PICKER"); } }, $ON_SHOW_COLOR_PICKER : function(){ this.elColorPaletteLayerColorPicker.style.display = ""; this.cpp = new nhn.ColorPicker(this.elCP_ColPanel, {huePanel:this.elCP_HuePanel}); var fn = jindo.$Fn(function(oEvent) { this.elPreview.style.backgroundColor = oEvent.hexColor; this.elInputColorCode.value = oEvent.hexColor; }, this).bind(); this.cpp.attach("colorchange", fn); this.$ON_SHOW_COLOR_PICKER = this._showColorPickerMain; this.$ON_SHOW_COLOR_PICKER(); }, $ON_HIDE_COLOR_PICKER : function(){ this.elColorPaletteLayerColorPicker.style.display = "none"; this.welMoreBtn.addClass("se2_view_more"); this.welMoreBtn.removeClass("se2_view_more2"); }, $ON_SHOW_COLOR_PALETTE : function(sCallbackCmd, oLayerContainer){ this.sCallbackCmd = sCallbackCmd; this.oLayerContainer = oLayerContainer; this.oLayerContainer.insertBefore(this.elColorPaletteLayer, null); this.elColorPaletteLayer.style.display = "block"; this.oApp.delayedExec("POSITION_TOOLBAR_LAYER", [this.elColorPaletteLayer.parentNode.parentNode], 0); }, $ON_HIDE_COLOR_PALETTE : function(){ this.elColorPaletteLayer.style.display = "none"; }, $ON_COLOR_PALETTE_APPLY_COLOR : function(sColorCode , bAddRecentColor){ bAddRecentColor = (!bAddRecentColor)? false : bAddRecentColor; sColorCode = this._getHexColorCode(sColorCode); //더보기 레이어에서 적용한 색상만 최근 사용한 색에 추가한다. if( this.bUseRecentColor && !!bAddRecentColor ){ this.oApp.exec("ADD_RECENT_COLOR", [sColorCode]); } this.oApp.exec(this.sCallbackCmd, [sColorCode]); }, $ON_EVENT_MOUSEUP_COLOR_PALETTE : function(oEvent){ var elButton = oEvent.element; if(! elButton.style.backgroundColor){return;} this.oApp.exec("COLOR_PALETTE_APPLY_COLOR", [elButton.style.backgroundColor,false]); }, $ON_ADD_RECENT_COLOR : function(sRGBCode){ var bAdd = (this.aRecentColor.length === 0); this._addRecentColor(sRGBCode); if(bAdd){ this._ajaxAddColor(); }else{ this._ajaxUpdateColor(); } this._redrawRecentColorElement(); }, _verifyColorCode : function(sColorCode){ return this.rxColorPattern.test(sColorCode); }, _getHexColorCode : function(sColorCode){ if(this.rxRGBColorPattern.test(sColorCode)){ var dec2Hex = function(sDec){ var sTmp = parseInt(sDec, 10).toString(16); if(sTmp.length<2){sTmp = "0"+sTmp;} return sTmp.toUpperCase(); }; var sR = dec2Hex(RegExp.$1); var sG = dec2Hex(RegExp.$2); var sB = dec2Hex(RegExp.$3); sColorCode = "#"+sR+sG+sB; } return sColorCode; }, _addRecentColor : function(sRGBCode){ var waRecentColor = jindo.$A(this.aRecentColor); waRecentColor = waRecentColor.refuse(sRGBCode); waRecentColor.unshift(sRGBCode); if(waRecentColor.length() > this.nLimitRecentColor){ waRecentColor.length(this.nLimitRecentColor); } this.aRecentColor = waRecentColor.$value(); }, _redrawRecentColorElement : function(){ var aRecentColorHtml = [], nRecentColor = this.aRecentColor.length, i; if(nRecentColor === 0){ return; } for(i=0; i<nRecentColor; i++){ aRecentColorHtml.push(this.sRecentColorTemp.replace(/\{RGB_CODE\}/gi, this.aRecentColor[i])); } this.elRecentColor.innerHTML = aRecentColorHtml.join(""); this.elColorPaletteLayerRecent.style.display = "block"; }, _ajaxAddColor : function(){ jindo.$Ajax(this.URL_COLOR_ADD, { type : "jsonp", onload: function(){} }).request({ text_key : "colortable", text_data : this.aRecentColor.join(",") }); }, _ajaxUpdateColor : function(){ jindo.$Ajax(this.URL_COLOR_UPDATE, { type : "jsonp", onload: function(){} }).request({ text_key : "colortable", text_data : this.aRecentColor.join(",") }); }, _showColorPickerMain : function(){ this._initColor(); this.elColorPaletteLayerColorPicker.style.display = ""; this.welMoreBtn.removeClass("se2_view_more"); this.welMoreBtn.addClass("se2_view_more2"); }, _initColor : function(){ if(this.cpp){this.cpp.rgb({r:0,g:0,b:0});} this.elPreview.style.backgroundColor = '#'+'000000'; this.elInputColorCode.value = '#'+'000000'; this.oApp.exec("HIDE_COLOR_PICKER"); }, _ajaxRecentColor : function(fCallback){ jindo.$Ajax(this.URL_COLOR_LIST, { type : "jsonp", onload : jindo.$Fn(fCallback, this).bind() }).request(); }, _ajaxRecentColorCallback : function(htResponse){ var aColorList = htResponse.json()["result"], waColorList, i, nLen; if(!aColorList || !!aColorList.error){ return; } waColorList = jindo.$A(aColorList).filter(this._verifyColorCode, this); if(waColorList.length() > this.nLimitRecentColor){ waColorList.length(this.nLimitRecentColor); } aColorList = waColorList.reverse().$value(); for(i = 0, nLen = aColorList.length; i < nLen; i++){ this._addRecentColor(this._getHexColorCode(aColorList[i])); } this._redrawRecentColorElement(); } }).extend(jindo.Component); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to changing the lineheight using layer * @name hp_SE2M_LineHeightWithLayerUI.js */ nhn.husky.SE2M_LineHeightWithLayerUI = jindo.$Class({ name : "SE2M_LineHeightWithLayerUI", $ON_MSG_APP_READY : function(){ this.oApp.exec("REGISTER_UI_EVENT", ["lineHeight", "click", "SE2M_TOGGLE_LINEHEIGHT_LAYER"]); }, //@lazyload_js SE2M_TOGGLE_LINEHEIGHT_LAYER[ _assignHTMLObjects : function(elAppContainer) { //this.elLineHeightSelect = jindo.$$.getSingle("SELECT.husky_seditor_ui_lineHeight_select", elAppContainer); this.oDropdownLayer = jindo.$$.getSingle("DIV.husky_se2m_lineHeight_layer", elAppContainer); this.aLIOptions = jindo.$A(jindo.$$("LI", this.oDropdownLayer)).filter(function(v,i,a){return (v.firstChild !== null);})._array; this.oInput = jindo.$$.getSingle("INPUT", this.oDropdownLayer); var tmp = jindo.$$.getSingle(".husky_se2m_lineHeight_direct_input", this.oDropdownLayer); tmp = jindo.$$("BUTTON", tmp); this.oBtn_up = tmp[0]; this.oBtn_down = tmp[1]; this.oBtn_ok = tmp[2]; this.oBtn_cancel = tmp[3]; }, $LOCAL_BEFORE_FIRST : function(){ this._assignHTMLObjects(this.oApp.htOptions.elAppContainer); this.oApp.exec("SE2_ATTACH_HOVER_EVENTS", [this.aLIOptions]); for(var i=0; i<this.aLIOptions.length; i++){ this.oApp.registerBrowserEvent(this.aLIOptions[i], "click", "SET_LINEHEIGHT_FROM_LAYER_UI", [this._getLineHeightFromLI(this.aLIOptions[i])]); } this.oApp.registerBrowserEvent(this.oBtn_up, "click", "SE2M_INC_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oBtn_down, "click", "SE2M_DEC_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oBtn_ok, "click", "SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT", []); this.oApp.registerBrowserEvent(this.oBtn_cancel, "click", "SE2M_CANCEL_LINEHEIGHT", []); this.oApp.registerBrowserEvent(this.oInput, "keydown", "EVENT_SE2M_LINEHEIGHT_KEYDOWN"); }, $ON_EVENT_SE2M_LINEHEIGHT_KEYDOWN : function(oEvent){ if (oEvent.key().enter){ this.oApp.exec("SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT"); oEvent.stop(); } }, $ON_SE2M_TOGGLE_LINEHEIGHT_LAYER : function(){ this.oApp.exec("TOGGLE_TOOLBAR_ACTIVE_LAYER", [this.oDropdownLayer, null, "LINEHEIGHT_LAYER_SHOWN", [], "LINEHEIGHT_LAYER_HIDDEN", []]); this.oApp.exec('MSG_NOTIFY_CLICKCR', ['lineheight']); }, $ON_SE2M_INC_LINEHEIGHT : function(){ this.oInput.value = parseInt(this.oInput.value, 10)||0; this.oInput.value++; }, $ON_SE2M_DEC_LINEHEIGHT : function(){ this.oInput.value = parseInt(this.oInput.value, 10)||0; if(this.oInput.value > 0){this.oInput.value--;} }, $ON_LINEHEIGHT_LAYER_SHOWN : function(){ this.oApp.exec("SELECT_UI", ["lineHeight"]); this.oInitialSelection = this.oApp.getSelection(); var nLineHeight = this.oApp.getLineStyle("lineHeight"); if(nLineHeight != null && nLineHeight !== 0){ this.oInput.value = (nLineHeight*100).toFixed(0); var elLi = this._getMatchingLI(this.oInput.value+"%"); if(elLi){jindo.$Element(elLi.firstChild).addClass("active");} }else{ this.oInput.value = ""; } }, $ON_LINEHEIGHT_LAYER_HIDDEN : function(){ this.oApp.exec("DESELECT_UI", ["lineHeight"]); this._clearOptionSelection(); }, $ON_SE2M_SET_LINEHEIGHT_FROM_DIRECT_INPUT : function(){ this._setLineHeightAndCloseLayer(this.oInput.value); }, $ON_SET_LINEHEIGHT_FROM_LAYER_UI : function(sValue){ this._setLineHeightAndCloseLayer(sValue); }, $ON_SE2M_CANCEL_LINEHEIGHT : function(){ this.oInitialSelection.select(); this.oApp.exec("HIDE_ACTIVE_LAYER"); }, _setLineHeightAndCloseLayer : function(sValue){ var nLineHeight = parseInt(sValue, 10)/100; if(nLineHeight>0){ this.oApp.exec("SET_LINE_STYLE", ["lineHeight", nLineHeight]); }else{ alert(this.oApp.$MSG("SE_LineHeight.invalidLineHeight")); } this.oApp.exec("SE2M_TOGGLE_LINEHEIGHT_LAYER", []); var oNavigator = jindo.$Agent().navigator(); if(oNavigator.chrome || oNavigator.safari){ this.oApp.exec("FOCUS"); // [SMARTEDITORSUS-654] } }, _getMatchingLI : function(sValue){ var elLi; sValue = sValue.toLowerCase(); for(var i=0; i<this.aLIOptions.length; i++){ elLi = this.aLIOptions[i]; if(this._getLineHeightFromLI(elLi).toLowerCase() == sValue){return elLi;} } return null; }, _getLineHeightFromLI : function(elLi){ return elLi.firstChild.firstChild.innerHTML; }, _clearOptionSelection : function(elLi){ for(var i=0; i<this.aLIOptions.length; i++){ jindo.$Element(this.aLIOptions[i].firstChild).removeClass("active"); } } //@lazyload_js] }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to setting/changing the line style * @name hp_SE_LineStyler.js */ nhn.husky.SE2M_LineStyler = jindo.$Class({ name : "SE2M_LineStyler", //@lazyload_js SE2M_TOGGLE_LINEHEIGHT_LAYER,SET_LINE_STYLE[ $ON_SE2M_TOGGLE_LINEHEIGHT_LAYER : function(){ this.oApp.exec("ADD_APP_PROPERTY", ["getLineStyle", jindo.$Fn(this.getLineStyle, this).bind()]); }, $ON_SET_LINE_STYLE : function(sStyleName, styleValue, htOptions){ this.oSelection = this.oApp.getSelection(); var nodes = this._getSelectedNodes(false); this.setLineStyle(sStyleName, styleValue, htOptions, nodes); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, $ON_SET_LINE_BLOCK_STYLE : function(sStyleName, styleValue, htOptions){ this.oSelection = this.oApp.getSelection(); this.setLineBlockStyle(sStyleName, styleValue, htOptions); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, getLineStyle : function(sStyle){ var nodes = this._getSelectedNodes(false); var curWrapper, prevWrapper; var sCurStyle, sStyleValue; if(nodes.length === 0){return null;} var iLength = nodes.length; if(iLength === 0){ sStyleValue = null; }else{ prevWrapper = this._getLineWrapper(nodes[0]); sStyleValue = this._getWrapperLineStyle(sStyle, prevWrapper); } var firstNode = this.oSelection.getStartNode(); if(sStyleValue != null){ for(var i=1; i<iLength; i++){ if(this._isChildOf(nodes[i], curWrapper)){continue;} if(!nodes[i]){continue;} curWrapper = this._getLineWrapper(nodes[i]); if(curWrapper == prevWrapper){continue;} sCurStyle = this._getWrapperLineStyle(sStyle, curWrapper); if(sCurStyle != sStyleValue){ sStyleValue = null; break; } prevWrapper = curWrapper; } } curWrapper = this._getLineWrapper(nodes[iLength-1]); var lastNode = this.oSelection.getEndNode(); selectText = jindo.$Fn(function(firstNode, lastNode){ this.oSelection.setEndNodes(firstNode, lastNode); this.oSelection.select(); this.oApp.exec("CHECK_STYLE_CHANGE", []); }, this).bind(firstNode, lastNode); setTimeout(selectText, 0); return sStyleValue; }, // height in percentage. For example pass 1 to set the line height to 100% and 1.5 to set it to 150% setLineStyle : function(sStyleName, styleValue, htOptions, nodes){ thisRef = this; var bWrapperCreated = false; function _setLineStyle(div, sStyleName, styleValue){ if(!div){ bWrapperCreated = true; // try to wrap with P first try{ div = thisRef.oSelection.surroundContentsWithNewNode("P"); // if the range contains a block-level tag, wrap it with a DIV }catch(e){ div = thisRef.oSelection.surroundContentsWithNewNode("DIV"); } } if(typeof styleValue == "function"){ styleValue(div); }else{ div.style[sStyleName] = styleValue; } if(div.childNodes.length === 0){ div.innerHTML = "&nbsp;"; } return div; } function isInBody(node){ while(node && node.tagName != "BODY"){ node = nhn.DOMFix.parentNode(node); } if(!node){return false;} return true; } if(nodes.length === 0){ return; } var curWrapper, prevWrapper; var iLength = nodes.length; if((!htOptions || !htOptions["bDontAddUndoHistory"])){ this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["LINE STYLE"]); } prevWrapper = this._getLineWrapper(nodes[0]); prevWrapper = _setLineStyle(prevWrapper, sStyleName, styleValue); var startNode = prevWrapper; var endNode = prevWrapper; for(var i=1; i<iLength; i++){ // Skip the node if a copy of the node were wrapped and the actual node no longer exists within the document. try{ if(!isInBody(nhn.DOMFix.parentNode(nodes[i]))){continue;} }catch(e){continue;} if(this._isChildOf(nodes[i], curWrapper)){continue;} curWrapper = this._getLineWrapper(nodes[i]); if(curWrapper == prevWrapper){continue;} curWrapper = _setLineStyle(curWrapper, sStyleName, styleValue); prevWrapper = curWrapper; } endNode = curWrapper || startNode; if(bWrapperCreated && (!htOptions || !htOptions.bDoNotSelect)) { setTimeout(jindo.$Fn(function(startNode, endNode, htOptions){ if(startNode == endNode){ this.oSelection.selectNodeContents(startNode); if(startNode.childNodes.length==1 && startNode.firstChild.tagName == "BR"){ this.oSelection.collapseToStart(); } }else{ this.oSelection.setEndNodes(startNode, endNode); } this.oSelection.select(); if((!htOptions || !htOptions["bDontAddUndoHistory"])){ this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["LINE STYLE"]); } }, this).bind(startNode, endNode, htOptions), 0); } }, /** * Block Style 적용 */ setLineBlockStyle : function(sStyleName, styleValue, htOptions) { var htSelectedTDs = {}; //var aTempNodes = aTextnodes = []; var aTempNodes = []; var aTextnodes = []; this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); var aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ this.oSelection.selectNode(aNodes[j]); aTempNodes = this.oSelection.getNodes(); for(var k = 0, m = 0; k < aTempNodes.length ; k++){ if(aTempNodes[k].nodeType == 3 || (aTempNodes[k].tagName == "BR" && k == 0)) { aTextnodes[m] = aTempNodes[k]; m ++; } } this.setLineStyle(sStyleName, styleValue, htOptions, aTextnodes); aTempNodes = aTextnodes = []; } }, getTextNodes : function(bSplitTextEndNodes, oSelection){ var txtFilter = function(oNode){ // 편집 중에 생겨난 빈 LI/P에도 스타일 먹이도록 포함함 if((oNode.nodeType == 3 && oNode.nodeValue != "\n" && oNode.nodeValue != "") || (oNode.tagName == "LI" && oNode.innerHTML == "") || (oNode.tagName == "P" && oNode.innerHTML == "")){ return true; }else{ return false; } }; return oSelection.getNodes(bSplitTextEndNodes, txtFilter); }, _getSelectedNodes : function(bDontUpdate){ if(!bDontUpdate){ this.oSelection = this.oApp.getSelection(); } // 페이지 최하단에 빈 LI 있을 경우 해당 LI 포함하도록 expand if(this.oSelection.endContainer.tagName == "LI" && this.oSelection.endOffset == 0 && this.oSelection.endContainer.innerHTML == ""){ this.oSelection.setEndAfter(this.oSelection.endContainer); } if(this.oSelection.collapsed){this.oSelection.selectNode(this.oSelection.commonAncestorContainer);} //var nodes = this.oSelection.getTextNodes(); var nodes = this.getTextNodes(false, this.oSelection); if(nodes.length === 0){ var tmp = this.oSelection.getStartNode(); if(tmp){ nodes[0] = tmp; }else{ var elTmp = this.oSelection._document.createTextNode("\u00A0"); this.oSelection.insertNode(elTmp); nodes = [elTmp]; } } return nodes; }, _getWrapperLineStyle : function(sStyle, div){ var sStyleValue = null; if(div && div.style[sStyle]){ sStyleValue = div.style[sStyle]; }else{ div = this.oSelection.commonAncesterContainer; while(div && !this.oSelection.rxLineBreaker.test(div.tagName)){ if(div && div.style[sStyle]){ sStyleValue = div.style[sStyle]; break; } div = nhn.DOMFix.parentNode(div); } } return sStyleValue; }, _isChildOf : function(node, container){ while(node && node.tagName != "BODY"){ if(node == container){return true;} node = nhn.DOMFix.parentNode(node); } return false; }, _getLineWrapper : function(node){ var oTmpSelection = this.oApp.getEmptySelection(); oTmpSelection.selectNode(node); var oLineInfo = oTmpSelection.getLineInfo(); var oStart = oLineInfo.oStart; var oEnd = oLineInfo.oEnd; var a, b; var breakerA, breakerB; var div = null; a = oStart.oNode; breakerA = oStart.oLineBreaker; b = oEnd.oNode; breakerB = oEnd.oLineBreaker; this.oSelection.setEndNodes(a, b); if(breakerA == breakerB){ if(breakerA.tagName == "P" || breakerA.tagName == "DIV" || breakerA.tagName == "LI"){ // if(breakerA.tagName == "P" || breakerA.tagName == "DIV"){ div = breakerA; }else{ this.oSelection.setEndNodes(breakerA.firstChild, breakerA.lastChild); } } return div; } //@lazyload_js] }); //}
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to styling the font * @name hp_SE_WYSIWYGStyler.js * @required SE_EditingArea_WYSIWYG, HuskyRangeManager */ nhn.husky.SE_WYSIWYGStyler = jindo.$Class({ name : "SE_WYSIWYGStyler", sBlankText : unescape("%uFEFF"), $init : function(){ var htBrowser = jindo.$Agent().navigator(); if(!htBrowser.ie || htBrowser.nativeVersion < 9 || document.documentMode < 9){ this._addCursorHolder = function(){}; } }, _addCursorHolder : function(oSelection, oSpan){ var oBody = this.oApp.getWYSIWYGDocument().body, oAncestor, welSpan = jindo.$Element(oSpan), sHtml, tmpTextNode; sHtml = oBody.innerHTML; oAncestor = oBody; if(sHtml === welSpan.outerHTML()){ tmpTextNode = oSelection._document.createTextNode(unescape("%uFEFF")); oAncestor.appendChild(tmpTextNode); return; } oAncestor = nhn.husky.SE2M_Utils.findAncestorByTagName("P", oSpan); if(!oAncestor){ return; } sHtml = oAncestor.innerHTML; if(sHtml.indexOf("&nbsp;") > -1){ return; } tmpTextNode = oSelection._document.createTextNode(unescape("%u00A0")); oAncestor.appendChild(tmpTextNode); }, $PRECONDITION : function(sFullCommand, aArgs){ return (this.oApp.getEditingMode() == "WYSIWYG"); }, $ON_SET_WYSIWYG_STYLE : function(oStyles){ var oSelection = this.oApp.getSelection(); var htSelectedTDs = {}; this.oApp.exec("IS_SELECTED_TD_BLOCK",['bIsSelectedTd',htSelectedTDs]); var bSelectedBlock = htSelectedTDs.bIsSelectedTd; // style cursor or !(selected block) if(oSelection.collapsed && !bSelectedBlock){ this.oApp.exec("RECORD_UNDO_ACTION", ["FONT STYLE", {bMustBlockElement : true}]); var oSpan, bNewSpan; var elCAC = oSelection.commonAncestorContainer; //var elCAC = nhn.CurrentSelection.getCommonAncestorContainer(); if(elCAC.nodeType == 3){ elCAC = elCAC.parentNode; } if(elCAC && elCAC.tagName == "SPAN" && (elCAC.innerHTML == "" || elCAC.innerHTML == this.sBlankText || elCAC.innerHTML == "&nbsp;")){ bNewSpan = false; oSpan = elCAC; }else{ bNewSpan = true; oSpan = this.oApp.getWYSIWYGDocument().createElement("SPAN"); } oSpan.innerHTML = this.sBlankText; var sValue; for(var sName in oStyles){ sValue = oStyles[sName]; if(typeof sValue != "string"){ continue; } oSpan.style[sName] = sValue; } if(bNewSpan){ if(oSelection.startContainer.tagName == "BODY" && oSelection.startOffset === 0){ var oVeryFirstNode = oSelection._getVeryFirstRealChild(this.oApp.getWYSIWYGDocument().body); var bAppendable = true; var elTmp = oVeryFirstNode.cloneNode(false); // some browsers may throw an exception for trying to set the innerHTML of BR/IMG tags try{ elTmp.innerHTML = "test"; if(elTmp.innerHTML != "test"){ bAppendable = false; } }catch(e){ bAppendable = false; } if(bAppendable && elTmp.nodeType == 1 && elTmp.tagName == "BR"){// [SMARTEDITORSUS-311] [FF4] Cursor Holder 인 BR 의 하위노드로 SPAN 을 추가하여 발생하는 문제 oSelection.selectNode(oVeryFirstNode); oSelection.collapseToStart(); oSelection.insertNode(oSpan); }else if(bAppendable && oVeryFirstNode.tagName != "IFRAME" && oVeryFirstNode.appendChild && typeof oVeryFirstNode.innerHTML == "string"){ oVeryFirstNode.appendChild(oSpan); }else{ oSelection.selectNode(oVeryFirstNode); oSelection.collapseToStart(); oSelection.insertNode(oSpan); } }else{ oSelection.collapseToStart(); oSelection.insertNode(oSpan); } }else{ oSelection = this.oApp.getEmptySelection(); } // [SMARTEDITORSUS-229] 새로 생성되는 SPAN 에도 취소선/밑줄 처리 추가 if(!!oStyles.color){ oSelection._checkTextDecoration(oSpan); } this._addCursorHolder(oSelection, oSpan); // [SMARTEDITORSUS-178] [IE9] 커서가 위로 올라가는 문제 oSelection.selectNodeContents(oSpan); oSelection.collapseToEnd(); oSelection._window.focus(); oSelection._window.document.body.focus(); oSelection.select(); // 영역으로 스타일이 잡혀 있는 경우(예:현재 커서가 B블럭 안에 존재) 해당 영역이 사라져 버리는 오류 발생해서 제거 // http://bts.nhncorp.com/nhnbts/browse/COM-912 /* var oCursorStyle = this.oApp.getCurrentStyle(); if(oCursorStyle.bold == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["bold"], 0); } if(oCursorStyle.underline == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["underline"], 0); } if(oCursorStyle.italic == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["italic"], 0); } if(oCursorStyle.lineThrough == "@^"){ this.oApp.delayedExec("EXECCOMMAND", ["strikethrough"], 0); } */ // FF3 will actually display %uFEFF when it is followed by a number AND certain font-family is used(like Gulim), so remove the character for FF3 //if(jindo.$Agent().navigator().firefox && jindo.$Agent().navigator().version == 3){ // FF4+ may have similar problems, so ignore the version number // [SMARTEDITORSUS-416] 커서가 올라가지 않도록 BR 을 살려둠 // if(jindo.$Agent().navigator().firefox){ // oSpan.innerHTML = ""; // } return; } this.oApp.exec("RECORD_UNDO_BEFORE_ACTION", ["FONT STYLE", {bMustBlockElement:true}]); if(bSelectedBlock){ var aNodes; this.oApp.exec("GET_SELECTED_TD_BLOCK",['aTdCells',htSelectedTDs]); aNodes = htSelectedTDs.aTdCells; for( var j = 0; j < aNodes.length ; j++){ oSelection.selectNodeContents(aNodes[j]); oSelection.styleRange(oStyles); oSelection.select(); } } else { var bCheckTextDecoration = !!oStyles.color; // [SMARTEDITORSUS-26] 취소선/밑줄 색상 적용 처리 var bIncludeLI = oStyles.fontSize || oStyles.fontFamily; oSelection.styleRange(oStyles, null, null, bIncludeLI, bCheckTextDecoration); // http://bts.nhncorp.com/nhnbts/browse/COM-964 // // In FF when, // 1) Some text was wrapped with a styling SPAN and a bogus BR is followed // eg: <span style="XXX">TEST</span><br> // 2) And some place outside the span is clicked. // // The text cursor will be located outside the SPAN like the following, // <span style="XXX">TEST</span>[CURSOR]<br> // // which is not what the user would expect // Desired result: <span style="XXX">TEST[CURSOR]</span><br> // // To make the cursor go inside the styling SPAN, remove the bogus BR when the styling SPAN is created. // -> Style TEST<br> as <span style="XXX">TEST</span> (remove unnecessary BR) // -> Cannot monitor clicks/cursor position real-time so make the contents error-proof instead. if(jindo.$Agent().navigator().firefox){ var aStyleParents = oSelection.aStyleParents; for(var i=0, nLen=aStyleParents.length; i<nLen; i++){ var elNode = aStyleParents[i]; if(elNode.nextSibling && elNode.nextSibling.tagName == "BR" && !elNode.nextSibling.nextSibling){ elNode.parentNode.removeChild(elNode.nextSibling); } } } oSelection._window.focus(); oSelection.select(); } this.oApp.exec("RECORD_UNDO_AFTER_ACTION", ["FONT STYLE", {bMustBlockElement:true}]); } }); //}
JavaScript
if(typeof window.nhn=='undefined'){window.nhn = {};} if (!nhn.husky){nhn.husky = {};} nhn.husky.oMockDebugger = { log_MessageStart: function() {}, log_MessageEnd: function() {}, log_MessageStepStart: function() {}, log_MessageStepEnd: function() {}, log_CallHandlerStart: function() {}, log_CallHandlerEnd: function() {}, handleException: function() {}, setApp: function() {} }; //{ /** * @fileOverview This file contains Husky framework core * @name HuskyCore.js */ nhn.husky.HuskyCore = jindo.$Class({ name : "HuskyCore", aCallerStack : null, $init : function(htOptions){ this.htOptions = htOptions||{}; if( this.htOptions.oDebugger ){ if( !nhn.husky.HuskyCore._cores ) { nhn.husky.HuskyCore._cores = []; nhn.husky.HuskyCore.getCore = function() { return nhn.husky.HuskyCore._cores; }; } nhn.husky.HuskyCore._cores.push(this); this.htOptions.oDebugger.setApp(this); } // To prevent processing a Husky message before all the plugins are registered and ready, // Queue up all the messages here until the application's status is changed to READY this.messageQueue = []; this.oMessageMap = {}; this.oDisabledMessage = {}; this.aPlugins = []; this.appStatus = nhn.husky.APP_STATUS.NOT_READY; this.aCallerStack = []; this._fnWaitForPluginReady = jindo.$Fn(this._waitForPluginReady, this).bind(); // Register the core as a plugin so it can receive messages this.registerPlugin(this); }, setDebugger: function(oDebugger) { this.htOptions.oDebugger = oDebugger; oDebugger.setApp(this); }, exec : function(msg, args, oEvent){ // If the application is not yet ready just queue the message if(this.appStatus == nhn.husky.APP_STATUS.NOT_READY){ this.messageQueue[this.messageQueue.length] = {'msg':msg, 'args':args, 'event':oEvent}; return true; } this.exec = this._exec; this.exec(msg, args, oEvent); }, delayedExec : function(msg, args, nDelay, oEvent){ var fExec = jindo.$Fn(this.exec, this).bind(msg, args, oEvent); setTimeout(fExec, nDelay); }, _exec : function(msg, args, oEvent){ return (this._exec = this.htOptions.oDebugger?this._execWithDebugger:this._execWithoutDebugger).call(this, msg, args, oEvent); }, _execWithDebugger : function(msg, args, oEvent){ this.htOptions.oDebugger.log_MessageStart(msg, args); var bResult = this._doExec(msg, args, oEvent); this.htOptions.oDebugger.log_MessageEnd(msg, args); return bResult; }, _execWithoutDebugger : function(msg, args, oEvent){ return this._doExec(msg, args, oEvent); }, _doExec : function(msg, args, oEvent){ var bContinue = false; if(!this.oDisabledMessage[msg]){ var allArgs = []; if(args && args.length){ var iLen = args.length; for(var i=0; i<iLen; i++){allArgs[i] = args[i];} } if(oEvent){allArgs[allArgs.length] = oEvent;} bContinue = this._execMsgStep("BEFORE", msg, allArgs); if(bContinue){bContinue = this._execMsgStep("ON", msg, allArgs);} if(bContinue){bContinue = this._execMsgStep("AFTER", msg, allArgs);} } return bContinue; }, registerPlugin : function(oPlugin){ if(!oPlugin){throw("An error occured in registerPlugin(): invalid plug-in");} oPlugin.nIdx = this.aPlugins.length; oPlugin.oApp = this; this.aPlugins[oPlugin.nIdx] = oPlugin; // If the plugin does not specify that it takes time to be ready, change the stauts to READY right away if(oPlugin.status != nhn.husky.PLUGIN_STATUS.NOT_READY){oPlugin.status = nhn.husky.PLUGIN_STATUS.READY;} // If run() function had been called already, need to recreate the message map if(this.appStatus != nhn.husky.APP_STATUS.NOT_READY){ for(var funcName in oPlugin){ if(funcName.match(/^\$(LOCAL|BEFORE|ON|AFTER)_/)){ this.addToMessageMap(funcName, oPlugin); } } } this.exec("MSG_PLUGIN_REGISTERED", [oPlugin]); return oPlugin.nIdx; }, disableMessage : function(sMessage, bDisable){this.oDisabledMessage[sMessage] = bDisable;}, registerBrowserEvent : function(obj, sEvent, sMessage, aParams, nDelay){ aParams = aParams || []; var func = (nDelay)?jindo.$Fn(this.delayedExec, this).bind(sMessage, aParams, nDelay):jindo.$Fn(this.exec, this).bind(sMessage, aParams); return jindo.$Fn(func, this).attach(obj, sEvent); }, run : function(htOptions){ this.htRunOptions = htOptions || {}; // Change the status from NOT_READY to let exec to process all the way this._changeAppStatus(nhn.husky.APP_STATUS.WAITING_FOR_PLUGINS_READY); // Process all the messages in the queue var iQueueLength = this.messageQueue.length; for(var i=0; i<iQueueLength; i++){ var curMsgAndArgs = this.messageQueue[i]; this.exec(curMsgAndArgs.msg, curMsgAndArgs.args, curMsgAndArgs.event); } this._fnWaitForPluginReady(); }, acceptLocalBeforeFirstAgain : function(oPlugin, bAccept){ // LOCAL_BEFORE_FIRST will be fired again if oPlugin._husky_bRun == false oPlugin._husky_bRun = !bAccept; }, // Use this also to update the mapping createMessageMap : function(sMsgHandler){ this.oMessageMap[sMsgHandler] = []; var nLen = this.aPlugins.length; for(var i=0; i<nLen; i++){this._doAddToMessageMap(sMsgHandler, this.aPlugins[i]);} }, addToMessageMap : function(sMsgHandler, oPlugin){ // cannot "ADD" unless the map is already created. // the message will be added automatically to the mapping when it is first passed anyways, so do not add now if(!this.oMessageMap[sMsgHandler]){return;} this._doAddToMessageMap(sMsgHandler, oPlugin); }, _changeAppStatus : function(appStatus){ this.appStatus = appStatus; // Initiate MSG_APP_READY if the application's status is being switched to READY if(this.appStatus == nhn.husky.APP_STATUS.READY){this.exec("MSG_APP_READY");} }, _execMsgStep : function(sMsgStep, sMsg, args){ return (this._execMsgStep = this.htOptions.oDebugger?this._execMsgStepWithDebugger:this._execMsgStepWithoutDebugger).call(this, sMsgStep, sMsg, args); }, _execMsgStepWithDebugger : function(sMsgStep, sMsg, args){ this.htOptions.oDebugger.log_MessageStepStart(sMsgStep, sMsg, args); var bStatus = this._execMsgHandler("$"+sMsgStep+"_"+sMsg, args); this.htOptions.oDebugger.log_MessageStepEnd(sMsgStep, sMsg, args); return bStatus; }, _execMsgStepWithoutDebugger : function(sMsgStep, sMsg, args){ return this._execMsgHandler ("$"+sMsgStep+"_"+sMsg, args); }, _execMsgHandler : function(sMsgHandler, args){ var i; if(!this.oMessageMap[sMsgHandler]){ this.createMessageMap(sMsgHandler); } var aPlugins = this.oMessageMap[sMsgHandler]; var iNumOfPlugins = aPlugins.length; if(iNumOfPlugins === 0){return true;} var bResult = true; // two similar codes were written twice due to the performace. if(sMsgHandler.match(/^\$(BEFORE|ON|AFTER)_MSG_APP_READY$/)){ for(i=0; i<iNumOfPlugins; i++){ if(this._execHandler(aPlugins[i], sMsgHandler, args) === false){ bResult = false; break; } } }else{ for(i=0; i<iNumOfPlugins; i++){ if(!aPlugins[i]._husky_bRun){ aPlugins[i]._husky_bRun = true; if(typeof aPlugins[i].$LOCAL_BEFORE_FIRST == "function" && this._execHandler(aPlugins[i], "$LOCAL_BEFORE_FIRST", [sMsgHandler, args]) === false){continue;} } if(typeof aPlugins[i].$LOCAL_BEFORE_ALL == "function"){ if(this._execHandler(aPlugins[i], "$LOCAL_BEFORE_ALL", [sMsgHandler, args]) === false){continue;} } if(this._execHandler(aPlugins[i], sMsgHandler, args) === false){ bResult = false; break; } } } return bResult; }, _execHandler : function(oPlugin, sHandler, args){ return (this._execHandler = this.htOptions.oDebugger?this._execHandlerWithDebugger:this._execHandlerWithoutDebugger).call(this, oPlugin, sHandler, args); }, _execHandlerWithDebugger : function(oPlugin, sHandler, args){ this.htOptions.oDebugger.log_CallHandlerStart(oPlugin, sHandler, args); var bResult; try{ this.aCallerStack.push(oPlugin); bResult = oPlugin[sHandler].apply(oPlugin, args); this.aCallerStack.pop(); }catch(e){ this.htOptions.oDebugger.handleException(e); bResult = false; } this.htOptions.oDebugger.log_CallHandlerEnd(oPlugin, sHandler, args); return bResult; }, _execHandlerWithoutDebugger : function(oPlugin, sHandler, args){ this.aCallerStack.push(oPlugin); var bResult = oPlugin[sHandler].apply(oPlugin, args); this.aCallerStack.pop(); return bResult; }, _doAddToMessageMap : function(sMsgHandler, oPlugin){ if(typeof oPlugin[sMsgHandler] != "function"){return;} var aMap = this.oMessageMap[sMsgHandler]; // do not add if the plugin is already in the mapping for(var i=0, iLen=aMap.length; i<iLen; i++){ if(this.oMessageMap[sMsgHandler][i] == oPlugin){return;} } this.oMessageMap[sMsgHandler][i] = oPlugin; }, _waitForPluginReady : function(){ var bAllReady = true; for(var i=0; i<this.aPlugins.length; i++){ if(this.aPlugins[i].status == nhn.husky.PLUGIN_STATUS.NOT_READY){ bAllReady = false; break; } } if(bAllReady){ this._changeAppStatus(nhn.husky.APP_STATUS.READY); }else{ setTimeout(this._fnWaitForPluginReady, 100); } } }); //} nhn.husky.APP_STATUS = { 'NOT_READY' : 0, 'WAITING_FOR_PLUGINS_READY' : 1, 'READY' : 2 }; nhn.husky.PLUGIN_STATUS = { 'NOT_READY' : 0, 'READY' : 1 };
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that bridges the HuskyRange function * @name hp_HuskyRangeManager.js */ nhn.husky.HuskyRangeManager = jindo.$Class({ name : "HuskyRangeManager", oWindow : null, $init : function(win){ this.oWindow = win || window; }, $BEFORE_MSG_APP_READY : function(){ if(this.oWindow && this.oWindow.tagName == "IFRAME"){ this.oWindow = this.oWindow.contentWindow; nhn.CurrentSelection.setWindow(this.oWindow); } this.oApp.exec("ADD_APP_PROPERTY", ["getSelection", jindo.$Fn(this.getSelection, this).bind()]); this.oApp.exec("ADD_APP_PROPERTY", ["getEmptySelection", jindo.$Fn(this.getEmptySelection, this).bind()]); }, $ON_SET_EDITING_WINDOW : function(oWindow){ this.oWindow = oWindow; }, getEmptySelection : function(oWindow){ var oHuskyRange = new nhn.HuskyRange(oWindow || this.oWindow); return oHuskyRange; }, getSelection : function(oWindow){ this.oApp.exec("RESTORE_IE_SELECTION", []); var oHuskyRange = this.getEmptySelection(oWindow); // this may throw an exception if the selected is area is not yet shown try{ oHuskyRange.setFromSelection(); }catch(e){} return oHuskyRange; } }); //}
JavaScript
if(typeof window.nhn=='undefined'){window.nhn = {};} nhn.CurrentSelection_IE = function(){ this.getCommonAncestorContainer = function(){ try{ this._oSelection = this._document.selection; if(this._oSelection.type == "Control"){ return this._oSelection.createRange().item(0); }else{ return this._oSelection.createRangeCollection().item(0).parentElement(); } }catch(e){ return this._document.body; } }; this.isCollapsed = function(){ this._oSelection = this._document.selection; return this._oSelection.type == "None"; }; }; nhn.CurrentSelection_FF = function(){ this.getCommonAncestorContainer = function(){ return this._getSelection().commonAncestorContainer; }; this.isCollapsed = function(){ var oSelection = this._window.getSelection(); if(oSelection.rangeCount<1){ return true; } return oSelection.getRangeAt(0).collapsed; }; this._getSelection = function(){ try{ return this._window.getSelection().getRangeAt(0); }catch(e){ return this._document.createRange(); } }; }; nhn.CurrentSelection = new (jindo.$Class({ $init : function(){ var oAgentInfo = jindo.$Agent().navigator(); if(oAgentInfo.ie){ nhn.CurrentSelection_IE.apply(this); }else{ nhn.CurrentSelection_FF.apply(this); } }, setWindow : function(oWin){ this._window = oWin; this._document = oWin.document; } }))(); /** * @fileOverview This file contains a cross-browser implementation of W3C's DOM Range * @name W3CDOMRange.js */ nhn.W3CDOMRange = jindo.$Class({ $init : function(win){ this.reset(win); }, reset : function(win){ this._window = win; this._document = this._window.document; this.collapsed = true; this.commonAncestorContainer = this._document.body; this.endContainer = this._document.body; this.endOffset = 0; this.startContainer = this._document.body; this.startOffset = 0; this.oBrowserSelection = new nhn.BrowserSelection(this._window); this.selectionLoaded = this.oBrowserSelection.selectionLoaded; }, cloneContents : function(){ var oClonedContents = this._document.createDocumentFragment(); var oTmpContainer = this._document.createDocumentFragment(); var aNodes = this._getNodesInRange(); if(aNodes.length < 1){return oClonedContents;} var oClonedContainers = this._constructClonedTree(aNodes, oTmpContainer); // oTopContainer = aNodes[aNodes.length-1].parentNode and this is not part of the initial array and only those child nodes should be cloned var oTopContainer = oTmpContainer.firstChild; if(oTopContainer){ var elCurNode = oTopContainer.firstChild; var elNextNode; while(elCurNode){ elNextNode = elCurNode.nextSibling; oClonedContents.appendChild(elCurNode); elCurNode = elNextNode; } } oClonedContainers = this._splitTextEndNodes({oStartContainer: oClonedContainers.oStartContainer, iStartOffset: this.startOffset, oEndContainer: oClonedContainers.oEndContainer, iEndOffset: this.endOffset}); if(oClonedContainers.oStartContainer && oClonedContainers.oStartContainer.previousSibling){ nhn.DOMFix.parentNode(oClonedContainers.oStartContainer).removeChild(oClonedContainers.oStartContainer.previousSibling); } if(oClonedContainers.oEndContainer && oClonedContainers.oEndContainer.nextSibling){ nhn.DOMFix.parentNode(oClonedContainers.oEndContainer).removeChild(oClonedContainers.oEndContainer.nextSibling); } return oClonedContents; }, _constructClonedTree : function(aNodes, oClonedParentNode){ var oClonedStartContainer = null; var oClonedEndContainer = null; var oStartContainer = this.startContainer; var oEndContainer = this.endContainer; var _recurConstructClonedTree = function(aAllNodes, iCurIdx, oClonedParentNode){ if(iCurIdx < 0){return iCurIdx;} var iChildIdx = iCurIdx-1; var oCurNodeCloneWithChildren = aAllNodes[iCurIdx].cloneNode(false); if(aAllNodes[iCurIdx] == oStartContainer){oClonedStartContainer = oCurNodeCloneWithChildren;} if(aAllNodes[iCurIdx] == oEndContainer){oClonedEndContainer = oCurNodeCloneWithChildren;} while(iChildIdx >= 0 && nhn.DOMFix.parentNode(aAllNodes[iChildIdx]) == aAllNodes[iCurIdx]){ iChildIdx = this._recurConstructClonedTree(aAllNodes, iChildIdx, oCurNodeCloneWithChildren); } // this may trigger an error message in IE when an erroneous script is inserted oClonedParentNode.insertBefore(oCurNodeCloneWithChildren, oClonedParentNode.firstChild); return iChildIdx; }; this._recurConstructClonedTree = _recurConstructClonedTree; aNodes[aNodes.length] = nhn.DOMFix.parentNode(aNodes[aNodes.length-1]); this._recurConstructClonedTree(aNodes, aNodes.length-1, oClonedParentNode); return {oStartContainer: oClonedStartContainer, oEndContainer: oClonedEndContainer}; }, cloneRange : function(){ return this._copyRange(new nhn.W3CDOMRange(this._window)); }, _copyRange : function(oClonedRange){ oClonedRange.collapsed = this.collapsed; oClonedRange.commonAncestorContainer = this.commonAncestorContainer; oClonedRange.endContainer = this.endContainer; oClonedRange.endOffset = this.endOffset; oClonedRange.startContainer = this.startContainer; oClonedRange.startOffset = this.startOffset; oClonedRange._document = this._document; return oClonedRange; }, collapse : function(toStart){ if(toStart){ this.endContainer = this.startContainer; this.endOffset = this.startOffset; }else{ this.startContainer = this.endContainer; this.startOffset = this.endOffset; } this._updateRangeInfo(); }, compareBoundaryPoints : function(how, sourceRange){ switch(how){ case nhn.W3CDOMRange.START_TO_START: return this._compareEndPoint(this.startContainer, this.startOffset, sourceRange.startContainer, sourceRange.startOffset); case nhn.W3CDOMRange.START_TO_END: return this._compareEndPoint(this.endContainer, this.endOffset, sourceRange.startContainer, sourceRange.startOffset); case nhn.W3CDOMRange.END_TO_END: return this._compareEndPoint(this.endContainer, this.endOffset, sourceRange.endContainer, sourceRange.endOffset); case nhn.W3CDOMRange.END_TO_START: return this._compareEndPoint(this.startContainer, this.startOffset, sourceRange.endContainer, sourceRange.endOffset); } }, _findBody : function(oNode){ if(!oNode){return null;} while(oNode){ if(oNode.tagName == "BODY"){return oNode;} oNode = nhn.DOMFix.parentNode(oNode); } return null; }, _compareEndPoint : function(oContainerA, iOffsetA, oContainerB, iOffsetB){ return this.oBrowserSelection.compareEndPoints(oContainerA, iOffsetA, oContainerB, iOffsetB); var iIdxA, iIdxB; if(!oContainerA || this._findBody(oContainerA) != this._document.body){ oContainerA = this._document.body; iOffsetA = 0; } if(!oContainerB || this._findBody(oContainerB) != this._document.body){ oContainerB = this._document.body; iOffsetB = 0; } var compareIdx = function(iIdxA, iIdxB){ // iIdxX == -1 when the node is the commonAncestorNode // if iIdxA == -1 // -> [[<nodeA>...<nodeB></nodeB>]]...</nodeA> // if iIdxB == -1 // -> <nodeB>...[[<nodeA></nodeA>...</nodeB>]] if(iIdxB == -1){iIdxB = iIdxA+1;} if(iIdxA < iIdxB){return -1;} if(iIdxA == iIdxB){return 0;} return 1; }; var oCommonAncestor = this._getCommonAncestorContainer(oContainerA, oContainerB); // ================================================================================================================================================ // Move up both containers so that both containers are direct child nodes of the common ancestor node. From there, just compare the offset // Add 0.5 for each contaienrs that has "moved up" since the actual node is wrapped by 1 or more parent nodes and therefore its position is somewhere between idx & idx+1 // <COMMON_ANCESTOR>NODE1<P>NODE2</P>NODE3</COMMON_ANCESTOR> // The position of NODE2 in COMMON_ANCESTOR is somewhere between after NODE1(idx1) and before NODE3(idx2), so we let that be 1.5 // container node A in common ancestor container var oNodeA = oContainerA; var oTmpNode = null; if(oNodeA != oCommonAncestor){ while((oTmpNode = nhn.DOMFix.parentNode(oNodeA)) != oCommonAncestor){oNodeA = oTmpNode;} iIdxA = this._getPosIdx(oNodeA)+0.5; }else{ iIdxA = iOffsetA; } // container node B in common ancestor container var oNodeB = oContainerB; if(oNodeB != oCommonAncestor){ while((oTmpNode = nhn.DOMFix.parentNode(oNodeB)) != oCommonAncestor){oNodeB = oTmpNode;} iIdxB = this._getPosIdx(oNodeB)+0.5; }else{ iIdxB = iOffsetB; } return compareIdx(iIdxA, iIdxB); }, _getCommonAncestorContainer : function(oNode1, oNode2){ oNode1 = oNode1 || this.startContainer; oNode2 = oNode2 || this.endContainer; var oComparingNode = oNode2; while(oNode1){ while(oComparingNode){ if(oNode1 == oComparingNode){return oNode1;} oComparingNode = nhn.DOMFix.parentNode(oComparingNode); } oComparingNode = oNode2; oNode1 = nhn.DOMFix.parentNode(oNode1); } return this._document.body; }, deleteContents : function(){ if(this.collapsed){return;} this._splitTextEndNodesOfTheRange(); var aNodes = this._getNodesInRange(); if(aNodes.length < 1){return;} var oPrevNode = aNodes[0].previousSibling; while(oPrevNode && this._isBlankTextNode(oPrevNode)){oPrevNode = oPrevNode.previousSibling;} var oNewStartContainer, iNewOffset = -1; if(!oPrevNode){ oNewStartContainer = nhn.DOMFix.parentNode(aNodes[0]); iNewOffset = 0; } for(var i=0; i<aNodes.length; i++){ var oNode = aNodes[i]; if(!oNode.firstChild || this._isAllChildBlankText(oNode)){ if(oNewStartContainer == oNode){ iNewOffset = this._getPosIdx(oNewStartContainer); oNewStartContainer = nhn.DOMFix.parentNode(oNode); } nhn.DOMFix.parentNode(oNode).removeChild(oNode); }else{ // move the starting point to out of the parent container if the starting point of parent container is meant to be removed // [<span>A]B</span> // -> []<span>B</span> // without these lines, the result would yeild to // -> <span>[]B</span> if(oNewStartContainer == oNode && iNewOffset === 0){ iNewOffset = this._getPosIdx(oNewStartContainer); oNewStartContainer = nhn.DOMFix.parentNode(oNode); } } } if(!oPrevNode){ this.setStart(oNewStartContainer, iNewOffset, true, true); }else{ if(oPrevNode.tagName == "BODY"){ this.setStartBefore(oPrevNode, true); }else{ this.setStartAfter(oPrevNode, true); } } this.collapse(true); }, extractContents : function(){ var oClonedContents = this.cloneContents(); this.deleteContents(); return oClonedContents; }, getInsertBeforeNodes : function(){ var oFirstNode = null; var oParentContainer; if(this.startContainer.nodeType == "3"){ oParentContainer = nhn.DOMFix.parentNode(this.startContainer); if(this.startContainer.nodeValue.length <= this.startOffset){ oFirstNode = this.startContainer.nextSibling; }else{ oFirstNode = this.startContainer.splitText(this.startOffset); } }else{ oParentContainer = this.startContainer; oFirstNode = nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } if(!oFirstNode || !nhn.DOMFix.parentNode(oFirstNode)){oFirstNode = null;} return {elParent: oParentContainer, elBefore: oFirstNode}; }, insertNode : function(newNode){ var oInsertBefore = this.getInsertBeforeNodes(); oInsertBefore.elParent.insertBefore(newNode, oInsertBefore.elBefore); this.setStartBefore(newNode); }, selectNode : function(refNode){ this.reset(this._window); this.setStartBefore(refNode); this.setEndAfter(refNode); }, selectNodeContents : function(refNode){ this.reset(this._window); this.setStart(refNode, 0, true); this.setEnd(refNode, nhn.DOMFix.childNodes(refNode).length); }, _endsNodeValidation : function(oNode, iOffset){ if(!oNode || this._findBody(oNode) != this._document.body){throw new Error("INVALID_NODE_TYPE_ERR oNode is not part of current document");} if(oNode.nodeType == 3){ if(iOffset > oNode.nodeValue.length){iOffset = oNode.nodeValue.length;} }else{ if(iOffset > nhn.DOMFix.childNodes(oNode).length){iOffset = nhn.DOMFix.childNodes(oNode).length;} } return iOffset; }, setEnd : function(refNode, offset, bSafe, bNoUpdate){ if(!bSafe){offset = this._endsNodeValidation(refNode, offset);} this.endContainer = refNode; this.endOffset = offset; if(!bNoUpdate){ if(!this.startContainer || this._compareEndPoint(this.startContainer, this.startOffset, this.endContainer, this.endOffset) != -1){ this.collapse(false); }else{ this._updateRangeInfo(); } } }, setEndAfter : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setEndAfter");} if(refNode.tagName == "BODY"){ this.setEnd(refNode, nhn.DOMFix.childNodes(refNode).length, true, bNoUpdate); return; } this.setEnd(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode)+1, true, bNoUpdate); }, setEndBefore : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setEndBefore");} if(refNode.tagName == "BODY"){ this.setEnd(refNode, 0, true, bNoUpdate); return; } this.setEnd(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode), true, bNoUpdate); }, setStart : function(refNode, offset, bSafe, bNoUpdate){ if(!bSafe){offset = this._endsNodeValidation(refNode, offset);} this.startContainer = refNode; this.startOffset = offset; if(!bNoUpdate){ if(!this.endContainer || this._compareEndPoint(this.startContainer, this.startOffset, this.endContainer, this.endOffset) != -1){ this.collapse(true); }else{ this._updateRangeInfo(); } } }, setStartAfter : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setStartAfter");} if(refNode.tagName == "BODY"){ this.setStart(refNode, nhn.DOMFix.childNodes(refNode).length, true, bNoUpdate); return; } this.setStart(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode)+1, true, bNoUpdate); }, setStartBefore : function(refNode, bNoUpdate){ if(!refNode){throw new Error("INVALID_NODE_TYPE_ERR in setStartBefore");} if(refNode.tagName == "BODY"){ this.setStart(refNode, 0, true, bNoUpdate); return; } this.setStart(nhn.DOMFix.parentNode(refNode), this._getPosIdx(refNode), true, bNoUpdate); }, surroundContents : function(newParent){ newParent.appendChild(this.extractContents()); this.insertNode(newParent); this.selectNode(newParent); }, toString : function(){ var oTmpContainer = this._document.createElement("DIV"); oTmpContainer.appendChild(this.cloneContents()); return oTmpContainer.textContent || oTmpContainer.innerText || ""; }, // this.oBrowserSelection.getCommonAncestorContainer which uses browser's built-in API runs faster but may return an incorrect value. // Call this function to fix the problem. // // In IE, the built-in API would return an incorrect value when, // 1. commonAncestorContainer is not selectable // AND // 2. The selected area will look the same when its child node is selected // eg) // when <P><SPAN>TEST</SPAN></p> is selected, <SPAN>TEST</SPAN> will be returned as commonAncestorContainer fixCommonAncestorContainer : function(){ if(!jindo.$Agent().navigator().ie){ return; } this.commonAncestorContainer = this._getCommonAncestorContainer(); }, _isBlankTextNode : function(oNode){ if(oNode.nodeType == 3 && oNode.nodeValue == ""){return true;} return false; }, _isAllChildBlankText : function(elNode){ for(var i=0, nLen=elNode.childNodes.length; i<nLen; i++){ if(!this._isBlankTextNode(elNode.childNodes[i])){return false;} } return true; }, _getPosIdx : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){idx++;} return idx; }, _updateRangeInfo : function(){ if(!this.startContainer){ this.reset(this._window); return; } // isCollapsed may not function correctly when the cursor is located, // (below a table) AND (at the end of the document where there's no P tag or anything else to actually hold the cursor) this.collapsed = this.oBrowserSelection.isCollapsed(this) || (this.startContainer === this.endContainer && this.startOffset === this.endOffset); // this.collapsed = this._isCollapsed(this.startContainer, this.startOffset, this.endContainer, this.endOffset); this.commonAncestorContainer = this.oBrowserSelection.getCommonAncestorContainer(this); // this.commonAncestorContainer = this._getCommonAncestorContainer(this.startContainer, this.endContainer); }, _isCollapsed : function(oStartContainer, iStartOffset, oEndContainer, iEndOffset){ var bCollapsed = false; if(oStartContainer == oEndContainer && iStartOffset == iEndOffset){ bCollapsed = true; }else{ var oActualStartNode = this._getActualStartNode(oStartContainer, iStartOffset); var oActualEndNode = this._getActualEndNode(oEndContainer, iEndOffset); // Take the parent nodes on the same level for easier comparison when they're next to each other // eg) From // <A> // <B> // <C> // </C> // </B> // <D> // <E> // <F> // </F> // </E> // </D> // </A> // , it's easier to compare the position of B and D rather than C and F because they are siblings // // If the range were collapsed, oActualEndNode will precede oActualStartNode by doing this oActualStartNode = this._getNextNode(this._getPrevNode(oActualStartNode)); oActualEndNode = this._getPrevNode(this._getNextNode(oActualEndNode)); if(oActualStartNode && oActualEndNode && oActualEndNode.tagName != "BODY" && (this._getNextNode(oActualEndNode) == oActualStartNode || (oActualEndNode == oActualStartNode && this._isBlankTextNode(oActualEndNode))) ){ bCollapsed = true; } } return bCollapsed; }, _splitTextEndNodesOfTheRange : function(){ var oEndPoints = this._splitTextEndNodes({oStartContainer: this.startContainer, iStartOffset: this.startOffset, oEndContainer: this.endContainer, iEndOffset: this.endOffset}); this.startContainer = oEndPoints.oStartContainer; this.startOffset = oEndPoints.iStartOffset; this.endContainer = oEndPoints.oEndContainer; this.endOffset = oEndPoints.iEndOffset; }, _splitTextEndNodes : function(oEndPoints){ oEndPoints = this._splitStartTextNode(oEndPoints); oEndPoints = this._splitEndTextNode(oEndPoints); return oEndPoints; }, _splitStartTextNode : function(oEndPoints){ var oStartContainer = oEndPoints.oStartContainer; var iStartOffset = oEndPoints.iStartOffset; var oEndContainer = oEndPoints.oEndContainer; var iEndOffset = oEndPoints.iEndOffset; if(!oStartContainer){return oEndPoints;} if(oStartContainer.nodeType != 3){return oEndPoints;} if(iStartOffset === 0){return oEndPoints;} if(oStartContainer.nodeValue.length <= iStartOffset){return oEndPoints;} var oLastPart = oStartContainer.splitText(iStartOffset); if(oStartContainer == oEndContainer){ iEndOffset -= iStartOffset; oEndContainer = oLastPart; } oStartContainer = oLastPart; iStartOffset = 0; return {oStartContainer: oStartContainer, iStartOffset: iStartOffset, oEndContainer: oEndContainer, iEndOffset: iEndOffset}; }, _splitEndTextNode : function(oEndPoints){ var oStartContainer = oEndPoints.oStartContainer; var iStartOffset = oEndPoints.iStartOffset; var oEndContainer = oEndPoints.oEndContainer; var iEndOffset = oEndPoints.iEndOffset; if(!oEndContainer){return oEndPoints;} if(oEndContainer.nodeType != 3){return oEndPoints;} if(iEndOffset >= oEndContainer.nodeValue.length){return oEndPoints;} if(iEndOffset === 0){return oEndPoints;} oEndContainer.splitText(iEndOffset); return {oStartContainer: oStartContainer, iStartOffset: iStartOffset, oEndContainer: oEndContainer, iEndOffset: iEndOffset}; }, _getNodesInRange : function(){ if(this.collapsed){return [];} var oStartNode = this._getActualStartNode(this.startContainer, this.startOffset); var oEndNode = this._getActualEndNode(this.endContainer, this.endOffset); return this._getNodesBetween(oStartNode, oEndNode); }, _getActualStartNode : function(oStartContainer, iStartOffset){ var oStartNode = oStartContainer; if(oStartContainer.nodeType == 3){ if(iStartOffset >= oStartContainer.nodeValue.length){ oStartNode = this._getNextNode(oStartContainer); if(oStartNode.tagName == "BODY"){oStartNode = null;} }else{ oStartNode = oStartContainer; } }else{ if(iStartOffset < nhn.DOMFix.childNodes(oStartContainer).length){ oStartNode = nhn.DOMFix.childNodes(oStartContainer)[iStartOffset]; }else{ oStartNode = this._getNextNode(oStartContainer); if(oStartNode.tagName == "BODY"){oStartNode = null;} } } return oStartNode; }, _getActualEndNode : function(oEndContainer, iEndOffset){ var oEndNode = oEndContainer; if(iEndOffset === 0){ oEndNode = this._getPrevNode(oEndContainer); if(oEndNode.tagName == "BODY"){oEndNode = null;} }else if(oEndContainer.nodeType == 3){ oEndNode = oEndContainer; }else{ oEndNode = nhn.DOMFix.childNodes(oEndContainer)[iEndOffset-1]; } return oEndNode; }, _getNextNode : function(oNode){ if(!oNode || oNode.tagName == "BODY"){return this._document.body;} if(oNode.nextSibling){return oNode.nextSibling;} return this._getNextNode(nhn.DOMFix.parentNode(oNode)); }, _getPrevNode : function(oNode){ if(!oNode || oNode.tagName == "BODY"){return this._document.body;} if(oNode.previousSibling){return oNode.previousSibling;} return this._getPrevNode(nhn.DOMFix.parentNode(oNode)); }, // includes partially selected // for <div id="a"><div id="b"></div></div><div id="c"></div>, _getNodesBetween(b, c) will yield to b, "a" and c _getNodesBetween : function(oStartNode, oEndNode){ var aNodesBetween = []; this._nNodesBetweenLen = 0; if(!oStartNode || !oEndNode){return aNodesBetween;} // IE may throw an exception on "oCurNode = oCurNode.nextSibling;" when oCurNode is 'invalid', not null or undefined but somehow 'invalid'. // It happened during browser's build-in UNDO with control range selected(table). try{ this._recurGetNextNodesUntil(oStartNode, oEndNode, aNodesBetween); }catch(e){ return []; } return aNodesBetween; }, _recurGetNextNodesUntil : function(oNode, oEndNode, aNodesBetween){ if(!oNode){return false;} if(!this._recurGetChildNodesUntil(oNode, oEndNode, aNodesBetween)){return false;} var oNextToChk = oNode.nextSibling; while(!oNextToChk){ if(!(oNode = nhn.DOMFix.parentNode(oNode))){return false;} aNodesBetween[this._nNodesBetweenLen++] = oNode; if(oNode == oEndNode){return false;} oNextToChk = oNode.nextSibling; } return this._recurGetNextNodesUntil(oNextToChk, oEndNode, aNodesBetween); }, _recurGetChildNodesUntil : function(oNode, oEndNode, aNodesBetween){ if(!oNode){return false;} var bEndFound = false; var oCurNode = oNode; if(oCurNode.firstChild){ oCurNode = oCurNode.firstChild; while(oCurNode){ if(!this._recurGetChildNodesUntil(oCurNode, oEndNode, aNodesBetween)){ bEndFound = true; break; } oCurNode = oCurNode.nextSibling; } } aNodesBetween[this._nNodesBetweenLen++] = oNode; if(bEndFound){return false;} if(oNode == oEndNode){return false;} return true; } }); nhn.W3CDOMRange.START_TO_START = 0; nhn.W3CDOMRange.START_TO_END = 1; nhn.W3CDOMRange.END_TO_END = 2; nhn.W3CDOMRange.END_TO_START = 3; /** * @fileOverview This file contains a cross-browser function that implements all of the W3C's DOM Range specification and some more * @name HuskyRange.js */ nhn.HuskyRange = jindo.$Class({ setWindow : function(win){ this.reset(win || window); }, $init : function(win){ this.HUSKY_BOOMARK_START_ID_PREFIX = "husky_bookmark_start_"; this.HUSKY_BOOMARK_END_ID_PREFIX = "husky_bookmark_end_"; this.sBlockElement = "P|DIV|LI|H[1-6]|PRE"; this.sBlockContainer = "BODY|TABLE|TH|TR|TD|UL|OL|BLOCKQUOTE|FORM"; this.rxBlockElement = new RegExp("^("+this.sBlockElement+")$"); this.rxBlockContainer = new RegExp("^("+this.sBlockContainer+")$"); this.rxLineBreaker = new RegExp("^("+this.sBlockElement+"|"+this.sBlockContainer+")$"); this.setWindow(win); }, select : function(){ try{ this.oBrowserSelection.selectRange(this); }catch(e){} }, setFromSelection : function(iNum){ this.setRange(this.oBrowserSelection.getRangeAt(iNum), true); }, setRange : function(oW3CRange, bSafe){ this.reset(this._window); this.setStart(oW3CRange.startContainer, oW3CRange.startOffset, bSafe, true); this.setEnd(oW3CRange.endContainer, oW3CRange.endOffset, bSafe); }, setEndNodes : function(oSNode, oENode){ this.reset(this._window); this.setEndAfter(oENode, true); this.setStartBefore(oSNode); }, splitTextAtBothEnds : function(){ this._splitTextEndNodesOfTheRange(); }, getStartNode : function(){ if(this.collapsed){ if(this.startContainer.nodeType == 3){ if(this.startOffset === 0){return null;} if(this.startContainer.nodeValue.length <= this.startOffset){return null;} return this.startContainer; } return null; } if(this.startContainer.nodeType == 3){ if(this.startOffset >= this.startContainer.nodeValue.length){return this._getNextNode(this.startContainer);} return this.startContainer; }else{ if(this.startOffset >= nhn.DOMFix.childNodes(this.startContainer).length){return this._getNextNode(this.startContainer);} return nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } }, getEndNode : function(){ if(this.collapsed){return this.getStartNode();} if(this.endContainer.nodeType == 3){ if(this.endOffset === 0){return this._getPrevNode(this.endContainer);} return this.endContainer; }else{ if(this.endOffset === 0){return this._getPrevNode(this.endContainer);} return nhn.DOMFix.childNodes(this.endContainer)[this.endOffset-1]; } }, getNodeAroundRange : function(bBefore, bStrict){ if(!this.collapsed){return this.getStartNode();} if(this.startContainer && this.startContainer.nodeType == 3){return this.startContainer;} //if(this.collapsed && this.startContainer && this.startContainer.nodeType == 3) return this.startContainer; //if(!this.collapsed || (this.startContainer && this.startContainer.nodeType == 3)) return this.getStartNode(); var oBeforeRange, oAfterRange, oResult; if(this.startOffset >= nhn.DOMFix.childNodes(this.startContainer).length){ oAfterRange = this._getNextNode(this.startContainer); }else{ oAfterRange = nhn.DOMFix.childNodes(this.startContainer)[this.startOffset]; } if(this.endOffset === 0){ oBeforeRange = this._getPrevNode(this.endContainer); }else{ oBeforeRange = nhn.DOMFix.childNodes(this.endContainer)[this.endOffset-1]; } if(bBefore){ oResult = oBeforeRange; if(!oResult && !bStrict){oResult = oAfterRange;} }else{ oResult = oAfterRange; if(!oResult && !bStrict){oResult = oBeforeRange;} } return oResult; }, _getXPath : function(elNode){ var sXPath = ""; while(elNode && elNode.nodeType == 1){ sXPath = "/" + elNode.tagName+"["+this._getPosIdx4XPath(elNode)+"]" + sXPath; elNode = nhn.DOMFix.parentNode(elNode); } return sXPath; }, _getPosIdx4XPath : function(refNode){ var idx = 0; for(var node = refNode.previousSibling; node; node = node.previousSibling){ if(node.tagName == refNode.tagName){idx++;} } return idx; }, // this was written specifically for XPath Bookmark and it may not perform correctly for general purposes _evaluateXPath : function(sXPath, oDoc){ sXPath = sXPath.substring(1, sXPath.length-1); var aXPath = sXPath.split(/\//); var elNode = oDoc.body; for(var i=2; i<aXPath.length && elNode; i++){ aXPath[i].match(/([^\[]+)\[(\d+)/i); var sTagName = RegExp.$1; var nIdx = RegExp.$2; var aAllNodes = nhn.DOMFix.childNodes(elNode); var aNodes = []; var nLength = aAllNodes.length; var nCount = 0; for(var ii=0; ii<nLength; ii++){ if(aAllNodes[ii].tagName == sTagName){aNodes[nCount++] = aAllNodes[ii];} } if(aNodes.length < nIdx){ elNode = null; }else{ elNode = aNodes[nIdx]; } } return elNode; }, _evaluateXPathBookmark : function(oBookmark){ var sXPath = oBookmark["sXPath"]; var nTextNodeIdx = oBookmark["nTextNodeIdx"]; var nOffset = oBookmark["nOffset"]; var elContainer = this._evaluateXPath(sXPath, this._document); if(nTextNodeIdx > -1 && elContainer){ var aChildNodes = nhn.DOMFix.childNodes(elContainer); var elNode = null; var nIdx = nTextNodeIdx; var nOffsetLeft = nOffset; while((elNode = aChildNodes[nIdx]) && elNode.nodeType == 3 && elNode.nodeValue.length < nOffsetLeft){ nOffsetLeft -= elNode.nodeValue.length; nIdx++; } elContainer = nhn.DOMFix.childNodes(elContainer)[nIdx]; nOffset = nOffsetLeft; } if(!elContainer){ elContainer = this._document.body; nOffset = 0; } return {elContainer: elContainer, nOffset: nOffset}; }, // this was written specifically for XPath Bookmark and it may not perform correctly for general purposes getXPathBookmark : function(){ var nTextNodeIdx1 = -1; var htEndPt1 = {elContainer: this.startContainer, nOffset: this.startOffset}; var elNode1 = this.startContainer; if(elNode1.nodeType == 3){ htEndPt1 = this._getFixedStartTextNode(); nTextNodeIdx1 = this._getPosIdx(htEndPt1.elContainer); elNode1 = nhn.DOMFix.parentNode(elNode1); } var sXPathNode1 = this._getXPath(elNode1); var oBookmark1 = {sXPath:sXPathNode1, nTextNodeIdx:nTextNodeIdx1, nOffset: htEndPt1.nOffset}; if(this.collapsed){ var oBookmark2 = {sXPath:sXPathNode1, nTextNodeIdx:nTextNodeIdx1, nOffset: htEndPt1.nOffset}; }else{ var nTextNodeIdx2 = -1; var htEndPt2 = {elContainer: this.endContainer, nOffset: this.endOffset}; var elNode2 = this.endContainer; if(elNode2.nodeType == 3){ htEndPt2 = this._getFixedEndTextNode(); nTextNodeIdx2 = this._getPosIdx(htEndPt2.elContainer); elNode2 = nhn.DOMFix.parentNode(elNode2); } var sXPathNode2 = this._getXPath(elNode2); var oBookmark2 = {sXPath:sXPathNode2, nTextNodeIdx:nTextNodeIdx2, nOffset: htEndPt2.nOffset}; } return [oBookmark1, oBookmark2]; }, moveToXPathBookmark : function(aBookmark){ if(!aBookmark){return false;} var oBookmarkInfo1 = this._evaluateXPathBookmark(aBookmark[0]); var oBookmarkInfo2 = this._evaluateXPathBookmark(aBookmark[1]); if(!oBookmarkInfo1["elContainer"] || !oBookmarkInfo2["elContainer"]){return;} this.startContainer = oBookmarkInfo1["elContainer"]; this.startOffset = oBookmarkInfo1["nOffset"]; this.endContainer = oBookmarkInfo2["elContainer"]; this.endOffset = oBookmarkInfo2["nOffset"]; return true; }, _getFixedTextContainer : function(elNode, nOffset){ while(elNode && elNode.nodeType == 3 && elNode.previousSibling && elNode.previousSibling.nodeType == 3){ nOffset += elNode.previousSibling.nodeValue.length; elNode = elNode.previousSibling; } return {elContainer:elNode, nOffset:nOffset}; }, _getFixedStartTextNode : function(){ return this._getFixedTextContainer(this.startContainer, this.startOffset); }, _getFixedEndTextNode : function(){ return this._getFixedTextContainer(this.endContainer, this.endOffset); }, placeStringBookmark : function(){ if(this.collapsed || jindo.$Agent().navigator().ie || jindo.$Agent().navigator().firefox){ return this.placeStringBookmark_NonWebkit(); }else{ return this.placeStringBookmark_Webkit(); } }, placeStringBookmark_NonWebkit : function(){ var sTmpId = (new Date()).getTime(); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToEnd(); var oEndMarker = this._document.createElement("SPAN"); oEndMarker.id = this.HUSKY_BOOMARK_END_ID_PREFIX+sTmpId; oInsertionPoint.insertNode(oEndMarker); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToStart(); var oStartMarker = this._document.createElement("SPAN"); oStartMarker.id = this.HUSKY_BOOMARK_START_ID_PREFIX+sTmpId; oInsertionPoint.insertNode(oStartMarker); // IE에서 빈 SPAN의 앞뒤로 커서가 이동하지 않아 문제가 발생 할 수 있어, 보이지 않는 특수 문자를 임시로 넣어 줌. if(jindo.$Agent().navigator().ie){ // SPAN의 위치가 TD와 TD 사이에 있을 경우, 텍스트 삽입 시 알수 없는 오류가 발생한다. // TD와 TD사이에서는 텍스트 삽입이 필요 없음으로 그냥 try/catch로 처리 try{ oStartMarker.innerHTML = unescape("%uFEFF"); }catch(e){} try{ oEndMarker.innerHTML = unescape("%uFEFF"); }catch(e){} } this.moveToBookmark(sTmpId); return sTmpId; }, placeStringBookmark_Webkit : function(){ var sTmpId = (new Date()).getTime(); var elInsertBefore, elInsertParent; // Do not insert the bookmarks between TDs as it will break the rendering in Chrome/Safari // -> modify the insertion position from [<td>abc</td>]<td>abc</td> to <td>[abc]</td><td>abc</td> var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToEnd(); elInsertBefore = this._document.createTextNode(""); oInsertionPoint.insertNode(elInsertBefore); elInsertParent = elInsertBefore.parentNode; if(elInsertBefore.previousSibling && elInsertBefore.previousSibling.tagName == "TD"){ elInsertParent = elInsertBefore.previousSibling; elInsertBefore = null; } var oEndMarker = this._document.createElement("SPAN"); oEndMarker.id = this.HUSKY_BOOMARK_END_ID_PREFIX+sTmpId; elInsertParent.insertBefore(oEndMarker, elInsertBefore); var oInsertionPoint = this.cloneRange(); oInsertionPoint.collapseToStart(); elInsertBefore = this._document.createTextNode(""); oInsertionPoint.insertNode(elInsertBefore); elInsertParent = elInsertBefore.parentNode; if(elInsertBefore.nextSibling && elInsertBefore.nextSibling.tagName == "TD"){ elInsertParent = elInsertBefore.nextSibling; elInsertBefore = elInsertParent.firstChild; } var oStartMarker = this._document.createElement("SPAN"); oStartMarker.id = this.HUSKY_BOOMARK_START_ID_PREFIX+sTmpId; elInsertParent.insertBefore(oStartMarker, elInsertBefore); //elInsertBefore.parentNode.removeChild(elInsertBefore); this.moveToBookmark(sTmpId); return sTmpId; }, cloneRange : function(){ return this._copyRange(new nhn.HuskyRange(this._window)); }, moveToBookmark : function(vBookmark){ if(typeof(vBookmark) != "object"){ return this.moveToStringBookmark(vBookmark); }else{ return this.moveToXPathBookmark(vBookmark); } }, getStringBookmark : function(sBookmarkID, bEndBookmark){ if(bEndBookmark){ return this._document.getElementById(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); }else{ return this._document.getElementById(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); } }, moveToStringBookmark : function(sBookmarkID, bIncludeBookmark){ var oStartMarker = this.getStringBookmark(sBookmarkID); var oEndMarker = this.getStringBookmark(sBookmarkID, true); if(!oStartMarker || !oEndMarker){return false;} this.reset(this._window); if(bIncludeBookmark){ this.setEndAfter(oEndMarker); this.setStartBefore(oStartMarker); }else{ this.setEndBefore(oEndMarker); this.setStartAfter(oStartMarker); } return true; }, removeStringBookmark : function(sBookmarkID){ /* var oStartMarker = this._document.getElementById(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); var oEndMarker = this._document.getElementById(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); if(oStartMarker) nhn.DOMFix.parentNode(oStartMarker).removeChild(oStartMarker); if(oEndMarker) nhn.DOMFix.parentNode(oEndMarker).removeChild(oEndMarker); */ this._removeAll(this.HUSKY_BOOMARK_START_ID_PREFIX+sBookmarkID); this._removeAll(this.HUSKY_BOOMARK_END_ID_PREFIX+sBookmarkID); }, _removeAll : function(sID){ var elNode; while((elNode = this._document.getElementById(sID))){ nhn.DOMFix.parentNode(elNode).removeChild(elNode); } }, collapseToStart : function(){ this.collapse(true); }, collapseToEnd : function(){ this.collapse(false); }, createAndInsertNode : function(sTagName){ var tmpNode = this._document.createElement(sTagName); this.insertNode(tmpNode); return tmpNode; }, getNodes : function(bSplitTextEndNodes, fnFilter){ if(bSplitTextEndNodes){this._splitTextEndNodesOfTheRange();} var aAllNodes = this._getNodesInRange(); var aFilteredNodes = []; if(!fnFilter){return aAllNodes;} for(var i=0; i<aAllNodes.length; i++){ if(fnFilter(aAllNodes[i])){aFilteredNodes[aFilteredNodes.length] = aAllNodes[i];} } return aFilteredNodes; }, getTextNodes : function(bSplitTextEndNodes){ var txtFilter = function(oNode){ if (oNode.nodeType == 3 && oNode.nodeValue != "\n" && oNode.nodeValue != ""){ return true; }else{ return false; } }; return this.getNodes(bSplitTextEndNodes, txtFilter); }, surroundContentsWithNewNode : function(sTagName){ var oNewParent = this._document.createElement(sTagName); this.surroundContents(oNewParent); return oNewParent; }, isRangeinRange : function(oAnoterRange, bIncludePartlySelected){ var startToStart = this.compareBoundaryPoints(this.W3CDOMRange.START_TO_START, oAnoterRange); var startToEnd = this.compareBoundaryPoints(this.W3CDOMRange.START_TO_END, oAnoterRange); var endToStart = this.compareBoundaryPoints(this.W3CDOMRange.ND_TO_START, oAnoterRange); var endToEnd = this.compareBoundaryPoints(this.W3CDOMRange.END_TO_END, oAnoterRange); if(startToStart <= 0 && endToEnd >= 0){return true;} if(bIncludePartlySelected){ if(startToEnd == 1){return false;} if(endToStart == -1){return false;} return true; } return false; }, isNodeInRange : function(oNode, bIncludePartlySelected, bContentOnly){ var oTmpRange = new nhn.HuskyRange(this._window); if(bContentOnly && oNode.firstChild){ oTmpRange.setStartBefore(oNode.firstChild); oTmpRange.setEndAfter(oNode.lastChild); }else{ oTmpRange.selectNode(oNode); } return this.isRangeInRange(oTmpRange, bIncludePartlySelected); }, pasteText : function(sText){ this.pasteHTML(sText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;").replace(/"/g, "&quot;")); }, pasteHTML : function(sHTML){ var oTmpDiv = this._document.createElement("DIV"); oTmpDiv.innerHTML = sHTML; if(!oTmpDiv.firstChild){ this.deleteContents(); return; } var oFirstNode = oTmpDiv.firstChild; var oLastNode = oTmpDiv.lastChild; var clone = this.cloneRange(); var sBM = clone.placeStringBookmark(); this.collapseToStart(); while(oTmpDiv.lastChild){this.insertNode(oTmpDiv.lastChild);} this.setEndNodes(oFirstNode, oLastNode); // delete the content later as deleting it first may mass up the insertion point // eg) <p>[A]BCD</p> ---paste O---> O<p>BCD</p> clone.moveToBookmark(sBM); clone.deleteContents(); clone.removeStringBookmark(sBM); }, toString : function(){ this.toString = nhn.W3CDOMRange.prototype.toString; return this.toString(); }, toHTMLString : function(){ var oTmpContainer = this._document.createElement("DIV"); oTmpContainer.appendChild(this.cloneContents()); return oTmpContainer.innerHTML; }, findAncestorByTagName : function(sTagName){ var oNode = this.commonAncestorContainer; while(oNode && oNode.tagName != sTagName){oNode = nhn.DOMFix.parentNode(oNode);} return oNode; }, selectNodeContents : function(oNode){ if(!oNode){return;} var oFirstNode = oNode.firstChild?oNode.firstChild:oNode; var oLastNode = oNode.lastChild?oNode.lastChild:oNode; this.reset(this._window); if(oFirstNode.nodeType == 3){ this.setStart(oFirstNode, 0, true); }else{ this.setStartBefore(oFirstNode); } if(oLastNode.nodeType == 3){ this.setEnd(oLastNode, oLastNode.nodeValue.length, true); }else{ this.setEndAfter(oLastNode); } }, /** * 노드의 취소선/밑줄 정보를 확인한다 * 관련 BTS [SMARTEDITORSUS-26] * @param {Node} oNode 취소선/밑줄을 확인할 노드 * @param {String} sValue textDecoration 정보 * @see nhn.HuskyRange#_checkTextDecoration */ _hasTextDecoration : function(oNode, sValue){ if(!oNode || !oNode.style){ return false; } if(oNode.style.textDecoration.indexOf(sValue) > -1){ return true; } if(sValue === "underline" && oNode.tagName === "U"){ return true; } if(sValue === "line-through" && (oNode.tagName === "S" || oNode.tagName === "STRIKE")){ return true; } return false; }, /** * 노드에 취소선/밑줄을 적용한다 * 관련 BTS [SMARTEDITORSUS-26] * [FF] 노드의 Style 에 textDecoration 을 추가한다 * [FF 외] U/STRIKE 태그를 추가한다 * @param {Node} oNode 취소선/밑줄을 적용할 노드 * @param {String} sValue textDecoration 정보 * @see nhn.HuskyRange#_checkTextDecoration */ _setTextDecoration : function(oNode, sValue){ if (jindo.$Agent().navigator().firefox) { // FF oNode.style.textDecoration = (oNode.style.textDecoration) ? oNode.style.textDecoration + " " + sValue : sValue; } else{ if(sValue === "underline"){ oNode.innerHTML = "<U>" + oNode.innerHTML + "</U>" }else if(sValue === "line-through"){ oNode.innerHTML = "<STRIKE>" + oNode.innerHTML + "</STRIKE>" } } }, /** * 인자로 전달받은 노드 상위의 취소선/밑줄 정보를 확인하여 노드에 적용한다 * 관련 BTS [SMARTEDITORSUS-26] * @param {Node} oNode 취소선/밑줄을 적용할 노드 */ _checkTextDecoration : function(oNode){ if(oNode.tagName !== "SPAN"){ return; } var bUnderline = false, bLineThrough = false, sTextDecoration = "", oParentNode = null; oChildNode = oNode.firstChild; /* check child */ while(oChildNode){ if(oChildNode.nodeType === 1){ bUnderline = (bUnderline || oChildNode.tagName === "U"); bLineThrough = (bLineThrough || oChildNode.tagName === "S" || oChildNode.tagName === "STRIKE"); } if(bUnderline && bLineThrough){ return; } oChildNode = oChildNode.nextSibling; } oParentNode = nhn.DOMFix.parentNode(oNode); /* check parent */ while(oParentNode && oParentNode.tagName !== "BODY"){ if(oParentNode.nodeType !== 1){ oParentNode = nhn.DOMFix.parentNode(oParentNode); continue; } if(!bUnderline && this._hasTextDecoration(oParentNode, "underline")){ bUnderline = true; this._setTextDecoration(oNode, "underline"); // set underline } if(!bLineThrough && this._hasTextDecoration(oParentNode, "line-through")){ bLineThrough = true; this._setTextDecoration(oNode, "line-through"); // set line-through } if(bUnderline && bLineThrough){ return; } oParentNode = nhn.DOMFix.parentNode(oParentNode); } }, /** * Range에 속한 노드들에 스타일을 적용한다 * @param {Object} oStyle 적용할 스타일을 가지는 Object (예) 글꼴 색 적용의 경우 { color : "#0075c8" } * @param {Object} [oAttribute] 적용할 속성을 가지는 Object (예) 맞춤범 검사의 경우 { _sm2_spchk: "강남콩", class: "se2_check_spell" } * @param {String} [sNewSpanMarker] 새로 추가된 SPAN 노드를 나중에 따로 처리해야하는 경우 마킹을 위해 사용하는 문자열 * @param {Boolean} [bIncludeLI] LI 도 스타일 적용에 포함할 것인지의 여부 [COM-1051] _getStyleParentNodes 메서드 참고하기 * @param {Boolean} [bCheckTextDecoration] 취소선/밑줄 처리를 적용할 것인지 여부 [SMARTEDITORSUS-26] _setTextDecoration 메서드 참고하기 */ styleRange : function(oStyle, oAttribute, sNewSpanMarker, bIncludeLI, bCheckTextDecoration){ var aStyleParents = this.aStyleParents = this._getStyleParentNodes(sNewSpanMarker, bIncludeLI); if(aStyleParents.length < 1){return;} var sName, sValue; for(var i=0; i<aStyleParents.length; i++){ for(var x in oStyle){ sName = x; sValue = oStyle[sName]; if(typeof sValue != "string"){continue;} // [SMARTEDITORSUS-26] 글꼴 색을 적용할 때 취소선/밑줄의 색상도 처리되도록 추가 if(bCheckTextDecoration && oStyle.color){ this._checkTextDecoration(aStyleParents[i]); } aStyleParents[i].style[sName] = sValue; } if(!oAttribute){continue;} for(var x in oAttribute){ sName = x; sValue = oAttribute[sName]; if(typeof sValue != "string"){continue;} if(sName == "class"){ jindo.$Element(aStyleParents[i]).addClass(sValue); }else{ aStyleParents[i].setAttribute(sName, sValue); } } } this.reset(this._window); this.setStartBefore(aStyleParents[0]); this.setEndAfter(aStyleParents[aStyleParents.length-1]); }, expandBothEnds : function(){ this.expandStart(); this.expandEnd(); }, expandStart : function(){ if(this.startContainer.nodeType == 3 && this.startOffset !== 0){return;} var elActualStartNode = this._getActualStartNode(this.startContainer, this.startOffset); elActualStartNode = this._getPrevNode(elActualStartNode); if(elActualStartNode.tagName == "BODY"){ this.setStartBefore(elActualStartNode); }else{ this.setStartAfter(elActualStartNode); } }, expandEnd : function(){ if(this.endContainer.nodeType == 3 && this.endOffset < this.endContainer.nodeValue.length){return;} var elActualEndNode = this._getActualEndNode(this.endContainer, this.endOffset); elActualEndNode = this._getNextNode(elActualEndNode); if(elActualEndNode.tagName == "BODY"){ this.setEndAfter(elActualEndNode); }else{ this.setEndBefore(elActualEndNode); } }, /** * Style 을 적용할 노드를 가져온다 * @param {String} [sNewSpanMarker] 새로 추가하는 SPAN 노드를 마킹을 위해 사용하는 문자열 * @param {Boolean} [bIncludeLI] LI 도 스타일 적용에 포함할 것인지의 여부 * @return {Array} Style 을 적용할 노드 배열 */ _getStyleParentNodes : function(sNewSpanMarker, bIncludeLI){ this._splitTextEndNodesOfTheRange(); var oSNode = this.getStartNode(); var oENode = this.getEndNode(); var aAllNodes = this._getNodesInRange(); var aResult = []; var nResult = 0; var oNode, oTmpNode, iStartRelPos, iEndRelPos, oSpan; var nInitialLength = aAllNodes.length; var arAllBottomNodes = jindo.$A(aAllNodes).filter(function(v){return (!v.firstChild || (bIncludeLI && v.tagName=="LI"));}); // [COM-1051] 본문내용을 한 줄만 입력하고 번호 매긴 상태에서 글자크기를 변경하면 번호크기는 변하지 않는 문제 // 부모 노드 중 LI 가 있고, 해당 LI 의 모든 자식 노드가 선택된 상태라면 LI에도 스타일을 적용하도록 처리함 // --- Range 에 LI 가 포함되지 않은 경우, LI 를 포함하도록 처리 var elTmpNode = this.commonAncestorContainer; if(bIncludeLI){ while(elTmpNode){ if(elTmpNode.tagName == "LI"){ if(this._isFullyContained(elTmpNode, arAllBottomNodes)){ aResult[nResult++] = elTmpNode; } break; } elTmpNode = elTmpNode.parentNode; } } for(var i=0; i<nInitialLength; i++){ oNode = aAllNodes[i]; if(!oNode){continue;} // --- Range 에 LI 가 포함된 경우에 대한 LI 확인 if(bIncludeLI && oNode.tagName == "LI" && this._isFullyContained(oNode, arAllBottomNodes)){ aResult[nResult++] = oNode; continue; } if(oNode.nodeType != 3){continue;} if(oNode.nodeValue == "" || oNode.nodeValue.match(/^(\r|\n)+$/)){continue;} var oParentNode = nhn.DOMFix.parentNode(oNode); // 부모 노드가 SPAN 인 경우에는 새로운 SPAN 을 생성하지 않고 SPAN 을 리턴 배열에 추가함 if(oParentNode.tagName == "SPAN"){ if(this._isFullyContained(oParentNode, arAllBottomNodes, oNode)){ aResult[nResult++] = oParentNode; continue; } } oSpan = this._document.createElement("SPAN"); oParentNode.insertBefore(oSpan, oNode); oSpan.appendChild(oNode); aResult[nResult++] = oSpan; if(sNewSpanMarker){oSpan.setAttribute(sNewSpanMarker, "true");} } this.setStartBefore(oSNode); this.setEndAfter(oENode); return aResult; }, /** * 컨테이너 엘리먼트(elContainer)의 모든 자식노드가 노드 배열(waAllNodes)에 속하는지 확인한다 * 첫 번째 자식 노드와 마지막 자식 노드가 노드 배열에 속하는지를 확인한다 * @param {Element} elContainer 컨테이너 엘리먼트 * @param {jindo.$A} waAllNodes Node 의 $A 배열 * @param {Node} [oNode] 성능을 위한 옵션 노드로 컨테이너의 첫 번째 혹은 마지막 자식 노드와 같으면 indexOf 함수 사용을 줄일 수 있음 * @return {Array} Style 을 적용할 노드 배열 */ // check if all the child nodes of elContainer are in waAllNodes _isFullyContained : function(elContainer, waAllNodes, oNode){ var nSIdx, nEIdx; var oTmpNode = this._getVeryFirstRealChild(elContainer); // do quick checks before trying indexOf() because indexOf() function is very slow // oNode is optional if(oNode && oTmpNode == oNode){ nSIdx = 1; }else{ nSIdx = waAllNodes.indexOf(oTmpNode); } if(nSIdx != -1){ oTmpNode = this._getVeryLastRealChild(elContainer); if(oNode && oTmpNode == oNode){ nEIdx = 1; }else{ nEIdx = waAllNodes.indexOf(oTmpNode); } } return (nSIdx != -1 && nEIdx != -1); }, _getVeryFirstChild : function(oNode){ if(oNode.firstChild){return this._getVeryFirstChild(oNode.firstChild);} return oNode; }, _getVeryLastChild : function(oNode){ if(oNode.lastChild){return this._getVeryLastChild(oNode.lastChild);} return oNode; }, _getFirstRealChild : function(oNode){ var oFirstNode = oNode.firstChild; while(oFirstNode && oFirstNode.nodeType == 3 && oFirstNode.nodeValue == ""){oFirstNode = oFirstNode.nextSibling;} return oFirstNode; }, _getLastRealChild : function(oNode){ var oLastNode = oNode.lastChild; while(oLastNode && oLastNode.nodeType == 3 && oLastNode.nodeValue == ""){oLastNode = oLastNode.previousSibling;} return oLastNode; }, _getVeryFirstRealChild : function(oNode){ var oFirstNode = this._getFirstRealChild(oNode); if(oFirstNode){return this._getVeryFirstRealChild(oFirstNode);} return oNode; }, _getVeryLastRealChild : function(oNode){ var oLastNode = this._getLastRealChild(oNode); if(oLastNode){return this._getVeryLastChild(oLastNode);} return oNode; }, _getLineStartInfo : function(node){ var frontEndFinal = null; var frontEnd = node; var lineBreaker = node; var bParentBreak = false; var rxLineBreaker = this.rxLineBreaker; // vertical(parent) search function getLineStart(node){ if(!node){return;} if(frontEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; frontEndFinal = frontEnd; bParentBreak = true; return; }else{ frontEnd = node; } getFrontEnd(node.previousSibling); if(frontEndFinal){return;} getLineStart(nhn.DOMFix.parentNode(node)); } // horizontal(sibling) search function getFrontEnd(node){ if(!node){return;} if(frontEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; frontEndFinal = frontEnd; bParentBreak = false; return; } if(node.firstChild && node.tagName != "TABLE"){ var curNode = node.lastChild; while(curNode && !frontEndFinal){ getFrontEnd(curNode); curNode = curNode.previousSibling; } }else{ frontEnd = node; } if(!frontEndFinal){ getFrontEnd(node.previousSibling); } } if(rxLineBreaker.test(node.tagName)){ frontEndFinal = node; }else{ getLineStart(node); } return {oNode: frontEndFinal, oLineBreaker: lineBreaker, bParentBreak: bParentBreak}; }, _getLineEndInfo : function(node){ var backEndFinal = null; var backEnd = node; var lineBreaker = node; var bParentBreak = false; var rxLineBreaker = this.rxLineBreaker; // vertical(parent) search function getLineEnd(node){ if(!node){return;} if(backEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; backEndFinal = backEnd; bParentBreak = true; return; }else{ backEnd = node; } getBackEnd(node.nextSibling); if(backEndFinal){return;} getLineEnd(nhn.DOMFix.parentNode(node)); } // horizontal(sibling) search function getBackEnd(node){ if(!node){return;} if(backEndFinal){return;} if(rxLineBreaker.test(node.tagName)){ lineBreaker = node; backEndFinal = backEnd; bParentBreak = false; return; } if(node.firstChild && node.tagName != "TABLE"){ var curNode = node.firstChild; while(curNode && !backEndFinal){ getBackEnd(curNode); curNode = curNode.nextSibling; } }else{ backEnd = node; } if(!backEndFinal){ getBackEnd(node.nextSibling); } } if(rxLineBreaker.test(node.tagName)){ backEndFinal = node; }else{ getLineEnd(node); } return {oNode: backEndFinal, oLineBreaker: lineBreaker, bParentBreak: bParentBreak}; }, getLineInfo : function(bAfter){ var bAfter = bAfter || false; var oSNode = this.getStartNode(); var oENode = this.getEndNode(); // oSNode && oENode will be null if the range is currently collapsed and the cursor is not located in the middle of a text node. if(!oSNode){oSNode = this.getNodeAroundRange(!bAfter, true);} if(!oENode){oENode = this.getNodeAroundRange(!bAfter, true);} var oStart = this._getLineStartInfo(oSNode); var oStartNode = oStart.oNode; var oEnd = this._getLineEndInfo(oENode); var oEndNode = oEnd.oNode; if(oSNode != oStartNode || oENode != oEndNode){ // check if the start node is positioned after the range's ending point // or // if the end node is positioned before the range's starting point var iRelativeStartPos = this._compareEndPoint(nhn.DOMFix.parentNode(oStartNode), this._getPosIdx(oStartNode), this.endContainer, this.endOffset); var iRelativeEndPos = this._compareEndPoint(nhn.DOMFix.parentNode(oEndNode), this._getPosIdx(oEndNode)+1, this.startContainer, this.startOffset); if(!(iRelativeStartPos <= 0 && iRelativeEndPos >= 0)){ oSNode = this.getNodeAroundRange(false, true); oENode = this.getNodeAroundRange(false, true); oStart = this._getLineStartInfo(oSNode); oEnd = this._getLineEndInfo(oENode); } } return {oStart: oStart, oEnd: oEnd}; } }).extend(nhn.W3CDOMRange); /** * @fileOverview This file contains cross-browser selection function * @name BrowserSelection.js */ nhn.BrowserSelection = function(win){ this.init = function(win){ this._window = win || window; this._document = this._window.document; }; this.init(win); // [SMARTEDITORSUS-888] IE9 이후로 document.createRange 를 지원 /* var oAgentInfo = jindo.$Agent().navigator(); if(oAgentInfo.ie){ nhn.BrowserSelectionImpl_IE.apply(this); }else{ nhn.BrowserSelectionImpl_FF.apply(this); }*/ if(!!this._document.createRange){ nhn.BrowserSelectionImpl_FF.apply(this); }else{ nhn.BrowserSelectionImpl_IE.apply(this); } this.selectRange = function(oRng){ this.selectNone(); this.addRange(oRng); }; this.selectionLoaded = true; if(!this._oSelection){this.selectionLoaded = false;} }; nhn.BrowserSelectionImpl_FF = function(){ this._oSelection = this._window.getSelection(); this.getRangeAt = function(iNum){ iNum = iNum || 0; try{ var oFFRange = this._oSelection.getRangeAt(iNum); }catch(e){return new nhn.W3CDOMRange(this._window);} return this._FFRange2W3CRange(oFFRange); }; this.addRange = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); this._oSelection.addRange(oFFRange); }; this.selectNone = function(){ this._oSelection.removeAllRanges(); }; this.getCommonAncestorContainer = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); return oFFRange.commonAncestorContainer; }; this.isCollapsed = function(oW3CRange){ var oFFRange = this._W3CRange2FFRange(oW3CRange); return oFFRange.collapsed; }; this.compareEndPoints = function(elContainerA, nOffsetA, elContainerB, nOffsetB){ var oFFRangeA = this._document.createRange(); var oFFRangeB = this._document.createRange(); oFFRangeA.setStart(elContainerA, nOffsetA); oFFRangeB.setStart(elContainerB, nOffsetB); oFFRangeA.collapse(true); oFFRangeB.collapse(true); try{ return oFFRangeA.compareBoundaryPoints(1, oFFRangeB); }catch(e){ return 1; } }; this._FFRange2W3CRange = function(oFFRange){ var oW3CRange = new nhn.W3CDOMRange(this._window); oW3CRange.setStart(oFFRange.startContainer, oFFRange.startOffset, true); oW3CRange.setEnd(oFFRange.endContainer, oFFRange.endOffset, true); return oW3CRange; }; this._W3CRange2FFRange = function(oW3CRange){ var oFFRange = this._document.createRange(); oFFRange.setStart(oW3CRange.startContainer, oW3CRange.startOffset); oFFRange.setEnd(oW3CRange.endContainer, oW3CRange.endOffset); return oFFRange; }; }; nhn.BrowserSelectionImpl_IE = function(){ this._oSelection = this._document.selection; this.oLastRange = { oBrowserRange : null, elStartContainer : null, nStartOffset : -1, elEndContainer : null, nEndOffset : -1 }; this._updateLastRange = function(oBrowserRange, oW3CRange){ this.oLastRange.oBrowserRange = oBrowserRange; this.oLastRange.elStartContainer = oW3CRange.startContainer; this.oLastRange.nStartOffset = oW3CRange.startOffset; this.oLastRange.elEndContainer = oW3CRange.endContainer; this.oLastRange.nEndOffset = oW3CRange.endOffset; }; this.getRangeAt = function(iNum){ iNum = iNum || 0; var oW3CRange, oBrowserRange; if(this._oSelection.type == "Control"){ oW3CRange = new nhn.W3CDOMRange(this._window); var oSelectedNode = this._oSelection.createRange().item(iNum); // if the selction occurs in a different document, ignore if(!oSelectedNode || oSelectedNode.ownerDocument != this._document){return oW3CRange;} oW3CRange.selectNode(oSelectedNode); return oW3CRange; }else{ //oBrowserRange = this._oSelection.createRangeCollection().item(iNum); oBrowserRange = this._oSelection.createRange(); var oSelectedNode = oBrowserRange.parentElement(); // if the selction occurs in a different document, ignore if(!oSelectedNode || oSelectedNode.ownerDocument != this._document){ oW3CRange = new nhn.W3CDOMRange(this._window); return oW3CRange; } oW3CRange = this._IERange2W3CRange(oBrowserRange); return oW3CRange; } }; this.addRange = function(oW3CRange){ var oIERange = this._W3CRange2IERange(oW3CRange); oIERange.select(); }; this.selectNone = function(){ this._oSelection.empty(); }; this.getCommonAncestorContainer = function(oW3CRange){ return this._W3CRange2IERange(oW3CRange).parentElement(); }; this.isCollapsed = function(oW3CRange){ var oRange = this._W3CRange2IERange(oW3CRange); var oRange2 = oRange.duplicate(); oRange2.collapse(); return oRange.isEqual(oRange2); }; this.compareEndPoints = function(elContainerA, nOffsetA, elContainerB, nOffsetB){ var oIERangeA, oIERangeB; if(elContainerA === this.oLastRange.elStartContainer && nOffsetA === this.oLastRange.nStartOffset){ oIERangeA = this.oLastRange.oBrowserRange.duplicate(); oIERangeA.collapse(true); }else{ if(elContainerA === this.oLastRange.elEndContainer && nOffsetA === this.oLastRange.nEndOffset){ oIERangeA = this.oLastRange.oBrowserRange.duplicate(); oIERangeA.collapse(false); }else{ oIERangeA = this._getIERangeAt(elContainerA, nOffsetA); } } if(elContainerB === this.oLastRange.elStartContainer && nOffsetB === this.oLastRange.nStartOffset){ oIERangeB = this.oLastRange.oBrowserRange.duplicate(); oIERangeB.collapse(true); }else{ if(elContainerB === this.oLastRange.elEndContainer && nOffsetB === this.oLastRange.nEndOffset){ oIERangeB = this.oLastRange.oBrowserRange.duplicate(); oIERangeB.collapse(false); }else{ oIERangeB = this._getIERangeAt(elContainerB, nOffsetB); } } return oIERangeA.compareEndPoints("StartToStart", oIERangeB); }; this._W3CRange2IERange = function(oW3CRange){ if(this.oLastRange.elStartContainer === oW3CRange.startContainer && this.oLastRange.nStartOffset === oW3CRange.startOffset && this.oLastRange.elEndContainer === oW3CRange.endContainer && this.oLastRange.nEndOffset === oW3CRange.endOffset){ return this.oLastRange.oBrowserRange; } var oStartIERange = this._getIERangeAt(oW3CRange.startContainer, oW3CRange.startOffset); var oEndIERange = this._getIERangeAt(oW3CRange.endContainer, oW3CRange.endOffset); oStartIERange.setEndPoint("EndToEnd", oEndIERange); this._updateLastRange(oStartIERange, oW3CRange); return oStartIERange; }; this._getIERangeAt = function(oW3CContainer, iW3COffset){ var oIERange = this._document.body.createTextRange(); var oEndPointInfoForIERange = this._getSelectableNodeAndOffsetForIE(oW3CContainer, iW3COffset); var oSelectableNode = oEndPointInfoForIERange.oSelectableNodeForIE; var iIEOffset = oEndPointInfoForIERange.iOffsetForIE; oIERange.moveToElementText(oSelectableNode); oIERange.collapse(oEndPointInfoForIERange.bCollapseToStart); oIERange.moveStart("character", iIEOffset); return oIERange; }; this._getSelectableNodeAndOffsetForIE = function(oW3CContainer, iW3COffset){ // var oIERange = this._document.body.createTextRange(); var oNonTextNode = null; var aChildNodes = null; var iNumOfLeftNodesToCount = 0; if(oW3CContainer.nodeType == 3){ oNonTextNode = nhn.DOMFix.parentNode(oW3CContainer); aChildNodes = nhn.DOMFix.childNodes(oNonTextNode); iNumOfLeftNodesToCount = aChildNodes.length; }else{ oNonTextNode = oW3CContainer; aChildNodes = nhn.DOMFix.childNodes(oNonTextNode); //iNumOfLeftNodesToCount = iW3COffset; iNumOfLeftNodesToCount = (iW3COffset<aChildNodes.length)?iW3COffset:aChildNodes.length; } //@ room 4 improvement var oNodeTester = null; var iResultOffset = 0; var bCollapseToStart = true; for(var i=0; i<iNumOfLeftNodesToCount; i++){ oNodeTester = aChildNodes[i]; if(oNodeTester.nodeType == 3){ if(oNodeTester == oW3CContainer){break;} iResultOffset += oNodeTester.nodeValue.length; }else{ // oIERange.moveToElementText(oNodeTester); oNonTextNode = oNodeTester; iResultOffset = 0; bCollapseToStart = false; } } if(oW3CContainer.nodeType == 3){iResultOffset += iW3COffset;} return {oSelectableNodeForIE:oNonTextNode, iOffsetForIE: iResultOffset, bCollapseToStart: bCollapseToStart}; }; this._IERange2W3CRange = function(oIERange){ var oW3CRange = new nhn.W3CDOMRange(this._window); var oIEPointRange = null; var oPosition = null; oIEPointRange = oIERange.duplicate(); oIEPointRange.collapse(true); oPosition = this._getW3CContainerAndOffset(oIEPointRange, true); oW3CRange.setStart(oPosition.oContainer, oPosition.iOffset, true, true); var oCollapsedChecker = oIERange.duplicate(); oCollapsedChecker.collapse(true); if(oCollapsedChecker.isEqual(oIERange)){ oW3CRange.collapse(true); }else{ oIEPointRange = oIERange.duplicate(); oIEPointRange.collapse(false); oPosition = this._getW3CContainerAndOffset(oIEPointRange); oW3CRange.setEnd(oPosition.oContainer, oPosition.iOffset, true); } this._updateLastRange(oIERange, oW3CRange); return oW3CRange; }; this._getW3CContainerAndOffset = function(oIEPointRange, bStartPt){ var oRgOrigPoint = oIEPointRange; var oContainer = oRgOrigPoint.parentElement(); var offset = -1; var oRgTester = this._document.body.createTextRange(); var aChildNodes = nhn.DOMFix.childNodes(oContainer); var oPrevNonTextNode = null; var pointRangeIdx = 0; for(var i=0;i<aChildNodes.length;i++){ if(aChildNodes[i].nodeType == 3){continue;} oRgTester.moveToElementText(aChildNodes[i]); if(oRgTester.compareEndPoints("StartToStart", oIEPointRange)>=0){break;} oPrevNonTextNode = aChildNodes[i]; } var pointRangeIdx = i; if(pointRangeIdx !== 0 && aChildNodes[pointRangeIdx-1].nodeType == 3){ var oRgTextStart = this._document.body.createTextRange(); var oCurTextNode = null; if(oPrevNonTextNode){ oRgTextStart.moveToElementText(oPrevNonTextNode); oRgTextStart.collapse(false); oCurTextNode = oPrevNonTextNode.nextSibling; }else{ oRgTextStart.moveToElementText(oContainer); oRgTextStart.collapse(true); oCurTextNode = oContainer.firstChild; } var oRgTextsUpToThePoint = oRgOrigPoint.duplicate(); oRgTextsUpToThePoint.setEndPoint("StartToStart", oRgTextStart); var textCount = oRgTextsUpToThePoint.text.replace(/[\r\n]/g,"").length; while(textCount > oCurTextNode.nodeValue.length && oCurTextNode.nextSibling){ textCount -= oCurTextNode.nodeValue.length; oCurTextNode = oCurTextNode.nextSibling; } // this will enforce IE to re-reference oCurTextNode var oTmp = oCurTextNode.nodeValue; if(bStartPt && oCurTextNode.nextSibling && oCurTextNode.nextSibling.nodeType == 3 && textCount == oCurTextNode.nodeValue.length){ textCount -= oCurTextNode.nodeValue.length; oCurTextNode = oCurTextNode.nextSibling; } oContainer = oCurTextNode; offset = textCount; }else{ oContainer = oRgOrigPoint.parentElement(); offset = pointRangeIdx; } return {"oContainer" : oContainer, "iOffset" : offset}; }; }; nhn.DOMFix = new (jindo.$Class({ $init : function(){ if(jindo.$Agent().navigator().ie || jindo.$Agent().navigator().opera){ this.childNodes = this._childNodes_Fix; this.parentNode = this._parentNode_Fix; }else{ this.childNodes = this._childNodes_Native; this.parentNode = this._parentNode_Native; } }, _parentNode_Native : function(elNode){ return elNode.parentNode; }, _parentNode_Fix : function(elNode){ if(!elNode){return elNode;} while(elNode.previousSibling){elNode = elNode.previousSibling;} return elNode.parentNode; }, _childNodes_Native : function(elNode){ return elNode.childNodes; }, _childNodes_Fix : function(elNode){ var aResult = null; var nCount = 0; if(elNode){ var aResult = []; elNode = elNode.firstChild; while(elNode){ aResult[nCount++] = elNode; elNode=elNode.nextSibling; } } return aResult; } }))();
JavaScript
/*[ * ADD_APP_PROPERTY * * 주요 오브젝트를 모든 플러그인에서 this.oApp를 통해서 직접 접근 가능 하도록 등록한다. * * sPropertyName string 등록명 * oProperty object 등록시킬 오브젝트 * ---------------------------------------------------------------------------]*/ /*[ * REGISTER_BROWSER_EVENT * * 특정 브라우저 이벤트가 발생 했을때 Husky 메시지를 발생 시킨다. * * obj HTMLElement 브라우저 이벤트를 발생 시킬 HTML 엘리먼트 * sEvent string 발생 대기 할 브라우저 이벤트 * sMsg string 발생 할 Husky 메시지 * aParams array 메시지에 넘길 파라미터 * nDelay number 브라우저 이벤트 발생 후 Husky 메시지 발생 사이에 딜레이를 주고 싶을 경우 설정. (1/1000초 단위) * ---------------------------------------------------------------------------]*/ /*[ * DISABLE_MESSAGE * * 특정 메시지를 코어에서 무시하고 라우팅 하지 않도록 비활성화 한다. * * sMsg string 비활성화 시킬 메시지 * ---------------------------------------------------------------------------]*/ /*[ * ENABLE_MESSAGE * * 무시하도록 설정된 메시지를 무시하지 않도록 활성화 한다. * * sMsg string 활성화 시킬 메시지 * ---------------------------------------------------------------------------]*/ /*[ * EXEC_ON_READY_FUNCTION * * oApp.run({fnOnAppReady:fnOnAppReady})와 같이 run 호출 시점에 지정된 함수가 있을 경우 이를 MSG_APP_READY 시점에 실행 시킨다. * 코어에서 자동으로 발생시키는 메시지로 직접 발생시키지는 않도록 한다. * * none * ---------------------------------------------------------------------------]*/ /** * @pluginDesc Husky Framework에서 자주 사용되는 메시지를 처리하는 플러그인 */ nhn.husky.CorePlugin = jindo.$Class({ name : "CorePlugin", // nStatus = 0(request not sent), 1(request sent), 2(response received) // sContents = response htLazyLoadRequest_plugins : {}, htLazyLoadRequest_allFiles : {}, htHTMLLoaded : {}, $AFTER_MSG_APP_READY : function(){ this.oApp.exec("EXEC_ON_READY_FUNCTION", []); }, $ON_ADD_APP_PROPERTY : function(sPropertyName, oProperty){ this.oApp[sPropertyName] = oProperty; }, $ON_REGISTER_BROWSER_EVENT : function(obj, sEvent, sMsg, aParams, nDelay){ this.oApp.registerBrowserEvent(obj, sEvent, sMsg, aParams, nDelay); }, $ON_DISABLE_MESSAGE : function(sMsg){ this.oApp.disableMessage(sMsg, true); }, $ON_ENABLE_MESSAGE : function(sMsg){ this.oApp.disableMessage(sMsg, false); }, $ON_LOAD_FULL_PLUGIN : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments){ var oPluginRef = oThisRef.$this || oThisRef; // var nIdx = _nIdx||0; var sFilename = aFilenames[0]; if(!this.htLazyLoadRequest_plugins[sFilename]){ this.htLazyLoadRequest_plugins[sFilename] = {nStatus:1, sContents:""}; } if(this.htLazyLoadRequest_plugins[sFilename].nStatus === 2){ //this.oApp.delayedExec("MSG_FULL_PLUGIN_LOADED", [sFilename, sClassName, sMsgName, oThisRef, oArguments, false], 0); this.oApp.exec("MSG_FULL_PLUGIN_LOADED", [sFilename, sClassName, sMsgName, oThisRef, oArguments, false]); }else{ this._loadFullPlugin(aFilenames, sClassName, sMsgName, oThisRef, oArguments, 0); } }, _loadFullPlugin : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx){ jindo.LazyLoading.load(nhn.husky.SE2M_Configuration.LazyLoad.sJsBaseURI+"/"+aFilenames[nIdx], jindo.$Fn(function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx){ var sCurFilename = aFilenames[nIdx]; // plugin filename var sFilename = aFilenames[0]; if(nIdx == aFilenames.length-1){ this.htLazyLoadRequest_plugins[sFilename].nStatus=2; this.oApp.exec("MSG_FULL_PLUGIN_LOADED", [aFilenames, sClassName, sMsgName, oThisRef, oArguments]); return; } //this.oApp.exec("LOAD_FULL_PLUGIN", [aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx+1]); this._loadFullPlugin(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx+1); }, this).bind(aFilenames, sClassName, sMsgName, oThisRef, oArguments, nIdx), "utf-8" ); }, $ON_MSG_FULL_PLUGIN_LOADED : function(aFilenames, sClassName, sMsgName, oThisRef, oArguments, oRes){ // oThisRef.$this는 현재 로드되는 플러그인이 parent 인스턴스일 경우 존재 함. oThisRef.$this는 현재 플러그인(oThisRef)를 parent로 삼고 있는 인스턴스 // oThisRef에 $this 속성이 없다면 parent가 아닌 일반 인스턴스 // oPluginRef는 결과적으로 상속 관계가 있다면 자식 인스턴스를 아니라면 일반적인 인스턴스를 가짐 var oPluginRef = oThisRef.$this || oThisRef; var sFilename = aFilenames; // now the source code is loaded, remove the loader handlers for(var i=0, nLen=oThisRef._huskyFLT.length; i<nLen; i++){ var sLoaderHandlerName = "$BEFORE_"+oThisRef._huskyFLT[i]; // if child class has its own loader function, remove the loader from current instance(parent) only var oRemoveFrom = (oThisRef.$this && oThisRef[sLoaderHandlerName])?oThisRef:oPluginRef; oRemoveFrom[sLoaderHandlerName] = null; this.oApp.createMessageMap(sLoaderHandlerName); } var oPlugin = eval(sClassName+".prototype"); //var oPlugin = eval("new "+sClassName+"()"); var bAcceptLocalBeforeFirstAgain = false; // if there were no $LOCAL_BEFORE_FIRST in already-loaded script, set to accept $LOCAL_BEFORE_FIRST next time as the function could be included in the lazy-loaded script. if(typeof oPluginRef["$LOCAL_BEFORE_FIRST"] !== "function"){ this.oApp.acceptLocalBeforeFirstAgain(oPluginRef, true); } for(var x in oPlugin){ // 자식 인스턴스에 parent를 override하는 함수가 없다면 parent 인스턴스에 함수 복사 해 줌. 이때 함수만 복사하고, 나머지 속성들은 현재 인스턴스에 존재 하지 않을 경우에만 복사. if(oThisRef.$this && (!oThisRef[x] || (typeof oPlugin[x] === "function" && x != "constructor"))){ oThisRef[x] = jindo.$Fn(oPlugin[x], oPluginRef).bind(); } // 현재 인스턴스에 함수 복사 해 줌. 이때 함수만 복사하고, 나머지 속성들은 현재 인스턴스에 존재 하지 않을 경우에만 복사 if(oPlugin[x] && (!oPluginRef[x] || (typeof oPlugin[x] === "function" && x != "constructor"))){ oPluginRef[x] = oPlugin[x]; // 새로 추가되는 함수가 메시지 핸들러라면 메시지 매핑에 추가 해 줌 if(x.match(/^\$(LOCAL|BEFORE|ON|AFTER)_/)){ this.oApp.addToMessageMap(x, oPluginRef); } } } if(bAcceptLocalBeforeFirstAgain){ this.oApp.acceptLocalBeforeFirstAgain(oPluginRef, true); } // re-send the message after all the jindo.$super handlers are executed if(!oThisRef.$this){ this.oApp.exec(sMsgName, oArguments); } }, $ON_LOAD_HTML : function(sId){ if(this.htHTMLLoaded[sId]) return; var elTextarea = jindo.$("_llh_"+sId); if(!elTextarea) return; this.htHTMLLoaded[sId] = true; var elTmp = document.createElement("DIV"); elTmp.innerHTML = elTextarea.value; while(elTmp.firstChild){ elTextarea.parentNode.insertBefore(elTmp.firstChild, elTextarea); } }, $ON_EXEC_ON_READY_FUNCTION : function(){ if(typeof this.oApp.htRunOptions.fnOnAppReady == "function"){this.oApp.htRunOptions.fnOnAppReady();} } });
JavaScript
/** * @name SE2M_QuickEditor_Common * @class * @description Quick Editor Common function Class * @author NHN AjaxUI Lab - mixed * @version 1.0 * @since 2009.09.29 * */ nhn.husky.SE2M_QuickEditor_Common = jindo.$Class({ /** * class 이름 * @type {String} */ name : "SE2M_QuickEditor_Common", /** * 환경 정보. * @type {Object} */ _environmentData : "", /** * 현재 타입 (table|img) * @type {String} */ _currentType :"", /** * 이벤트가 레이어 안에서 호출되었는지 알기 위한 변수 * @type {Boolean} */ _in_event : false, /** * Ajax처리를 하지 않음 * @type {Boolean} */ _bUseConfig : true, /** * 공통 서버에서 개인 설정 받아오는 AjaxUrl * @See SE2M_Configuration.js */ _sBaseAjaxUrl : "", _sAddTextAjaxUrl : "", /** * 초기 인스턴스 생성 실행되는 함수. */ $init : function() { this.waHotkeys = new jindo.$A(); this.waHotkeyLayers = new jindo.$A(); }, $ON_MSG_APP_READY : function() { var htConfiguration = nhn.husky.SE2M_Configuration.QuickEditor; if(htConfiguration){ this._bUseConfig = (!!htConfiguration.common && typeof htConfiguration.common.bUseConfig !== "undefined") ? htConfiguration.common.bUseConfig : true; } if(!this._bUseConfig){ this.setData("{table:'full',img:'full',review:'full'}"); } else { this._sBaseAjaxUrl = htConfiguration.common.sBaseAjaxUrl; this._sAddTextAjaxUrl = htConfiguration.common.sAddTextAjaxUrl; this.getData(); } }, //삭제 시에 qe layer close $ON_EVENT_EDITING_AREA_KEYDOWN : function(oEvent){ var oKeyInfo = oEvent.key(); //Backspace : 8, Delete :46 if (oKeyInfo.keyCode == 8 || oKeyInfo.keyCode == 46 ) { this.oApp.exec("CLOSE_QE_LAYER", [oEvent]); } }, getData : function() { var self = this; jindo.$Ajax(self._sBaseAjaxUrl, { type : "jsonp", timeout : 1, onload: function(rp) { var result = rp.json().result; if (!!result && !!result.length) { self.setData(result[result.length - 1]); } else { self.setData("{table:'full',img:'full',review:'full'}"); } }, onerror : function() { self.setData("{table:'full',img:'full',review:'full'}"); }, ontimeout : function() { self.setData("{table:'full',img:'full',review:'full'}"); } }).request({ text_key : "qeditor_fold" }); }, setData : function(sResult){ var oResult = { table : "full", img : "full", review : "full" }; if(sResult){ oResult = eval("("+sResult+")"); } this._environmentData = { table : { isOpen : false, type : oResult["table"],//full,fold, isFixed : false, position : [] }, img : { isOpen : false, type : oResult["img"],//full,fold isFixed : false }, review : { isOpen : false, type : oResult["review"],//full,fold isFixed : false, position : [] } }; this.waTableTagNames =jindo.$A(["table","tbody","td","tfoot","th","thead","tr"]); }, /** * 위지윅 영역에 단축키가 등록될 때, * tab 과 shift+tab (들여쓰기 / 내어쓰기 ) 를 제외한 단축키 리스트를 저장한다. */ $ON_REGISTER_HOTKEY : function(sHotkey, sCMD, aArgs){ if(sHotkey != "tab" && sHotkey != "shift+tab"){ this.waHotkeys.push([sHotkey, sCMD, aArgs]); } }, //@lazyload_js OPEN_QE_LAYER[ $ON_MSG_BEFOREUNLOAD_FIRED : function(){ if (!this._environmentData || !this._bUseConfig) { return; } jindo.$Ajax(this._sAddTextAjaxUrl,{ type : "jsonp", onload: function(){} }).request({ text_key :"qeditor_fold", text_data : "{table:'"+this._environmentData["table"]["type"]+"',img:'"+this._environmentData["img"]["type"]+"',review:'"+this._environmentData["review"]["type"]+"'}" }); }, /** * openType을 저장하는 함수. * @param {String} sType * @param {Boolean} bBol */ setOpenType : function(sType,bBol){ this._environmentData[sType].isOpen = bBol; }, /** * 레이어가 오픈 할 때 실행되는 이벤트. * 레이어가 처음 뜰 때, * 저장된 단축키 리스트를 레이어에 등록하고 (레이어가 떠 있을때도 단축키가 먹도록 하기 위해) * 레이어에 대한 키보드/마우스 이벤트를 등록한다. * @param {Element} oEle * @param {Element} oLayer * @param {String} sType(img|table|review) */ $ON_OPEN_QE_LAYER : function(oEle,oLayer,sType){ if(this.waHotkeys.length() > 0 && !this.waHotkeyLayers.has(oLayer)){ this.waHotkeyLayers.push(oLayer); var aParam; for(var i=0, nLen=this.waHotkeys.length(); i<nLen; i++){ aParam = this.waHotkeys.get(i); this.oApp.exec("ADD_HOTKEY", [aParam[0], aParam[1], aParam[2], oLayer]); } } var type = sType;//?sType:"table";//this.get_type(oEle); if(type){ this.targetEle = oEle; this.currentEle = oLayer; this.layer_show(type,oEle); } }, /** * 레이어가 닫혔을때 실행되는 이벤트. * @param {jindo.$Event} weEvent */ $ON_CLOSE_QE_LAYER : function(weEvent){ if(!this.currentEle){return;} // this.oApp.exec("HIDE_EDITING_AREA_COVER"); // this.oApp.exec("ENABLE_ALL_UI"); this.oApp.exec("CLOSE_SUB_LAYER_QE"); this.layer_hide(weEvent); }, /** * 어플리케이션이 준비단계일때 실행되는 이벤트 */ $LOCAL_BEFORE_FIRST : function(sMsg) { if (!sMsg.match(/OPEN_QE_LAYER/)) { // (sMsg == "$ON_CLOSE_QE_LAYER" && !this.currentEle) this.oApp.acceptLocalBeforeFirstAgain(this, true); if(sMsg.match(/REGISTER_HOTKEY/)){ return true; } return false; } this.woEditor = jindo.$Element(this.oApp.elEditingAreaContainer); this.woStandard = jindo.$Element(this.oApp.htOptions.elAppContainer).offset(); this._qe_wrap = jindo.$$.getSingle("DIV.quick_wrap", this.oApp.htOptions.elAppContainer); var that = this; new jindo.DragArea(this._qe_wrap, { sClassName : 'q_dragable', bFlowOut : false, nThreshold : 1 }).attach({ beforeDrag : function(oCustomEvent) { oCustomEvent.elFlowOut = oCustomEvent.elArea.parentNode; }, dragStart: function(oCustomEvent){ if(!jindo.$Element(oCustomEvent.elDrag).hasClass('se2_qmax')){ oCustomEvent.elDrag = oCustomEvent.elDrag.parentNode; } that.oApp.exec("SHOW_EDITING_AREA_COVER"); }, dragEnd : function(oCustomEvent){ that.changeFixedMode(); that._in_event = false; //if(that._currentType=="review"||that._currentType=="table"){ // [SMARTEDITORSUS-153] 이미지 퀵 에디터도 같은 로직으로 처리하도록 수정 var richEle = jindo.$Element(oCustomEvent.elDrag); that._environmentData[that._currentType].position = [richEle.css("top"),richEle.css("left")]; //} that.oApp.exec("HIDE_EDITING_AREA_COVER"); } }); var imgFn = jindo.$Fn(this.toggle,this).bind("img"); var tableFn = jindo.$Fn(this.toggle,this).bind("table"); jindo.$Fn(imgFn,this).attach(jindo.$$.getSingle(".q_open_img_fold", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(imgFn,this).attach(jindo.$$.getSingle(".q_open_img_full", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(tableFn,this).attach(jindo.$$.getSingle(".q_open_table_fold", this.oApp.htOptions.elAppContainer),"click"); jindo.$Fn(tableFn,this).attach(jindo.$$.getSingle(".q_open_table_full", this.oApp.htOptions.elAppContainer),"click"); }, /** * 레이어의 최대화/최소화를 토글링 하는 함수. * @param {String} sType(table|img) * @param {jindo.$Event} weEvent */ toggle : function(sType,weEvent){ sType = this._currentType; // var oBefore = jindo.$Element(jindo.$$.getSingle("._"+this._environmentData[sType].type,this.currentEle)); // var beforeX = oBefore.css("left"); // var beforeY = oBefore.css("top"); this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); if(this._environmentData[sType].type=="full"){ this._environmentData[sType].type = "fold"; }else{ this._environmentData[sType].type = "full"; } // this.positionCopy(beforeX,beforeY,this._environmentData[sType].type); this.oApp.exec("OPEN_QE_LAYER", [this.targetEle,this.currentEle,sType]); this._in_event = false; weEvent.stop(jindo.$Event.CANCEL_DEFAULT); }, /** * 토글링시 전에 엘리먼트에 위치를 카피하는 함수. * @param {Number} beforeX * @param {Number} beforeY * @param {Element} sAfterEle */ positionCopy:function(beforeX, beforeY, sAfterEle){ jindo.$Element(jindo.$$.getSingle("._"+sAfterEle,this.currentEle)).css({ top : beforeY, left : beforeX }); }, /** * 레이어를 고정으로 할때 실행되는 함수. */ changeFixedMode : function(){ this._environmentData[this._currentType].isFixed = true; }, /** * 에디팅 영역에서 keyup할때 실행되는 함수. * @param {jindo.$Event} weEvent */ /* $ON_EVENT_EDITING_AREA_KEYUP:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, */ $ON_HIDE_ACTIVE_LAYER : function(){ this.oApp.exec("CLOSE_QE_LAYER"); }, /** * 에디팅 영역에서 mousedown할때 실행되는 함수. * @param {jindo.$Event} weEvent */ $ON_EVENT_EDITING_AREA_MOUSEDOWN:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, /** * 에디팅 영역에서 mousewheel할때 실행되는 함수. * @param {jindo.$Event} weEvent */ $ON_EVENT_EDITING_AREA_MOUSEWHEEL:function(weEvent){ if(this._currentType&&(!this._in_event)&&this._environmentData[this._currentType].isOpen){ this.oApp.exec("CLOSE_QE_LAYER", [weEvent]); } this._in_event = false; }, /** * 레이어를 띄우는데 레이어가 table(템플릿),img인지를 확인하여 id를 반환하는 함수. * @param {Element} oEle * @return {String} layer id */ get_type : function(oEle){ var tagName = oEle.tagName.toLowerCase(); if(this.waTableTagNames.has(tagName)){ return "table"; }else if(tagName=="img"){ return "img"; } }, /** * 퀵에디터에서 keyup시 실행되는 이벤트 */ $ON_QE_IN_KEYUP : function(){ this._in_event = true; }, /** * 퀵에디터에서 mousedown시 실행되는 이벤트 */ $ON_QE_IN_MOUSEDOWN : function(){ this._in_event = true; }, /** * 퀵에디터에서 mousewheel시 실행되는 이벤트 */ $ON_QE_IN_MOUSEWHEEL : function(){ this._in_event = true; }, /** * 레이어를 숨기는 함수. * @param {jindo.$Event} weEvent */ layer_hide : function(weEvent){ this.setOpenType(this._currentType,false); jindo.$Element(jindo.$$.getSingle("._"+this._environmentData[this._currentType].type,this.currentEle)).hide(); }, /** * 늦게 이벤트 바인딩 하는 함수. * 레이어가 처음 뜰 때 이벤트를 등록한다. */ lazy_common : function(){ this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "keyup", "QE_IN_KEYUP"); this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "mousedown", "QE_IN_MOUSEDOWN"); this.oApp.registerBrowserEvent(jindo.$(this._qe_wrap), "mousewheel", "QE_IN_MOUSEWHEEL"); this.lazy_common = function(){}; }, /** * 레이어를 보여주는 함수. * @param {String} sType * @param {Element} oEle */ layer_show : function(sType,oEle){ this._currentType = sType; this.setOpenType(this._currentType,true); var layer = jindo.$$.getSingle("._"+this._environmentData[this._currentType].type,this.currentEle); jindo.$Element(layer) .show() .css( this.get_position_layer(oEle , layer) ); this.lazy_common(); }, /** * 레이어의 위치를 반환 하는 함수 * 고정 상태가 아니거나 최소화 상태이면 엘리먼트 위치에 퀵에디터를 띄우고 * 고정 상태이고 최대화 상태이면 표나 글 양식은 저장된 위치에 띄워주고, 이미지는...? * @param {Element} oEle * @param {Element} oLayer */ get_position_layer : function(oEle , oLayer){ if(!this.isCurrentFixed() || this._environmentData[this._currentType].type == "fold"){ return this.calculateLayer(oEle , oLayer); } //if(this._currentType == "review" || this._currentType == "table"){ // [SMARTEDITORSUS-153] 이미지 퀵 에디터도 같은 로직으로 처리하도록 수정 var position = this._environmentData[this._currentType].position; var nTop = parseInt(position[0], 10); var nAppHeight = this.getAppPosition().h; var nLayerHeight = jindo.$Element(oLayer).height(); // [SMARTEDITORSUS-129] 편집 영역 높이를 줄였을 때 퀵에디터가 영역을 벗어나지 않도록 처리 if((nTop + nLayerHeight + this.nYGap) > nAppHeight){ nTop = nAppHeight - nLayerHeight; this._environmentData[this._currentType].position[0] = nTop; } return { top : nTop + "px", left :position[1] }; //} //return this.calculateLayer(null , oLayer); }, /** * 현재 레이어가 고정형태인지 반환하는 함수. */ isCurrentFixed : function(){ return this._environmentData[this._currentType].isFixed; }, /** * 레이어를 띄울 위치를 계산하는 함수. * @param {Element} oEle * @param {Element} oLayer */ calculateLayer : function(oEle, oLayer){ /* * 기준을 한군데로 만들어야 함. * 1. 에디터는 페이지 * 2. 엘리먼트는 안에 에디팅 영역 * 3. 레이어는 에디팅 영역 * * 기준은 페이지로 함. */ var positionInfo = this.getPositionInfo(oEle, oLayer); return { top : positionInfo.y + "px", left : positionInfo.x + "px" }; }, /** * 위치를 반환 하는 함수. * @param {Element} oEle * @param {Element} oLayer */ getPositionInfo : function(oEle, oLayer){ this.nYGap = jindo.$Agent().navigator().ie? -16 : -18; this.nXGap = 1; var oRevisePosition = {}; var eleInfo = this.getElementPosition(oEle, oLayer); var appInfo = this.getAppPosition(); var layerInfo = { w : jindo.$Element(oLayer).width(), h : jindo.$Element(oLayer).height() }; if((eleInfo.x + layerInfo.w + this.nXGap) > appInfo.w){ oRevisePosition.x = appInfo.w - layerInfo.w ; }else{ oRevisePosition.x = eleInfo.x + this.nXGap; } if((eleInfo.y + layerInfo.h + this.nYGap) > appInfo.h){ oRevisePosition.y = appInfo.h - layerInfo.h - 2; }else{ oRevisePosition.y = eleInfo.y + this.nYGap; } return { x : oRevisePosition.x , y : oRevisePosition.y }; }, /** * 기준 엘리먼트의 위치를 반환하는 함수 * 엘리먼트가 있는 경우 * @param {Element} eEle */ getElementPosition : function(eEle, oLayer){ var wEle, oOffset, nEleWidth, nEleHeight, nScrollX, nScrollY; if(eEle){ wEle = jindo.$Element(eEle); oOffset = wEle.offset(); nEleWidth = wEle.width(); nEleHeight = wEle.height(); }else{ oOffset = { top : parseInt(oLayer.style.top, 10) - this.nYGap, left : parseInt(oLayer.style.left, 10) - this.nXGap }; nEleWidth = 0; nEleHeight = 0; } var oAppWindow = this.oApp.getWYSIWYGWindow(); if(typeof oAppWindow.scrollX == "undefined"){ nScrollX = oAppWindow.document.documentElement.scrollLeft; nScrollY = oAppWindow.document.documentElement.scrollTop; }else{ nScrollX = oAppWindow.scrollX; nScrollY = oAppWindow.scrollY; } var oEditotOffset = this.woEditor.offset(); return { x : oOffset.left - nScrollX + nEleWidth, y : oOffset.top - nScrollY + nEleHeight }; }, /** * 에디터의 크기 계산하는 함수. */ getAppPosition : function(){ return { w : this.woEditor.width(), h : this.woEditor.height() }; } //@lazyload_js] });
JavaScript
//{ /** * @fileOverview This file contains Husky plugin that takes care of the operations related to the tool bar UI * @name hp_SE2M_Toolbar.js */ nhn.husky.SE2M_Toolbar = jindo.$Class({ name : "SE2M_Toolbar", toolbarArea : null, toolbarButton : null, uiNameTag : "uiName", // 0: unknown // 1: all enabled // 2: all disabled nUIStatus : 1, sUIClassPrefix : "husky_seditor_ui_", aUICmdMap : null, _assignHTMLElements : function(oAppContainer){ oAppContainer = jindo.$(oAppContainer) || document; this.rxUI = new RegExp(this.sUIClassPrefix+"([^ ]+)"); //@ec[ this.toolbarArea = jindo.$$.getSingle(".se2_tool", oAppContainer); this.aAllUI = jindo.$$("[class*=" + this.sUIClassPrefix + "]", this.toolbarArea); //@ec] this.welToolbarArea = jindo.$Element(this.toolbarArea); for (var i = 0, nCount = this.aAllUI.length; i < nCount; i++) { if (this.rxUI.test(this.aAllUI[i].className)) { var sUIName = RegExp.$1; if(this.htUIList[sUIName] !== undefined){ continue; } this.htUIList[sUIName] = this.aAllUI[i]; this.htWrappedUIList[sUIName] = jindo.$Element(this.htUIList[sUIName]); } } }, $init : function(oAppContainer){ this.htUIList = {}; this.htWrappedUIList = {}; this.aUICmdMap = {}; this._assignHTMLElements(oAppContainer); }, $ON_MSG_APP_READY : function(){ this.oApp.registerBrowserEvent(this.toolbarArea, "mouseover", "EVENT_TOOLBAR_MOUSEOVER", []); this.oApp.registerBrowserEvent(this.toolbarArea, "mouseout", "EVENT_TOOLBAR_MOUSEOUT", []); this.oApp.registerBrowserEvent(this.toolbarArea, "mousedown", "EVENT_TOOLBAR_MOUSEDOWN", []); /* var aBtns = jindo.$$("BUTTON", this.toolbarArea); for(var i=0; i<aBtns.length; i++){ this.oApp.registerBrowserEvent(aBtns[i], "focus", "EVENT_TOOLBAR_MOUSEOVER", []); this.oApp.registerBrowserEvent(aBtns[i], "blur", "EVENT_TOOLBAR_MOUSEOUT", []); } */ this.oApp.exec("ADD_APP_PROPERTY", ["getToolbarButtonByUIName", jindo.$Fn(this.getToolbarButtonByUIName, this).bind()]); }, $ON_TOGGLE_TOOLBAR_ACTIVE_LAYER : function(elLayer, elBtn, sOpenCmd, aOpenArgs, sCloseCmd, aCloseArgs){ this.oApp.exec("TOGGLE_ACTIVE_LAYER", [elLayer, "MSG_TOOLBAR_LAYER_SHOWN", [elLayer, elBtn, sOpenCmd, aOpenArgs], sCloseCmd, aCloseArgs]); }, $ON_MSG_TOOLBAR_LAYER_SHOWN : function(elLayer, elBtn, aOpenCmd, aOpenArgs){ this.oApp.exec("POSITION_TOOLBAR_LAYER", [elLayer, elBtn]); if(aOpenCmd){ this.oApp.exec(aOpenCmd, aOpenArgs); } }, $ON_SHOW_TOOLBAR_ACTIVE_LAYER : function(elLayer, sCmd, aArgs, elBtn){ this.oApp.exec("SHOW_ACTIVE_LAYER", [elLayer, sCmd, aArgs]); this.oApp.exec("POSITION_TOOLBAR_LAYER", [elLayer, elBtn]); }, $ON_ENABLE_UI : function(sUIName){ this._enableUI(sUIName); }, $ON_DISABLE_UI : function(sUIName){ this._disableUI(sUIName); }, $ON_SELECT_UI : function(sUIName){ var welUI = this.htWrappedUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("hover"); welUI.addClass("active"); }, $ON_DESELECT_UI : function(sUIName){ var welUI = this.htWrappedUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("active"); }, $ON_ENABLE_ALL_UI : function(htOptions){ if(this.nUIStatus === 1){ return; } var sUIName, className; htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); for(var sUIName in this.htUIList){ if(sUIName && !waExceptions.has(sUIName)){ this._enableUI(sUIName); } // if(sUIName) this.oApp.exec("ENABLE_UI", [sUIName]); } // jindo.$Element(this.toolbarArea).removeClass("off"); this.nUIStatus = 1; }, $ON_DISABLE_ALL_UI : function(htOptions){ if(this.nUIStatus === 2){ return; } var sUIName; htOptions = htOptions || {}; var waExceptions = jindo.$A(htOptions.aExceptions || []); var bLeavlActiveLayer = htOptions.bLeaveActiveLayer || false; if(!bLeavlActiveLayer){ this.oApp.exec("HIDE_ACTIVE_LAYER",[]); } for(var sUIName in this.htUIList){ if(sUIName && !waExceptions.has(sUIName)){ this._disableUI(sUIName); } // if(sUIName) this.oApp.exec("DISABLE_UI", [sUIName]); } // jindo.$Element(this.toolbarArea).addClass("off"); this.nUIStatus = 2; }, $ON_MSG_STYLE_CHANGED : function(sAttributeName, attributeValue){ if(attributeValue === "@^"){ this.oApp.exec("SELECT_UI", [sAttributeName]); }else{ this.oApp.exec("DESELECT_UI", [sAttributeName]); } }, $ON_POSITION_TOOLBAR_LAYER : function(elLayer, htOption){ elLayer = jindo.$(elLayer); htOption = htOption || {}; var elBtn = jindo.$(htOption.elBtn); var sAlign = htOption.sAlign; var nMargin = -1; if(!elLayer){ return; } if(elBtn && elBtn.tagName && elBtn.tagName == "BUTTON"){ elBtn.parentNode.appendChild(elLayer); } var welLayer = jindo.$Element(elLayer); if(sAlign != "right"){ elLayer.style.left = "0"; var nLayerLeft = welLayer.offset().left; var nLayerRight = nLayerLeft + elLayer.offsetWidth; var nToolbarLeft = this.welToolbarArea.offset().left; var nToolbarRight = nToolbarLeft + this.toolbarArea.offsetWidth; if(nLayerRight > nToolbarRight){ welLayer.css("left", (nToolbarRight-nLayerRight-nMargin)+"px"); } if(nLayerLeft < nToolbarLeft){ welLayer.css("left", (nToolbarLeft-nLayerLeft+nMargin)+"px"); } }else{ elLayer.style.right = "0"; var nLayerLeft = welLayer.offset().left; var nLayerRight = nLayerLeft + elLayer.offsetWidth; var nToolbarLeft = this.welToolbarArea.offset().left; var nToolbarRight = nToolbarLeft + this.toolbarArea.offsetWidth; if(nLayerRight > nToolbarRight){ welLayer.css("right", -1*(nToolbarRight-nLayerRight-nMargin)+"px"); } if(nLayerLeft < nToolbarLeft){ welLayer.css("right", -1*(nToolbarLeft-nLayerLeft+nMargin)+"px"); } } }, $ON_EVENT_TOOLBAR_MOUSEOVER : function(weEvent){ if(this.nUIStatus === 2){ return; } var aAffectedElements = this._getAffectedElements(weEvent.element); for(var i=0; i<aAffectedElements.length; i++){ if(!aAffectedElements[i].hasClass("active")){ aAffectedElements[i].addClass("hover"); } } }, $ON_EVENT_TOOLBAR_MOUSEOUT : function(weEvent){ if(this.nUIStatus === 2){ return; } var aAffectedElements = this._getAffectedElements(weEvent.element); for(var i=0; i<aAffectedElements.length; i++){ aAffectedElements[i].removeClass("hover"); } }, $ON_EVENT_TOOLBAR_MOUSEDOWN : function(weEvent){ var elTmp = weEvent.element; // Check if the button pressed is in active status and has a visible layer i.e. the button had been clicked and its layer is open already. (buttons like font styles-bold, underline-got no sub layer -> childNodes.length<=2) // -> In this case, do not close here(mousedown). The layer will be closed on "click". If we close the layer here, the click event will open it again because it toggles the visibility. while(elTmp){ if(elTmp.className && elTmp.className.match(/active/) && (elTmp.childNodes.length>2 || elTmp.parentNode.className.match(/se2_pair/))){ return; } elTmp = elTmp.parentNode; } this.oApp.exec("HIDE_ACTIVE_LAYER_IF_NOT_CHILD", [weEvent.element]); }, _enableUI : function(sUIName){ this.nUIStatus = 0; var welUI = this.htWrappedUIList[sUIName]; var elUI = this.htUIList[sUIName]; if(!welUI){ return; } welUI.removeClass("off"); var aAllBtns = elUI.getElementsByTagName("BUTTON"); for(var i=0, nLen=aAllBtns.length; i<nLen; i++){ aAllBtns[i].disabled = false; } // enable related commands var sCmd = ""; if(this.aUICmdMap[sUIName]){ for(var i=0; i<this.aUICmdMap[sUIName].length;i++){ sCmd = this.aUICmdMap[sUIName][i]; this.oApp.exec("ENABLE_MESSAGE", [sCmd]); } } }, _disableUI : function(sUIName){ this.nUIStatus = 0; var welUI = this.htWrappedUIList[sUIName]; var elUI = this.htUIList[sUIName]; if(!welUI){ return; } welUI.addClass("off"); welUI.removeClass("hover"); var aAllBtns = elUI.getElementsByTagName("BUTTON"); for(var i=0, nLen=aAllBtns.length; i<nLen; i++){ aAllBtns[i].disabled = true; } // disable related commands var sCmd = ""; if(this.aUICmdMap[sUIName]){ for(var i=0; i<this.aUICmdMap[sUIName].length;i++){ sCmd = this.aUICmdMap[sUIName][i]; this.oApp.exec("DISABLE_MESSAGE", [sCmd]); } } }, _getAffectedElements : function(el){ var elLi, welLi; // 버튼 클릭시에 return false를 해 주지 않으면 chrome에서 버튼이 포커스 가져가 버림. // 에디터 로딩 시에 일괄처리 할 경우 로딩 속도가 느려짐으로 hover시에 하나씩 처리 if(!el.bSE2_MDCancelled){ el.bSE2_MDCancelled = true; var aBtns = el.getElementsByTagName("BUTTON"); for(var i=0, nLen=aBtns.length; i<nLen; i++){ aBtns[i].onmousedown = function(){return false}; } } if(!el || !el.tagName) return []; if((elLi = el).tagName == "BUTTON"){ // typical button // <LI> // <BUTTON> if((elLi = elLi.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } // button pair // <LI> // <SPAN> // <BUTTON> // <SPAN> // <BUTTON> elLi = el; if((elLi = elLi.parentNode.parentNode) && elLi.tagName == "LI" && (welLi = jindo.$Element(elLi)).hasClass("se2_pair")){ return [welLi, jindo.$Element(el.parentNode)]; } return []; } // span in a button if((elLi = el).tagName == "SPAN"){ // <LI> // <BUTTON> // <SPAN> if((elLi = elLi.parentNode.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } // <LI> // <SPAN> //글감과 글양식 if((elLi = elLi.parentNode) && elLi.tagName == "LI" && this.rxUI.test(elLi.className)){ return [jindo.$Element(elLi)]; } } return []; }, $ON_REGISTER_UI_EVENT : function(sUIName, sEvent, sCmd, aParams){ //[SMARTEDITORSUS-966][IE8 표준/IE 10] 호환 모드를 제거하고 사진 첨부 시 에디팅 영역의 // 커서 주위에 <sub><sup> 태그가 붙어서 글자가 매우 작게 되는 현상 //원인 : 아래의 [SMARTEDITORSUS-901] 수정 내용에서 윗첨자 아랫첨자 이벤트 등록 시 //해당 플러그인이 마크업에 없으면 this.htUIList에 존재하지 않아 getsingle 사용시 사진첨부에 이벤트가 걸렸음 //해결 : this.htUIList에 존재하지 않으면 이벤트를 등록하지 않음 if(!this.htUIList[sUIName]){ return; } // map cmd & ui var elButton; if(!this.aUICmdMap[sUIName]){this.aUICmdMap[sUIName] = [];} this.aUICmdMap[sUIName][this.aUICmdMap[sUIName].length] = sCmd; //[SMARTEDITORSUS-901]플러그인 태그 코드 추가 시 <li>태그와<button>태그 사이에 개행이 있으면 이벤트가 등록되지 않는 현상 //원인 : IE9, Chrome, FF, Safari 에서는 태그를 개행 시 그 개행을 text node로 인식하여 firstchild가 text 노드가 되어 버튼 이벤트가 할당되지 않음 //해결 : firstchild에 이벤트를 거는 것이 아니라, child 중 button 인 것에 이벤트를 걸도록 변경 elButton = jindo.$$.getSingle('button', this.htUIList[sUIName]); if(!elButton){return;} this.oApp.registerBrowserEvent(elButton, sEvent, sCmd, aParams); }, getToolbarButtonByUIName : function(sUIName){ return jindo.$$.getSingle("BUTTON", this.htUIList[sUIName]); } }); //}
JavaScript
/* ******************************************************************** ********************************************************************** * HTML Virtual Keyboard Interface Script - v1.32 * Copyright (c) 2009 - GreyWyvern * * - Licenced for free distribution under the BSDL * http://www.opensource.org/licenses/bsd-license.php * * Add a script-driven keyboard interface to text fields, password * fields and textareas. * * See http://www.greywyvern.com/code/javascript/keyboard for examples * and usage instructions. * * Version 1.32 - December 31, 2009 * - Added keyboard position switch function * - Added some CSS3 styles * - Added Pashto keyboard layout * - Added Macedonian keyboard layout * - Added Ukrainian keyboard layout * * See full changelog at: * http://www.greywyvern.com/code/javascript/keyboard.changelog.txt * * Keyboard Credits * - Ukrainian keyboard layout by Dmitry Nikitin * - Macedonian keyboard layout by Damjan Dimitrioski * - Pashto keyboard layout by Ahmad Wali Achakzai (qamosona.com) * - Armenian Eastern and Western keyboard layouts by Hayastan Project (www.hayastan.co.uk) * - Pinyin keyboard layout from a collaboration with Lou Winklemann * - Kazakh keyboard layout by Alex Madyankin * - Danish keyboard layout by Verner Kjærsgaard * - Slovak keyboard layout by Daniel Lara (www.learningslovak.com) * - Belarusian, Serbian Cyrillic and Serbian Latin keyboard layouts by Evgeniy Titov * - Bulgarian Phonetic keyboard layout by Samuil Gospodinov * - Swedish keyboard layout by Håkan Sandberg * - Romanian keyboard layout by Aurel * - Farsi (Persian) keyboard layout by Kaveh Bakhtiyari (www.bakhtiyari.com) * - Burmese keyboard layout by Cetanapa * - Slovenian keyboard layout by Miran Zeljko * - Hungarian keyboard layout by Antal Sall 'Hiromacu' * - Arabic keyboard layout by Srinivas Reddy * - Italian and Spanish (Spain) keyboard layouts by dictionarist.com * - Lithuanian and Russian keyboard layouts by Ramunas * - German keyboard layout by QuHno * - French keyboard layout by Hidden Evil * - Polish Programmers layout by moose * - Turkish keyboard layouts by offcu * - Dutch and US Int'l keyboard layouts by jerone * */ // you need to modify these to intercept the calls... function razInsert(s) { try { razInvoke ('/mutant/robot/razKeyboard?key='+s+'&state='+false) } catch(e) {} } function razModify(s,b) { try { razInvoke ('/mutant/robot/razKeyboard?key='+s+'&state='+b) } catch(e) {} } var VKI_attach, VKI_close, razShow; function VKI_buildKeyboardInputs() { var self = this; this.VKI_version = "1.32"; this.VKI_showVersion = true; this.VKI_target = this.VKI_visible = false; this.VKI_shift = this.VKI_shiftlock = false; this.VKI_altgr = this.VKI_altgrlock = false; this.VKI_switcher = true; // show the position switcher this.VKI_above = 0; // 0 = below the input, 1 = above this.VKI_dead = false; this.VKI_deadkeysOn = false; this.VKI_kt = "US Int'l"; // Default keyboard layout this.VKI_clearPasswords = false; // Clear password fields on focus this.VKI_imageURI = "/mutant/public/keyboard.png"; this.VKI_clickless = 0; // 0 = disabled, > 0 = delay in ms this.VKI_keyCenter = 3; this.VKI_isIE = /*@cc_on!@*/false; this.VKI_isIE6 = /*@if(@_jscript_version == 5.6)!@end@*/false; this.VKI_isIElt8 = /*@if(@_jscript_version < 5.8)!@end@*/false; this.VKI_isMoz = (navigator.product == "Gecko"); this.VKI_isWebKit = RegExp("KHTML").test(navigator.userAgent); /* ***** Create keyboards ************************************** */ this.VKI_layout = {}; // - Lay out each keyboard in rows of sub-arrays. Each sub-array // represents one key. // // - Each sub-array consists of four slots described as follows: // example: ["a", "A", "\u00e1", "\u00c1"] // // a) Normal character // A) Character + Shift/Caps // \u00e1) Character + Alt/AltGr/AltLk // \u00c1) Character + Shift/Caps + Alt/AltGr/AltLk // // You may include sub-arrays which are fewer than four slots. // In these cases, the missing slots will be blanked when the // corresponding modifier key (Shift or AltGr) is pressed. // // - If the second slot of a sub-array matches one of the following // strings: // "Tab", "Caps", "Shift", "Enter", "Bksp", // "Alt" OR "AltGr", "AltLk" // then the function of the key will be the following, // respectively: // - Insert a tab // - Toggle Caps Lock (technically a Shift Lock) // - Next entered character will be the shifted character // - Insert a newline (textarea), or close the keyboard // - Delete the previous character // - Next entered character will be the alternate character // - Toggle Alt/AltGr Lock // // The first slot of this sub-array will be the text to display // on the corresponding key. This allows for easy localisation // of key names. // // - Layout dead keys (diacritic + letter) should be added as // arrays of two item arrays with hash keys equal to the // diacritic. See the "this.VKI_deadkey" object below the layout // definitions. In each two item child array, the second item // is what the diacritic would change the first item to. // // - To disable dead keys for a layout, simply assign true to the // DDK property of the layout (DDK = disable dead keys). See the // Numpad layout below for an example. // // - Note that any characters beyond the normal ASCII set should be // entered in escaped Unicode format. (eg \u00a3 = Pound symbol) // You can find Unicode values for characters here: // http://unicode.org/charts/ // // - To remove a keyboard, just delete it, or comment it out of the // source code this.VKI_layout.Arabic = [ // Arabic Keyboard [["\u0630", "\u0651 "], ["1", "!", "\u00a1", "\u00b9"], ["2", "@", "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00a4", "\u00a3"], ["5", "%", "\u20ac"], ["6", "^", "\u00bc"], ["7", "&", "\u00bd"], ["8", "*", "\u00be"], ["9", "(", "\u2018"], ["0", ")", "\u2019"], ["-", "_", "\u00a5"], ["=", "+", "\u00d7", "\u00f7"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0636", "\u064e"], ["\u0635", "\u064b"], ["\u062b", "\u064f"], ["\u0642", "\u064c"], ["\u0641", "\u0644"], ["\u063a", "\u0625"], ["\u0639", "\u2018"], ["\u0647", "\u00f7"], ["\u062e", "\u00d7"], ["\u062d", "\u061b"], ["\u062c", "\u003c"], ["\u062f", "\u003e"], ["\u005c", "\u007c"]], [["Caps", "Caps"], ["\u0634", "\u0650"], ["\u0633", "\u064d"], ["\u064a", "\u005d"], ["\u0628", "\u005b"], ["\u0644", "\u0644"], ["\u0627", "\u0623"], ["\u062a", "\u0640"], ["\u0646", "\u060c"], ["\u0645", "\u002f"], ["\u0643", "\u003a"], ["\u0637", "\u0022"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u0626", "\u007e"], ["\u0621", "\u0652"], ["\u0624", "\u007d"], ["\u0631", "\u007b"], ["\u0644", "\u0644"], ["\u0649", "\u0622"], ["\u0629", "\u2019"], ["\u0648", "\u002c"], ["\u0632", "\u002e"], ["\u0638", "\u061f"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout["Armenian East"] = [ // Eastern Armenian Keyboard [["\u055D", "\u055C"], [":", "1"], ["\u0571", "\u0541"], ["\u0575", "\u0545"], ["\u055B", "3"], [",", "4"], ["-", "9"], [".", "\u0587"], ["\u00AB", "("], ["\u00BB", ")"], ["\u0585", "\u0555"], ["\u057C", "\u054C"], ["\u056A", "\u053A"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u056D", "\u053D"], ["\u0582", "\u0552"], ["\u0567", "\u0537"], ["\u0580", "\u0550"], ["\u057F", "\u054F"], ["\u0565", "\u0535"], ["\u0568", "\u0538"], ["\u056B", "\u053B"], ["\u0578", "\u0548"], ["\u057A", "\u054A"], ["\u0579", "\u0549"], ["\u057B", "\u054B"], ["'", "\u055E"]], [["Caps", "Caps"], ["\u0561", "\u0531"], ["\u057D", "\u054D"], ["\u0564", "\u0534"], ["\u0586", "\u0556"], ["\u0584", "\u0554"], ["\u0570", "\u0540"], ["\u0573", "\u0543"], ["\u056F", "\u053F"], ["\u056C", "\u053C"], ["\u0569", "\u0539"], ["\u0583", "\u0553"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u0566", "\u0536"], ["\u0581", "\u0551"], ["\u0563", "\u0533"], ["\u057E", "\u054E"], ["\u0562", "\u0532"], ["\u0576", "\u0546"], ["\u0574", "\u0544"], ["\u0577", "\u0547"], ["\u0572", "\u0542"], ["\u056E", "\u053E"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout["Armenian West"] = [ // Western Armenian Keyboard [["\u055D", "\u055C"], [":", "1"], ["\u0571", "\u0541"], ["\u0575", "\u0545"], ["\u055B", "3"], [",", "4"], ["-", "9"], [".", "\u0587"], ["\u00AB", "("], ["\u00BB", ")"], ["\u0585", "\u0555"], ["\u057C", "\u054C"], ["\u056A", "\u053A"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u056D", "\u053D"], ["\u057E", "\u054E"], ["\u0567", "\u0537"], ["\u0580", "\u0550"], ["\u0564", "\u0534"], ["\u0565", "\u0535"], ["\u0568", "\u0538"], ["\u056B", "\u053B"], ["\u0578", "\u0548"], ["\u0562", "\u0532"], ["\u0579", "\u0549"], ["\u057B", "\u054B"], ["'", "\u055E"]], [["Caps", "Caps"], ["\u0561", "\u0531"], ["\u057D", "\u054D"], ["\u057F", "\u054F"], ["\u0586", "\u0556"], ["\u056F", "\u053F"], ["\u0570", "\u0540"], ["\u0573", "\u0543"], ["\u0584", "\u0554"], ["\u056C", "\u053C"], ["\u0569", "\u0539"], ["\u0583", "\u0553"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u0566", "\u0536"], ["\u0581", "\u0551"], ["\u0563", "\u0533"], ["\u0582", "\u0552"], ["\u057A", "\u054A"], ["\u0576", "\u0546"], ["\u0574", "\u0544"], ["\u0577", "\u0547"], ["\u0572", "\u0542"], ["\u056E", "\u053E"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Belarusian = [ // Belarusian Standard Keyboard [["\u0451", "\u0401"], ["1", "!"], ["2", '"'], ["3", "\u2116"], ["4", ";"], ["5", "%"], ["6", ":"], ["7", "?"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0439", "\u0419"], ["\u0446", "\u0426"], ["\u0443", "\u0423"], ["\u043a", "\u041a"], ["\u0435", "\u0415"], ["\u043d", "\u041d"], ["\u0433", "\u0413"], ["\u0448", "\u0428"], ["\u045e", "\u040e"], ["\u0437", "\u0417"], ["\u0445", "\u0425"], ["'", "'"], ["\\", "/"]], [["Caps", "Caps"], ["\u0444", "\u0424"], ["\u044b", "\u042b"], ["\u0432", "\u0412"], ["\u0430", "\u0410"], ["\u043f", "\u041f"], ["\u0440", "\u0420"], ["\u043e", "\u041e"], ["\u043b", "\u041b"], ["\u0434", "\u0414"], ["\u0436", "\u0416"], ["\u044d", "\u042d"], ["Enter", "Enter"]], [["Shift", "Shift"], ["/", "|"], ["\u044f", "\u042f"], ["\u0447", "\u0427"], ["\u0441", "\u0421"], ["\u043c", "\u041c"], ["\u0456", "\u0406"], ["\u0442", "\u0422"], ["\u044c", "\u042c"], ["\u0431", "\u0411"], ["\u044e", "\u042e"], [".", ","], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Belgian = [ // Belgian Standard Keyboard [["\u00b2", "\u00b3"], ["&", "1", "|"], ["\u00e9", "2", "@"], ['"', "3", "#"], ["'", "4"], ["(", "5"], ["\u00a7", "6", "^"], ["\u00e8", "7"], ["!", "8"], ["\u00e7", "9", "{"], ["\u00e0", "0", "}"], [")", "\u00b0"], ["-", "_"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["a", "A"], ["z", "Z"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u005e", "\u00a8", "["], ["$", "*", "]"], ["Enter", "Enter"]], [["Caps", "Caps"], ["q", "Q"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["m", "M"], ["\u00f9", "%", "\u00b4"], ["\u03bc", "\u00a3", "`"]], [["Shift", "Shift"], ["<", ">", "\\"], ["w", "W"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], [",", "?"], [";", "."], [":", "/"], ["=", "+", "~"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Bengali = [ // Bengali Standard Keyboard [[""], ["1", "", "\u09E7"], ["2", "", "\u09E8"], ["3", "\u09CD\u09B0", "\u09E9"], ["4", "\u09B0\u09CD", "\u09EA"], ["5", "\u099C\u09CD\u09B0", "\u09EB"], ["6", "\u09A4\u09CD\u09B7", "\u09EC"], ["7", "\u0995\u09CD\u09B0", "\u09ED"], ["8", "\u09B6\u09CD\u09B0", "\u09EE"], ["9", "(", "\u09EF"], ["0", ")", "\u09E6"], ["-", "\u0983"], ["\u09C3", "\u098B", "\u09E2", "\u09E0"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u09CC", "\u0994", "\u09D7"], ["\u09C8", "\u0990"], ["\u09BE", "\u0986"], ["\u09C0", "\u0988", "\u09E3", "\u09E1"], ["\u09C2", "\u098A"], ["\u09AC", "\u09AD"], ["\u09B9", "\u0999"], ["\u0997", "\u0998"], ["\u09A6", "\u09A7"], ["\u099C", "\u099D"], ["\u09A1", "\u09A2", "\u09DC", "\u09DD"], ["\u09BC", "\u099E"]], [["Caps", "Caps"], ["\u09CB", "\u0993", "\u09F4", "\u09F5"], ["\u09C7", "\u098F", "\u09F6", "\u09F7"], ["\u09CD", "\u0985", "\u09F8", "\u09F9"], ["\u09BF", "\u0987", "\u09E2", "\u098C"], ["\u09C1", "\u0989"], ["\u09AA", "\u09AB"], ["\u09B0", "", "\u09F0", "\u09F1"], ["\u0995", "\u0996"], ["\u09A4", "\u09A5"], ["\u099A", "\u099B"], ["\u099F", "\u09A0"], ["Enter", "Enter"]], [["Shift", "Shift"], [""], ["\u0982", "\u0981", "\u09FA"], ["\u09AE", "\u09A3"], ["\u09A8"], ["\u09AC"], ["\u09B2"], ["\u09B8", "\u09B6"], [",", "\u09B7"], [".", "{"], ["\u09AF", "\u09DF"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout['Bulgarian Ph'] = [ // Bulgarian Phonetic Keyboard [["\u0447", "\u0427"], ["1", "!"], ["2", "@"], ["3", "#"], ["4", "$"], ["5", "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u044F", "\u042F"], ["\u0432", "\u0412"], ["\u0435", "\u0415"], ["\u0440", "\u0420"], ["\u0442", "\u0422"], ["\u044A", "\u042A"], ["\u0443", "\u0423"], ["\u0438", "\u0418"], ["\u043E", "\u041E"], ["\u043F", "\u041F"], ["\u0448", "\u0428"], ["\u0449", "\u0429"], ["\u044E", "\u042E"]], [["Caps", "Caps"], ["\u0430", "\u0410"], ["\u0441", "\u0421"], ["\u0434", "\u0414"], ["\u0444", "\u0424"], ["\u0433", "\u0413"], ["\u0445", "\u0425"], ["\u0439", "\u0419"], ["\u043A", "\u041A"], ["\u043B", "\u041B"], [";", ":"], ["'", '"'], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u0437", "\u0417"], ["\u044C", "\u042C"], ["\u0446", "\u0426"], ["\u0436", "\u0416"], ["\u0431", "\u0411"], ["\u043D", "\u041D"], ["\u043C", "\u041C"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Burmese = [ // Burmese Keyboard [["\u1039`", "~"], ["\u1041", "\u100D"], ["\u1042", "\u100E"], ["\u1043", "\u100B"], ["\u1044", "\u1000\u103B\u1015\u103A"], ["\u1045", "%"], ["\u1046", "\u002F"], ["\u1047", "\u101B"], ["\u1048", "\u1002"], ["\u1049", "("], ["\u1040", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u1006", "\u1029"], ["\u1010", "\u1040"], ["\u1014", "\u103F"], ["\u1019", "\u1023"], ["\u1021", "\u1024"], ["\u1015", "\u104C"], ["\u1000", "\u1009"], ["\u1004", "\u104D"], ["\u101E", "\u1025"], ["\u1005", "\u100F"], ["\u101F", "\u1027"], ["\u2018", "\u2019"], ["\u104F", "\u100B\u1039\u100C"]], [["Caps", "Caps"], ["\u200B\u1031", "\u1017"], ["\u200B\u103B", "\u200B\u103E"], ["\u200B\u102D", "\u200B\u102E"], ["\u200B\u103A","\u1004\u103A\u1039\u200B"], ["\u200B\u102B", "\u200B\u103D"], ["\u200B\u1037", "\u200B\u1036"], ["\u200B\u103C", "\u200B\u1032"], ["\u200B\u102F", "\u200B\u102F"], ["\u200B\u1030", "\u200B\u1030"], ["\u200B\u1038", "\u200B\u102B\u103A"], ["\u1012", "\u1013"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u1016", "\u1007"], ["\u1011", "\u100C"], ["\u1001", "\u1003"], ["\u101C", "\u1020"], ["\u1018", "\u1026"], ["\u100A", "\u1008"], ["\u200B\u102C", "\u102A"], ["\u101A", "\u101B"], ["\u002E", "\u101B"], ["\u104B", "\u104A"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Czech = [ // Czech Keyboard [[";", "\u00b0", "`", "~"], ["+", "1", "!"], ["\u011B", "2", "@"], ["\u0161", "3", "#"], ["\u010D", "4", "$"], ["\u0159", "5", "%"], ["\u017E", "6", "^"], ["\u00FD", "7", "&"], ["\u00E1", "8", "*"], ["\u00ED", "9", "("], ["\u00E9", "0", ")"], ["=", "%", "-", "_"], ["\u00B4", "\u02c7", "=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20AC"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00FA", "/", "[", "{"], [")", "(", "]", "}"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u016F", '"', ";", ":"], ["\u00A7", "!", "\u00a4", "^"], ["\u00A8", "'", "\\", "|"]], [["Shift", "Shift"], ["\\", "|", "", "\u02dd"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "?", "<", "\u00d7"], [".", ":", ">", "\u00f7"], ["-", "_", "/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout.Danish = [ // Danish Standard Keyboard [["\u00bd", "\u00a7"], ["1", "!"], ["2", '"', "@"], ["3", "#", "\u00a3"], ["4", "\u00a4", "$"], ["5", "%", "\u20ac"], ["6", "&"], ["7", "/", "{"], ["8", "(", "["], ["9", ")", "]"], ["0", "=", "}"], ["+", "?"], ["\u00b4", "`", "|"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00e5", "\u00c5"], ["\u00a8", "^", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00e6", "\u00c6"], ["\u00f8", "\u00d8"], ["'", "*"]], [["Shift", "Shift"], ["<", ">", "\\"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M", "\u03bc", "\u039c"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Dutch = [ // Dutch Standard Keyboard [["@", "\u00a7", "\u00ac"], ["1", "!", "\u00b9"], ["2", '"', "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00bc"], ["5", "%", "\u00bd"], ["6", "&", "\u00be"], ["7", "_", "\u00a3"], ["8", "(", "{"], ["9", ")", "}"], ["0", "'"], ["/", "?", "\\"], ["\u00b0", "~", "\u00b8"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R", "\u00b6"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00a8", "^"], ["*", "|"], ["<", ">"]], [["Caps", "Caps"], ["a", "A"], ["s", "S", "\u00df"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["+", "\u00b1"], ["\u00b4", "\u0060"], ["Enter", "Enter"]], [["Shift", "Shift"], ["]", "[", "\u00a6"], ["z", "Z", "\u00ab"], ["x", "X", "\u00bb"], ["c", "C", "\u00a2"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M", "\u00b5"], [",", ";"], [".", ":", "\u00b7"], ["-", "="], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Dvorak = [ // Dvorak Keyboard [["`", "~"], ["1", "!"], ["2", "@"], ["3", "#"], ["4", "$"], ["5", "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["[", "{"], ["]", "}"], ["Bksp", "Bksp"]], [["Tab", "Tab"],["'", '"'], [",", "<"], [".", ">"], ["p", "P"], ["y", "Y"], ["f", "F"], ["g", "G"], ["c", "C"], ["r", "R"], ["l", "L"], ["/", "?"], ["=", "+"], ["\\", "|"]], [["Caps", "Caps"], ["a", "A"], ["o", "O"], ["e", "E"], ["u", "U"], ["i", "I"], ["d", "D"], ["h", "H"], ["t", "T"], ["n", "N"], ["s", "S"], ["-", "_"], ["Enter", "Enter"]], [["Shift", "Shift"], [";", ":"], ["q", "Q"], ["j", "J"], ["k", "K"], ["x", "X"], ["b", "B"], ["m", "M"], ["w", "W"], ["v", "V"], ["z", "Z"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Farsi = [ // Farsi Keyboard [["\u067e", "\u0651 "], ["1", "!", "\u00a1", "\u00b9"], ["2", "@", "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00a4", "\u00a3"], ["5", "%", "\u20ac"], ["6", "^", "\u00bc"], ["7", "&", "\u00bd"], ["8", "*", "\u00be"], ["9", "(", "\u2018"], ["0", ")", "\u2019"], ["-", "_", "\u00a5"], ["=", "+", "\u00d7", "\u00f7"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0636", "\u064e"], ["\u0635", "\u064b"], ["\u062b", "\u064f"], ["\u0642", "\u064c"], ["\u0641", "\u0644"], ["\u063a", "\u0625"], ["\u0639", "\u2018"], ["\u0647", "\u00f7"], ["\u062e", "\u00d7"], ["\u062d", "\u061b"], ["\u062c", "\u003c"], ["\u0686", "\u003e"], ["\u0698", "\u007c"]], [["Caps", "Caps"], ["\u0634", "\u0650"], ["\u0633", "\u064d"], ["\u064a", "\u005d"], ["\u0628", "\u005b"], ["\u0644", "\u0644"], ["\u0627", "\u0623"], ["\u062a", "\u0640"], ["\u0646", "\u060c"], ["\u0645", "\u005c"], ["\u06af", "\u003a"], ["\u0643", "\u0022"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u0626", "\u007e"], ["\u0621", "\u0652"], ["\u0632", "\u007d"], ["\u0631", "\u007b"], ["\u0630", "\u0644"], ["\u062f", "\u0622"], ["\u0626", "\u0621"], ["\u0648", "\u002c"], [".", "\u002e"], ["/", "\u061f"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout.French = [ // French Standard Keyboard [["\u00b2", "\u00b3"], ["&", "1"], ["\u00e9", "2", "~"], ['"', "3", "#"], ["'", "4", "{"], ["(", "5", "["], ["-", "6", "|"], ["\u00e8", "7", "\u0060"], ["_", "8", "\\"], ["\u00e7", "9", "\u005e"], ["\u00e0", "0", "\u0040"], [")", "\u00b0", "]"], ["=", "+", "}"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["a", "A"], ["z", "Z"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["^", "\u00a8"], ["$", "\u00a3", "\u00a4"], ["Enter", "Enter"]], [["Caps", "Caps"], ["q", "Q"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["m", "M"], ["\u00f9", "%"], ["*", "\u03bc"]], [["Shift", "Shift"], ["<", ">"], ["w", "W"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], [",", "?"], [";", "."], [":", "/"], ["!", "\u00a7"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.German = [ // German Standard Keyboard [["\u005e", "\u00b0"], ["1", "!"], ["2", '"', "\u00b2"], ["3", "\u00a7", "\u00b3"], ["4", "$"], ["5", "%"], ["6", "&"], ["7", "/", "{"], ["8", "(", "["], ["9", ")", "]"], ["0", "=", "}"], ["\u00df", "?", "\\"], ["\u00b4", "\u0060"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\u0040"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["z", "Z"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00fc", "\u00dc"], ["+", "*", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00f6", "\u00d6"], ["\u00e4", "\u00c4"], ["#", "'"]], [["Shift", "Shift"], ["<", ">", "\u00a6"], ["y", "Y"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M", "\u00b5"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Greek = [ // Greek Standard Keyboard [["`", "~"], ["1", "!"], ["2", "@", "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00a3"], ["5", "%", "\u00a7"], ["6", "^", "\u00b6"], ["7", "&"], ["8", "*", "\u00a4"], ["9", "(", "\u00a6"], ["0", ")", "\u00ba"], ["-", "_", "\u00b1"], ["=", "+", "\u00bd"], ["Bksp", "Bksp"]], [["Tab", "Tab"], [";", ":"], ["\u03c2", "^"], ["\u03b5", "\u0395"], ["\u03c1", "\u03a1"], ["\u03c4", "\u03a4"], ["\u03c5", "\u03a5"], ["\u03b8", "\u0398"], ["\u03b9", "\u0399"], ["\u03bf", "\u039f"], ["\u03c0", "\u03a0"], ["[", "{", "\u201c"], ["]", "}", "\u201d"], ["Enter", "Enter"]], [["Caps", "Caps"], ["\u03b1", "\u0391"], ["\u03c3", "\u03a3"], ["\u03b4", "\u0394"], ["\u03c6", "\u03a6"], ["\u03b3", "\u0393"], ["\u03b7", "\u0397"], ["\u03be", "\u039e"], ["\u03ba", "\u039a"], ["\u03bb", "\u039b"], ["\u0384", "\u00a8", "\u0385"], ["'", '"'], ["\\", "|", "\u00ac"]], [["Shift", "Shift"], ["<", ">"], ["\u03b6", "\u0396"], ["\u03c7", "\u03a7"], ["\u03c8", "\u03a8"], ["\u03c9", "\u03a9"], ["\u03b2", "\u0392"], ["\u03bd", "\u039d"], ["\u03bc", "\u039c"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Hebrew = [ // Hebrew Standard Keyboard [["~", "`"], ["1", "!"], ["2", "@"], ["3", "#"], ["4" , "$", "\u20aa"], ["5" , "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", ")"], ["0", "("], ["-", "_"], ["=", "+"], ["\\", "|"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["/", "Q"], ["'", "W"], ["\u05e7", "E", "\u20ac"], ["\u05e8", "R"], ["\u05d0", "T"], ["\u05d8", "Y"], ["\u05d5", "U", "\u05f0"], ["\u05df", "I"], ["\u05dd", "O"], ["\u05e4", "P"], ["]", "}"], ["[", "{"]], [["Caps", "Caps"], ["\u05e9", "A"], ["\u05d3", "S"], ["\u05d2", "D"], ["\u05db", "F"], ["\u05e2", "G"], ["\u05d9", "H", "\u05f2"], ["\u05d7", "J", "\u05f1"], ["\u05dc", "K"], ["\u05da", "L"], ["\u05e3", ":"], ["," , '"'], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u05d6", "Z"], ["\u05e1", "X"], ["\u05d1", "C"], ["\u05d4", "V"], ["\u05e0", "B"], ["\u05de", "N"], ["\u05e6", "M"], ["\u05ea", ">"], ["\u05e5", "<"], [".", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Hindi = [ // Hindi Traditional Keyboard [["\u200d", "\u200c", "`", "~"], ["1", "\u090D", "\u0967", "!"], ["2", "\u0945", "\u0968", "@"], ["3", "\u094D\u0930", "\u0969", "#"], ["4", "\u0930\u094D", "\u096A", "$"], ["5", "\u091C\u094D\u091E", "\u096B", "%"], ["6", "\u0924\u094D\u0930", "\u096C", "^"], ["7", "\u0915\u094D\u0937", "\u096D", "&"], ["8", "\u0936\u094D\u0930", "\u096E", "*"], ["9", "(", "\u096F", "("], ["0", ")", "\u0966", ")"], ["-", "\u0903", "-", "_"], ["\u0943", "\u090B", "=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u094C", "\u0914"], ["\u0948", "\u0910"], ["\u093E", "\u0906"], ["\u0940", "\u0908"], ["\u0942", "\u090A"], ["\u092C", "\u092D"], ["\u0939", "\u0919"], ["\u0917", "\u0918"], ["\u0926", "\u0927"], ["\u091C", "\u091D"], ["\u0921", "\u0922", "[", "{"], ["\u093C", "\u091E", "]", "}"], ["Enter", "Enter"]], [["Caps", "Caps"], ["\u094B", "\u0913"], ["\u0947", "\u090F"], ["\u094D", "\u0905"], ["\u093F", "\u0907"], ["\u0941", "\u0909"], ["\u092A", "\u092B"], ["\u0930", "\u0931"], ["\u0915", "\u0916"], ["\u0924", "\u0925"], ["\u091A", "\u091B", ";", ":"], ["\u091F", "\u0920", "'", '"'], ["\u0949", "\u0911", "\\", "|"]], [["Shift", "Shift"], [""], ["\u0902", "\u0901", "", "\u0950"], ["\u092E", "\u0923"], ["\u0928"], ["\u0935"], ["\u0932", "\u0933"], ["\u0938", "\u0936"], [",", "\u0937", ",", "<"], [".", "\u0964", ".", ">"], ["\u092F", "\u095F", "/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Hungarian = [ // Hungarian Standard Keyboard [["0", "\u00a7"], ["1", "'", "\u007e"], ["2", '"', "\u02c7"], ["3", "+", "\u02c6"], ["4", "!", "\u02d8"], ["5", "%", "\u00b0"], ["6", "/", "\u02db"], ["7", "=", "\u0060"], ["8", "(", "\u02d9"], ["9", ")", "\u00b4"], ["\u00f6", "\u00d6", "\u02dd"], ["\u00fc", "\u00dc", "\u00a8"], ["\u00f3", "\u00d3", "\u00b8"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\u005c"], ["w", "W", "\u007c"], ["e", "E", "\u00c4"], ["r", "R"], ["t", "T"], ["z", "Z"], ["u", "U", "\u20ac"], ["i", "I", "\u00cd"], ["o", "O"], ["p", "P"], ["\u0151", "\u0150", "\u00f7"], ["\u00fa", "\u00da", "\u00d7"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A", "\u00e4"], ["s", "S","\u0111"], ["d", "D","\u0110"], ["f", "F","\u005b"], ["g", "G","\u005d"], ["h", "H"], ["j", "J","\u00ed"], ["k", "K","\u0141"], ["l", "L","\u0142"], ["\u00e9", "\u00c9","\u0024"], ["\u00e1", "\u00c1","\u00df"], ["\u0171", "\u0170","\u00a4"]], [["Shift", "Shift"], ["\u00ed", "\u00cd","\u003c"], ["y", "Y","\u003e"], ["x", "X","\u0023"], ["c", "C","\u0026"], ["v", "V","\u0040"], ["b", "B","\u007b"], ["n", "N","\u007d"], ["m", "M","\u003c"], [",", "?","\u003b"], [".", ":","\u003e"], ["-", "_","\u002a"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Italian = [ // Italian Standard Keyboard [["\u005c", "\u007c"], ["1", "!"], ["2", '"'], ["3", "\u00a3"], ["4", "$", "\u20ac"], ["5", "%"], ["6", "&"], ["7", "/"], ["8", "("], ["9", ")"], ["0", "="], ["'", "?"], ["\u00ec", "\u005e"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00e8", "\u00e9", "[", "{"], ["+", "*", "]", "}"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00f2", "\u00e7", "@"], ["\u00e0", "\u00b0", "#"], ["\u00f9", "\u00a7"]], [["Shift", "Shift"], ["<", ">"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Kazakh = [ // Kazakh Standard Keyboard [["(", ")"], ['"', "!"], ["\u04d9", "\u04d8"], ["\u0456", "\u0406"], ["\u04a3", "\u04a2"], ["\u0493", "\u0492"], [",", ";"], [".", ":"], ["\u04af", "\u04ae"], ["\u04b1", "\u04b0"], ["\u049b", "\u049a"], ["\u04e9", "\u04e8"], ["\u04bb", "\u04ba"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0439", "\u0419"], ["\u0446", "\u0426"], ["\u0443", "\u0423"], ["\u043A", "\u041A"], ["\u0435", "\u0415"], ["\u043D", "\u041D"], ["\u0433", "\u0413"], ["\u0448", "\u0428"], ["\u0449", "\u0429"], ["\u0437", "\u0417"], ["\u0445", "\u0425"], ["\u044A", "\u042A"], ["\\", "/"]], [["Caps", "Caps"], ["\u0444", "\u0424"], ["\u044B", "\u042B"], ["\u0432", "\u0412"], ["\u0430", "\u0410"], ["\u043F", "\u041F"], ["\u0440", "\u0420"], ["\u043E", "\u041E"], ["\u043B", "\u041B"], ["\u0434", "\u0414"], ["\u0436", "\u0416"], ["\u044D", "\u042D"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\\", "|"], ["\u044F", "\u042F"], ["\u0447", "\u0427"], ["\u0441", "\u0421"], ["\u043C", "\u041C"], ["\u0438", "\u0418"], ["\u0442", "\u0422"], ["\u044C", "\u042C"], ["\u0431", "\u0411"], ["\u044E", "\u042E"], ["\u2116", "?"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Lithuanian = [ // Lithuanian Standard Keyboard [["`", "~"], ["\u0105", "\u0104"], ["\u010D", "\u010C"], ["\u0119", "\u0118"], ["\u0117", "\u0116"], ["\u012F", "\u012E"], ["\u0161", "\u0160"], ["\u0173", "\u0172"], ["\u016B", "\u016A"], ["\u201E", "("], ["\u201C", ")"], ["-", "_"], ["\u017E", "\u017D"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["[", "{"], ["]", "}"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], [";", ":"], ["'", '"'], ["\\", "|"]], [["Shift", "Shift"], ["\u2013", "\u20AC"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.Macedonian = [ // Macedonian Cyrillic Standard Keyboard [["`", "~"], ["1", "!"], ["2", "\u201E"], ["3", "\u201C"], ["4", "\u2019"], ["5", "%"], ["6", "\u2018"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0459", "\u0409"], ["\u045A", "\u040A"], ["\u0435", "\u0415", "\u20AC"], ["\u0440", "\u0420"], ["\u0442", "\u0422"], ["\u0455", "\u0405"], ["\u0443", "\u0423"], ["\u0438", "\u0418"], ["\u043E", "\u041E"], ["\u043F", "\u041F"], ["\u0448", "\u0428", "\u0402"], ["\u0453", "\u0403", "\u0452"], ["Enter", "Enter"]], [["Caps", "Caps"], ["\u0430", "\u0410"], ["\u0441", "\u0421"], ["\u0434", "\u0414"], ["\u0444", "\u0424", "["], ["\u0433", "\u0413", "]"], ["\u0445", "\u0425"], ["\u0458", "\u0408"], ["\u043A", "\u041A"], ["\u043B", "\u041B"], ["\u0447", "\u0427", "\u040B"], ["\u045C", "\u040C", "\u045B"], ["\u0436", "\u0416"]], [["Shift", "Shift"], ["\u0451", "\u0401"], ["\u0437", "\u0417"], ["\u045F", "\u040F"], ["\u0446", "\u0426"], ["\u0432", "\u0412", "@"], ["\u0431", "\u0411", "{"], ["\u043D", "\u041D", "}"], ["\u043C", "\u041C", "\u00A7"], [",", ";"], [".", ":"], ["/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Norwegian = [ // Norwegian Standard Keyboard [["|", "\u00a7"], ["1", "!"], ["2", '"', "@"], ["3", "#", "\u00a3"], ["4", "\u00a4", "$"], ["5", "%"], ["6", "&"], ["7", "/", "{"], ["8", "(", "["], ["9", ")", "]"], ["0", "=", "}"], ["+", "?"], ["\\", "`", "\u00b4"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00e5", "\u00c5"], ["\u00a8", "^", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00f8", "\u00d8"], ["\u00e6", "\u00c6"], ["'", "*"]], [["Shift", "Shift"], ["<", ">"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M", "\u03bc", "\u039c"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Numpad = [ // Number pad [["$"], ["\u00a3"], ["\u20ac"], ["\u00a5"], ["/"], ["^"], ["Bksp", "Bksp"]], [["."], ["7"], ["8"], ["9"], ["*"], ["<"], ["("], ["["]], [["="], ["4"], ["5"], ["6"], ["-"], [">"], [")"], ["]"]], [["0"], ["1"], ["2"], ["3"], ["+"], ["Enter", "Enter"]], [[" "]] ]; this.VKI_layout.Numpad.DDK = true; this.VKI_layout.Pashto = [ // Pashto Keyboard [["\u200d", "\u00f7"], ["\u06f1", "\u0021", "\u0060"], ["\u06f2", "\u066c", "\u0040"], ["\u06f3", "\u066b", "\u066b"], ["\u06f4", "\u00a4", "\u00a3"], ["\u06f5", "\u066a", "\u0025"], ["\u06f6", "\u00d7", "\u005e"], ["\u06f7", "\u00ab", "\u0026"], ["\u06f8", "\u00bb", "\u002a"], ["\u06f9", "(", "\ufdf2"], ["\u06f0", ")", "\ufefb"], ["\u002d", "\u0640", "\u005f"], ["\u003d", "\u002b", "\ufe87", "\u00f7"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0636", "\u0652", "\u06d5"], ["\u0635", "\u064c", "\u0653"], ["\u062b", "\u064d", "\u20ac"], ["\u0642", "\u064b", "\ufef7"], ["\u0641", "\u064f", "\ufef5"], ["\u063a", "\u0650", "\u0027"], ["\u0639", "\u064e", "\ufe84"], ["\u0647", "\u0651", "\u0670"], ["\u062e", "\u0685", "\u0027"], ["\u062d", "\u0681", "\u0022"], ["\u062c", "\u005b", "\u007b"], ["\u0686", "\u005d", "\u007d"], ["\u005c", "\u066d", "\u007c"]], [["Caps", "Caps"], ["\u0634", "\u069a", "\ufbb0"], ["\u0633", "\u0626", "\ufe87"], ["\u06cc", "\u064a", "\u06d2"], ["\u0628", "\u067e", "\u06ba"], ["\u0644", "\u0623", "\u06b7"], ["\u0627", "\u0622", "\u0671"], ["\u062a", "\u067c", "\u0679"], ["\u0646", "\u06bc", "\u003c"], ["\u0645", "\u0629", "\u003e"], ["\u06a9", "\u003a", "\u0643"], ["\u06af", "\u061b", "\u06ab"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u06cd", "\u0638", "\u003b"], ["\u06d0", "\u0637", "\ufbb0"], ["\u0632", "\u0698", "\u0655"], ["\u0631", "\u0621", "\u0654"], ["\u0630", "\u200c", "\u0625"], ["\u062f", "\u0689", "\u0688"], ["\u0693", "\u0624", "\u0691"], ["\u0648", "\u060c", "\u002c"], ["\u0696", "\u002e", "\u06c7"], ["\u002f", "\u061f", "\u06c9"], ["Shift", "Shift", "\u064d"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout.Pinyin = [ // Pinyin Keyboard [["`", "~", "\u4e93", "\u301C"], ["1", "!", "\uFF62"], ["2", "@", "\uFF63"], ["3", "#", "\u301D"], ["4", "$", "\u301E"], ["5", "%", "\u301F"], ["6", "^", "\u3008"], ["7", "&", "\u3009"], ["8", "*", "\u302F"], ["9", "(", "\u300A"], ["0", ")", "\u300B"], ["-", "_", "\u300E"], ["=", "+", "\u300F"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\u0101", "\u0100"], ["w", "W", "\u00E1", "\u00C1"], ["e", "E", "\u01CE", "\u01CD"], ["r", "R", "\u00E0", "\u00C0"], ["t", "T", "\u0113", "\u0112"], ["y", "Y", "\u00E9", "\u00C9"], ["u", "U", "\u011B", "\u011A"], ["i", "I", "\u00E8", "\u00C8"], ["o", "O", "\u012B", "\u012A"], ["p", "P", "\u00ED", "\u00CD"], ["[", "{", "\u01D0", "\u01CF"], ["]", "}", "\u00EC", "\u00CC"], ["\\", "|", "\u3020"]], [["Caps", "Caps"], ["a", "A", "\u014D", "\u014C"], ["s", "S", "\u00F3", "\u00D3"], ["d", "D", "\u01D2", "\u01D1"], ["f", "F", "\u00F2", "\u00D2"], ["g", "G", "\u00fc", "\u00dc"], ["h", "H", "\u016B", "\u016A"], ["j", "J", "\u00FA", "\u00DA"], ["k", "K", "\u01D4", "\u01D3"], ["l", "L", "\u00F9", "\u00D9"], [";", ":"], ["'", '"'], ["Enter", "Enter"]], [["Shift", "Shift"], ["z", "Z", "\u01D6", "\u01D5"], ["x", "X", "\u01D8", "\u01D7"], ["c", "C", "\u01DA", "\u01D9"], ["v", "V", "\u01DC", "\u01DB"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "<", "\u3001"], [".", ">", "\u3002"], ["/", "?"], ["Shift", "Shift"]], [["AltLk", "AltLk"], [" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout["Polish Prog"] = [ // Polish Programmers Keyboard [["`", "~"], ["1", "!"], ["2", "@"], ["3", "#"], ["4", "$"], ["5", "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u0119", "\u0118"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O", "\u00f3", "\u00d3"], ["p", "P"], ["[", "{"], ["]", "}"], ["\\", "|"]], [["Caps", "Caps"], ["a", "A", "\u0105", "\u0104"], ["s", "S", "\u015b", "\u015a"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L", "\u0142", "\u0141"], [";", ":"], ["'", '"'], ["Enter", "Enter"]], [["Shift", "Shift"], ["z", "Z", "\u017c", "\u017b"], ["x", "X", "\u017a", "\u0179"], ["c", "C", "\u0107", "\u0106"], ["v", "V"], ["b", "B"], ["n", "N", "\u0144", "\u0143"], ["m", "M"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; this.VKI_layout["Portuguese Br"] = [ // Portuguese (Brazil) Standard Keyboard [["'", '"'], ["1", "!", "\u00b9"], ["2", "@", "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00a3"], ["5", "%", "\u00a2"], ["6", "\u00a8", "\u00ac"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+", "\u00a7"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "/"], ["w", "W", "?"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00b4", "`"], ["[", "{", "\u00aa"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00e7", "\u00c7"], ["~", "^"], ["]", "}", "\u00ba"], ["/", "?"]], [["Shift", "Shift"], ["\\", "|"], ["z", "Z"], ["x", "X"], ["c", "C", "\u20a2"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "<"], [".", ">"], [":", ":"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout["Portuguese Pt"] = [ // Portuguese (Portugal) Standard Keyboard [["\\", "|"], ["1", "!"], ["2", '"', "@"], ["3", "#", "\u00a3"], ["4", "$", "\u00a7"], ["5", "%"], ["6", "&"], ["7", "/", "{"], ["8", "(", "["], ["9", ")", "]"], ["0", "=", "}"], ["'", "?"], ["\u00ab", "\u00bb"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["+", "*", "\u00a8"], ["\u00b4", "`"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00e7", "\u00c7"], ["\u00ba", "\u00aa"], ["~", "^"]], [["Shift", "Shift"], ["<", ">", "\\"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Romanian = [ // Romanian Standard Keyboard [["\u201E", "\u201D", "\u0060", "~"], ["1", "!","~"], ["2", "\u0040", "\u02C7"], ["3", "#","\u005E"], ["4", "$", "\u02D8"], ["5", "%", "\u00B0"], ["6", "\u005E", "\u02DB"], ["7", "&", "\u0060"], ["8", "*", "\u02D9"], ["9", "(", "\u00B4"], ["0", ")", "\u02DD"], ["-", "_", "\u00A8"], ["=", "+", "\u00B8", "\u00B1"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20AC"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P", "\u00A7"], ["\u0103", "\u0102", "[", "{"], ["\u00EE", "\u00CE", "]","}"], ["\u00E2", "\u00C2", "\\", "|"]], [["Caps", "Caps"], ["a", "A"], ["s", "S", "\u00df"], ["d", "D", "\u00f0", "\u00D0"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L", "\u0142", "\u0141"], [(this.VKI_isIElt8) ? "\u015F" : "\u0219", (this.VKI_isIElt8) ? "\u015E" : "\u0218", ";", ":"], [(this.VKI_isIElt8) ? "\u0163" : "\u021B", (this.VKI_isIElt8) ? "\u0162" : "\u021A", "\'", "\""], ["Enter", "Enter"]], [["Shift", "Shift"], ["\\", "|"], ["z", "Z"], ["x", "X"], ["c", "C", "\u00A9"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", ";", "<", "\u00AB"], [".", ":", ">", "\u00BB"], ["/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Russian = [ // Russian Standard Keyboard [["\u0451", "\u0401"], ["1", "!"], ["2", '"'], ["3", "\u2116"], ["4", ";"], ["5", "%"], ["6", ":"], ["7", "?"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0439", "\u0419"], ["\u0446", "\u0426"], ["\u0443", "\u0423"], ["\u043A", "\u041A"], ["\u0435", "\u0415"], ["\u043D", "\u041D"], ["\u0433", "\u0413"], ["\u0448", "\u0428"], ["\u0449", "\u0429"], ["\u0437", "\u0417"], ["\u0445", "\u0425"], ["\u044A", "\u042A"], ["Enter", "Enter"]], [["Caps", "Caps"], ["\u0444", "\u0424"], ["\u044B", "\u042B"], ["\u0432", "\u0412"], ["\u0430", "\u0410"], ["\u043F", "\u041F"], ["\u0440", "\u0420"], ["\u043E", "\u041E"], ["\u043B", "\u041B"], ["\u0434", "\u0414"], ["\u0436", "\u0416"], ["\u044D", "\u042D"], ["\\", "/"]], [["Shift", "Shift"], ["/", "|"], ["\u044F", "\u042F"], ["\u0447", "\u0427"], ["\u0441", "\u0421"], ["\u043C", "\u041C"], ["\u0438", "\u0418"], ["\u0442", "\u0422"], ["\u044C", "\u042C"], ["\u0431", "\u0411"], ["\u044E", "\u042E"], [".", ","], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.SerbianCyr = [ // Serbian Cyrillic Standard Keyboard [["`", "~"], ["1", "!"], ["2", '"'], ["3", "#"], ["4", "$"], ["5", "%"], ["6", "&"], ["7", "/"], ["8", "("], ["9", ")"], ["0", "="], ["'", "?"], ["+", "*"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0459", "\u0409"], ["\u045a", "\u040a"], ["\u0435", "\u0415", "\u20ac"], ["\u0440", "\u0420"], ["\u0442", "\u0422"], ["\u0437", "\u0417"], ["\u0443", "\u0423"], ["\u0438", "\u0418"], ["\u043e", "\u041e"], ["\u043f", "\u041f"], ["\u0448", "\u0428"], ["\u0452", "\u0402"], ["Enter", "Enter"]], [["Caps", "Caps"], ["\u0430", "\u0410"], ["\u0441", "\u0421"], ["\u0434", "\u0414"], ["\u0444", "\u0424"], ["\u0433", "\u0413"], ["\u0445", "\u0425"], ["\u0458", "\u0408"], ["\u043a", "\u041a"], ["\u043b", "\u041b"], ["\u0447", "\u0427"], ["\u045b", "\u040b"], ["\u0436", "\u0416"]], [["Shift", "Shift"], ["<", ">"], ["\u0455", "\u0405"], ["\u045f", "\u040f"], ["\u0446", "\u0426"], ["\u0432", "\u0412"], ["\u0431", "\u0411"], ["\u043d", "\u041d"], ["\u043c", "\u041c"], [",", ";", "<"], [".", ":", ">"], ["-", "_", "\u00a9"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.SerbianLat = [ // Serbian Latin Standard Keyboard [["\u201a", "~"], ["1", "!", "~"], ["2", '"', "\u02c7"], ["3", "#", "^"], ["4", "$", "\u02d8"], ["5", "%", "\u00b0"], ["6", "&", "\u02db"], ["7", "/", "`"], ["8", "(", "\u02d9"], ["9", ")", "\u00b4"], ["0", "=", "\u02dd"], ["'", "?", "\u00a8"], ["+", "*", "\u00b8"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\\"], ["w", "W","|"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["z", "Z"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u0161", "\u0160", "\u00f7"], ["\u0111", "\u0110", "\u00d7"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F", "["], ["g", "G", "]"], ["h", "H"], ["j", "J"], ["k", "K", "\u0142"], ["l", "L", "\u0141"], ["\u010d", "\u010c"], ["\u0107", "\u0106", "\u00df"], ["\u017e", "\u017d", "\u00a4"]], [["Shift", "Shift"], ["<", ">"], ["y", "Y"], ["x", "X"], ["c", "C"], ["v", "V", "@"], ["b", "B", "{",], ["n", "N", "}"], ["m", "M", "\u00a7"], [",", ";", "<"], [".", ":", ">"], ["-", "_", "\u00a9"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Slovak = [ // Slovak Keyboard [[";", "\u00b0"], ["+", "1", "~"], ["\u013E", "2", "\u02C7"], ["\u0161", "3", "\u005E"], ["\u010D", "4", "\u02D8"], ["\u0165", "5", "\u00B0"], ["\u017E", "6", "\u02DB"], ["\u00FD", "7", "\u0060"], ["\u00E1", "8", "\u02D9"], ["\u00ED", "9", "\u00B4"], ["\u00E9", "0", "\u02DD"], ["=", "%", "\u00A8"], ["\u00B4", "\u02c7", "\u00B8"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q","\u005C"], ["w", "W","\u007C"], ["e", "E", "\u20AC"], ["r", "R"], ["t", "T"], ["z", "Z"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P","\u0027"], ["\u00FA", "/", "\u00F7"], ["\u00E4", "(", "\u00D7"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S","\u0111"], ["d", "D","\u0110"], ["f", "F","\u005B"], ["g", "G","\u005D"], ["h", "H"], ["j", "J"], ["k", "K","\u0142"], ["l", "L","\u0141"], ["\u00F4", '"', "\u0024"], ["\u00A7", "!", "\u00DF",], ["\u0148", ")","\u00A4"]], [["Shift", "Shift"], ["&", "*", "\u003C"], ["y", "Y","\u003E"], ["x", "X","\u0023"], ["c", "C","\u0026"], ["v", "V","\u0040"], ["b", "B","\u007B"], ["n", "N","\u007D"], ["m", "M"], [",", "?", "<"], [".", ":", ">"], ["-", "_", "\u002A", ], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Slovenian = [ // Slovenian Standard Keyboard [["\u00a8", "\u00a8", "\u00b8"], ["1", "!", "~"], ["2", '"', "\u02c7"], ["3", "#", "^"], ["4", "$", "\u02d8"], ["5", "%", "\u00b0"], ["6", "&", "\u02db"], ["7", "/", "\u0060"], ["8", "(", "\u00B7"], ["9", ")", "\u00b4"], ["0", "=", "\u2033"], ["'", "?", "\u00a8"], ["+", "*", "\u00b8"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\\"], ["w", "W","|"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["z", "Z"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u0161", "\u0160", "\u00f7"], ["\u0111", "\u0110", "\u00d7"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F", "["], ["g", "G", "]"], ["h", "H"], ["j", "J"], ["k", "K", "\u0142"], ["l", "L", "\u0141"], ["\u010D", "\u010C"], ["\u0107", "\u0106", "\u00df"], ["\u017E", "\u017D", "\u00a4"]], [["Shift", "Shift"], ["<", ">"], ["y", "Y"], ["x", "X"], ["c", "C"], ["v", "V", "@"], ["b", "B", "{",], ["n", "N", "}"], ["m", "M", "\u00a7"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout["Spanish Es"] = [ // Spanish (Spain) Standard Keyboard [["\u00ba", "\u00aa", "\\"], ["1", "!", "|"], ["2", '"', "@"], ["3", "'", "#"], ["4", "$", "~"], ["5", "%", "\u20ac"], ["6", "&","\u00ac"], ["7", "/"], ["8", "("], ["9", ")"], ["0", "="], ["'", "?"], ["\u00a1", "\u00bf"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u0060", "^", "["], ["\u002b", "\u002a", "]"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00f1", "\u00d1"], ["\u00b4", "\u00a8", "{"], ["\u00e7", "\u00c7", "}"]], [["Shift", "Shift"], ["<", ">"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Swedish = [ // Swedish Standard Keyboard [["\u00a7", "\u00bd"], ["1", "!"], ["2", '"', "@"], ["3", "#", "\u00a3"], ["4", "\u00a4", "$"], ["5", "%", "\u20ac"], ["6", "&"], ["7", "/", "{"], ["8", "(", "["], ["9", ")", "]"], ["0", "=", "}"], ["+", "?", "\\"], ["\u00b4", "`"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["\u00e5", "\u00c5"], ["\u00a8", "^", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u00f6", "\u00d6"], ["\u00e4", "\u00c4"], ["'", "*"]], [["Shift", "Shift"], ["<", ">", "|"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M", "\u03bc", "\u039c"], [",", ";"], [".", ":"], ["-", "_"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout["Turkish-F"] = [ // Turkish F Keyboard Layout [['+', "*", "\u00ac"], ["1", "!", "\u00b9", "\u00a1"], ["2", '"', "\u00b2"], ["3", "^", "#", "\u00b3"], ["4", "$", "\u00bc", "\u00a4"], ["5", "%", "\u00bd"], ["6", "&", "\u00be"], ["7", "'", "{"], ["8", "(", '['], ["9", ")", ']'], ["0", "=", "}"], ["/", "?", "\\", "\u00bf"], ["-", "_", "|"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["f", "F", "@"], ["g", "G"], ["\u011f", "\u011e"], ["\u0131", "\u0049", "\u00b6", "\u00ae"], ["o", "O"], ["d", "D", "\u00a5"], ["r", "R"], ["n", "N"], ["h", "H", "\u00f8", "\u00d8"], ["p", "P", "\u00a3"], ["q", "Q", "\u00a8"], ["w", "W", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["u", "U", "\u00e6", "\u00c6"], ["i", "\u0130", "\u00df", "\u00a7"], ["e", "E", "\u20ac"], ["a", "A", " ", "\u00aa"], ["\u00fc", "\u00dc"], ["t", "T"], ["k", "K"], ["m", "M"], ["l", "L"], ["y", "Y", "\u00b4"], ["\u015f", "\u015e"], ["x", "X", "`"]], [["Shift", "Shift"], ["<", ">", "|", "\u00a6"], ["j", "J", "\u00ab", "<"], ["\u00f6", "\u00d6", "\u00bb", ">"], ["v", "V", "\u00a2", "\u00a9"], ["c", "C"], ["\u00e7", "\u00c7"], ["z", "Z"], ["s", "S", "\u00b5", "\u00ba"], ["b", "B", "\u00d7"], [".", ":", "\u00f7"], [",", ";", "-"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout["Turkish-Q"] = [ // Turkish Q Keyboard Layout [['"', "\u00e9", "<"], ["1", "!", ">"], ["2", "'", "\u00a3"], ["3", "^", "#"], ["4", "+", "$"], ["5", "%", "\u00bd"], ["6", "&"], ["7", "/", "{"], ["8", "(", '['], ["9", ")", ']'], ["0", "=", "}"], ["*", "?", "\\"], ["-", "_", "|"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "@"], ["w", "W"], ["e", "E", "\u20ac"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["\u0131", "\u0049", "\u0069", "\u0130"], ["o", "O"], ["p", "P"], ["\u011f", "\u011e", "\u00a8"], ["\u00fc", "\u00dc", "~"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A", "\u00e6", "\u00c6"], ["s", "S", "\u00df"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], ["\u015f", "\u015e", "\u00b4"], ["\u0069", "\u0130"], [",", ";", "`"]], [["Shift", "Shift"], ["<", ">", "|"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], ["\u00f6", "\u00d6"], ["\u00e7", "\u00c7"], [".", ":"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.UK = [ // UK Standard Keyboard [["`", "\u00ac", "\u00a6"], ["1", "!"], ["2", '"'], ["3", "\u00a3"], ["4", "$", "\u20ac"], ["5", "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E", "\u00e9", "\u00c9"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U", "\u00fa", "\u00da"], ["i", "I", "\u00ed", "\u00cd"], ["o", "O", "\u00f3", "\u00d3"], ["p", "P"], ["[", "{"], ["]", "}"], ["Enter", "Enter"]], [["Caps", "Caps"], ["a", "A", "\u00e1", "\u00c1"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], [";", ":"], ["'", "@"], ["#", "~"]], [["Shift", "Shift"], ["\\", "|"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["AltGr", "AltGr"]] ]; this.VKI_layout.Ukrainian = [ // Ukrainian Standard Keyboard [["\u00b4", "~"], ["1", "!"], ["2", '"'], ["3", "\u2116"], ["4", ";"], ["5", "%"], ["6", ":"], ["7", "?"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["\u0439", "\u0419"], ["\u0446", "\u0426"], ["\u0443", "\u0423"], ["\u043A", "\u041A"], ["\u0435", "\u0415"], ["\u043D", "\u041D"], ["\u0433", "\u0413"], ["\u0448", "\u0428"], ["\u0449", "\u0429"], ["\u0437", "\u0417"], ["\u0445", "\u0425"], ["\u0457", "\u0407"], ["\u0491", "\u0490"]], [["Caps", "Caps"], ["\u0444", "\u0424"], ["\u0456", "\u0406"], ["\u0432", "\u0412"], ["\u0430", "\u0410"], ["\u043F", "\u041F"], ["\u0440", "\u0420"], ["\u043E", "\u041E"], ["\u043B", "\u041B"], ["\u0434", "\u0414"], ["\u0436", "\u0416"], ["\u0454", "\u0404"], ["Enter", "Enter"]], [["Shift", "Shift"], ["\u044F", "\u042F"], ["\u0447", "\u0427"], ["\u0441", "\u0421"], ["\u043C", "\u041C"], ["\u0438", "\u0418"], ["\u0442", "\u0422"], ["\u044C", "\u042C"], ["\u0431", "\u0411"], ["\u044E", "\u042E"], [".", ","], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout.US = [ // US Standard Keyboard [["`", "~"], ["1", "!"], ["2", "@"], ["3", "#"], ["4", "$"], ["5", "%"], ["6", "^"], ["7", "&"], ["8", "*"], ["9", "("], ["0", ")"], ["-", "_"], ["=", "+"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q"], ["w", "W"], ["e", "E"], ["r", "R"], ["t", "T"], ["y", "Y"], ["u", "U"], ["i", "I"], ["o", "O"], ["p", "P"], ["[", "{"], ["]", "}"], ["\\", "|"]], [["Caps", "Caps"], ["a", "A"], ["s", "S"], ["d", "D"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L"], [";", ":"], ["'", '"'], ["Enter", "Enter"]], [["Shift", "Shift"], ["z", "Z"], ["x", "X"], ["c", "C"], ["v", "V"], ["b", "B"], ["n", "N"], ["m", "M"], [",", "<"], [".", ">"], ["/", "?"], ["Shift", "Shift"]], [[" ", " "]] ]; this.VKI_layout["US Int'l"] = [ // US International Keyboard [["`", "~"], ["1", "!", "\u00a1", "\u00b9"], ["2", "@", "\u00b2"], ["3", "#", "\u00b3"], ["4", "$", "\u00a4", "\u00a3"], ["5", "%", "\u20ac"], ["6", "^", "\u00bc"], ["7", "&", "\u00bd"], ["8", "*", "\u00be"], ["9", "(", "\u2018"], ["0", ")", "\u2019"], ["-", "_", "\u00a5"], ["=", "+", "\u00d7", "\u00f7"], ["Bksp", "Bksp"]], [["Tab", "Tab"], ["q", "Q", "\u00e4", "\u00c4"], ["w", "W", "\u00e5", "\u00c5"], ["e", "E", "\u00e9", "\u00c9"], ["r", "R", "\u00ae"], ["t", "T", "\u00fe", "\u00de"], ["y", "Y", "\u00fc", "\u00dc"], ["u", "U", "\u00fa", "\u00da"], ["i", "I", "\u00ed", "\u00cd"], ["o", "O", "\u00f3", "\u00d3"], ["p", "P", "\u00f6", "\u00d6"], ["[", "{", "\u00ab"], ["]", "}", "\u00bb"], ["\\", "|", "\u00ac", "\u00a6"]], [["Caps", "Caps"], ["a", "A", "\u00e1", "\u00c1"], ["s", "S", "\u00df", "\u00a7"], ["d", "D", "\u00f0", "\u00d0"], ["f", "F"], ["g", "G"], ["h", "H"], ["j", "J"], ["k", "K"], ["l", "L", "\u00f8", "\u00d8"], [";", ":", "\u00b6", "\u00b0"], ["'", '"', "\u00b4", "\u00a8"], ["Enter", "Enter"]], [["Shift", "Shift"], ["z", "Z", "\u00e6", "\u00c6"], ["x", "X"], ["c", "C", "\u00a9", "\u00a2"], ["v", "V"], ["b", "B"], ["n", "N", "\u00f1", "\u00d1"], ["m", "M", "\u00b5"], [",", "<", "\u00e7", "\u00c7"], [".", ">"], ["/", "?", "\u00bf"], ["Shift", "Shift"]], [[" ", " ", " ", " "], ["Alt", "Alt"]] ]; /* ***** Define Dead Keys ************************************** */ this.VKI_deadkey = {}; // - Lay out each dead key set in one row of sub-arrays. The rows // below are wrapped so uppercase letters are below their // lowercase equivalents. // // - The first letter in each sub-array is the letter pressed after // the diacritic. The second letter is the letter this key-combo // will generate. // // - Note that if you have created a new keyboard layout and want // it included in the distributed script, PLEASE TELL ME if you // have added additional dead keys to the ones below. this.VKI_deadkey['"'] = this.VKI_deadkey['\u00a8'] = [ // Umlaut / Diaeresis / Greek Dialytika ["a", "\u00e4"], ["e", "\u00eb"], ["i", "\u00ef"], ["o", "\u00f6"], ["u", "\u00fc"], ["y", "\u00ff"], ["\u03b9", "\u03ca"], ["\u03c5", "\u03cb"], ["\u016B", "\u01D6"], ["\u00FA", "\u01D8"], ["\u01D4", "\u01DA"], ["\u00F9", "\u01DC"], ["A", "\u00c4"], ["E", "\u00cb"], ["I", "\u00cf"], ["O", "\u00d6"], ["U", "\u00dc"], ["Y", "\u0178"], ["\u0399", "\u03aa"], ["\u03a5", "\u03ab"], ["\u016A", "\u01D5"], ["\u00DA", "\u01D7"], ["\u01D3", "\u01D9"], ["\u00D9", "\u01DB"] ]; this.VKI_deadkey['~'] = [ // Tilde / Stroke ["a", "\u00e3"], ["l", "\u0142"], ["n", "\u00f1"], ["o", "\u00f5"], ["A", "\u00c3"], ["L", "\u0141"], ["N", "\u00d1"], ["O", "\u00d5"] ]; this.VKI_deadkey['^'] = [ // Circumflex ["a", "\u00e2"], ["e", "\u00ea"], ["i", "\u00ee"], ["o", "\u00f4"], ["u", "\u00fb"], ["w", "\u0175"], ["y", "\u0177"], ["A", "\u00c2"], ["E", "\u00ca"], ["I", "\u00ce"], ["O", "\u00d4"], ["U", "\u00db"], ["W", "\u0174"], ["Y", "\u0176"] ]; this.VKI_deadkey['\u02c7'] = [ // Baltic caron ["c", "\u010D"], ["d", "\u010f"], ["e", "\u011b"], ["s", "\u0161"], ["l", "\u013e"], ["n", "\u0148"], ["r", "\u0159"], ["t", "\u0165"], ["u", "\u01d4"], ["z", "\u017E"], ["\u00fc", "\u01da"], ["C", "\u010C"], ["D", "\u010e"], ["E", "\u011a"], ["S", "\u0160"], ["L", "\u013d"], ["N", "\u0147"], ["R", "\u0158"], ["T", "\u0164"], ["U", "\u01d3"], ["Z", "\u017D"], ["\u00dc", "\u01d9"] ]; this.VKI_deadkey['\u02d8'] = [ // Romanian and Turkish breve ["a", "\u0103"], ["g", "\u011f"], ["A", "\u0102"], ["G", "\u011e"] ]; this.VKI_deadkey['-'] = this.VKI_deadkey['\u00af'] = [ // Macron ["a", "\u0101"], ["e", "\u0113"], ["i", "\u012b"], ["o", "\u014d"], ["u", "\u016B"], ["y", "\u0233"], ["\u00fc", "\u01d6"], ["A", "\u0100"], ["E", "\u0112"], ["I", "\u012a"], ["O", "\u014c"], ["U", "\u016A"], ["Y", "\u0232"], ["\u00dc", "\u01d5"] ]; this.VKI_deadkey['`'] = [ // Grave ["a", "\u00e0"], ["e", "\u00e8"], ["i", "\u00ec"], ["o", "\u00f2"], ["u", "\u00f9"], ["\u00fc", "\u01dc"], ["A", "\u00c0"], ["E", "\u00c8"], ["I", "\u00cc"], ["O", "\u00d2"], ["U", "\u00d9"], ["\u00dc", "\u01db"] ]; this.VKI_deadkey["'"] = this.VKI_deadkey['\u00b4'] = this.VKI_deadkey['\u0384'] = [ // Acute / Greek Tonos ["a", "\u00e1"], ["e", "\u00e9"], ["i", "\u00ed"], ["o", "\u00f3"], ["u", "\u00fa"], ["y", "\u00fd"], ["\u03b1", "\u03ac"], ["\u03b5", "\u03ad"], ["\u03b7", "\u03ae"], ["\u03b9", "\u03af"], ["\u03bf", "\u03cc"], ["\u03c5", "\u03cd"], ["\u03c9", "\u03ce"], ["\u00fc", "\u01d8"], ["A", "\u00c1"], ["E", "\u00c9"], ["I", "\u00cd"], ["O", "\u00d3"], ["U", "\u00da"], ["Y", "\u00dd"], ["\u0391", "\u0386"], ["\u0395", "\u0388"], ["\u0397", "\u0389"], ["\u0399", "\u038a"], ["\u039f", "\u038c"], ["\u03a5", "\u038e"], ["\u03a9", "\u038f"], ["\u00dc", "\u01d7"] ]; this.VKI_deadkey['\u02dd'] = [ // Hungarian Double Acute Accent ["o", "\u0151"], ["u", "\u0171"], ["O", "\u0150"], ["U", "\u0170"] ]; this.VKI_deadkey['\u0385'] = [ // Greek Dialytika + Tonos ["\u03b9", "\u0390"], ["\u03c5", "\u03b0"] ]; this.VKI_deadkey['\u00b0'] = this.VKI_deadkey['\u00ba'] = [ // Ring ["a", "\u00e5"], ["u", "\u016f"], ["A", "\u00c5"], ["U", "\u016e"] ]; this.VKI_deadkey['\u02DB'] = [ // Ogonek ["a", "\u0106"], ["e", "\u0119"], ["i", "\u012f"], ["o", "\u01eb"], ["u", "\u0173"], ["y", "\u0177"], ["A", "\u0105"], ["E", "\u0118"], ["I", "\u012e"], ["O", "\u01ea"], ["U", "\u0172"], ["Y", "\u0176"] ]; this.VKI_deadkey['\u02D9'] = [ // Dot-above ["c", "\u010B"], ["e", "\u0117"], ["g", "\u0121"], ["z", "\u017C"], ["C", "\u010A"], ["E", "\u0116"], ["G", "\u0120"], ["Z", "\u017B"] ]; this.VKI_deadkey['\u00B8'] = this.VKI_deadkey['\u201a'] = [ // Cedilla ["c", "\u00e7"], ["s", "\u015F"], ["C", "\u00c7"], ["S", "\u015E"] ]; this.VKI_deadkey[','] = [ // Comma ["s", (this.VKI_isIElt8) ? "\u015F" : "\u0219"], ["t", (this.VKI_isIElt8) ? "\u0163" : "\u021B"], ["S", (this.VKI_isIElt8) ? "\u015E" : "\u0218"], ["T", (this.VKI_isIElt8) ? "\u0162" : "\u021A"] ]; /* ***** Define Symbols **************************************** */ this.VKI_symbol = { '\u200c': "ZW\r\nNJ", '\u200d': "ZW\r\nJ" }; /* **************************************************************** * Attach the keyboard to an element * */ this.VKI_attachKeyboard = VKI_attach = function(elem) { if (elem.VKI_attached) return false; var keybut = document.createElement('img'); keybut.src = this.VKI_imageURI; keybut.alt = "Keyboard interface"; keybut.className = "keyboardInputInitiator"; keybut.title = "Display graphical keyboard interface"; keybut.elem = elem; keybut.onclick = function() { self.VKI_show(this.elem); }; elem.VKI_attached = true; elem.parentNode.insertBefore(keybut, (elem.dir == "rtl") ? elem : elem.nextSibling); if (this.VKI_isIE) { elem.onclick = elem.onselect = elem.onkeyup = function(e) { if ((e || event).type != "keyup" || !this.readOnly) this.range = document.selection.createRange(); }; } }; /* ***** Find tagged input & textarea elements ***************** */ var inputElems = [ document.getElementsByTagName('input'), document.getElementsByTagName('textarea') ]; for (var x = 0, elem; elem = inputElems[x++];) for (var y = 0, ex; ex = elem[y++];) if ((ex.nodeName == "TEXTAREA" || ex.type == "text" || ex.type == "password") && ex.className.indexOf("keyboardInput") > -1) this.VKI_attachKeyboard(ex); /* ***** Build the keyboard interface ************************** */ this.VKI_keyboard = document.createElement('table'); this.VKI_keyboard.id = "keyboardInputMaster"; this.VKI_keyboard.dir = "ltr"; this.VKI_keyboard.cellSpacing = this.VKI_keyboard.border = "0"; var thead = document.createElement('thead'); var tr = document.createElement('tr'); var th = document.createElement('th'); var kblist = document.createElement('select'); for (ktype in this.VKI_layout) { if (typeof this.VKI_layout[ktype] == "object") { var opt = document.createElement('option'); opt.value = ktype; opt.appendChild(document.createTextNode(ktype)); kblist.appendChild(opt); } } if (kblist.options.length) { kblist.value = this.VKI_kt; kblist.onchange = function() { self.VKI_kt = this.value; self.VKI_buildKeys(); self.VKI_position(); }; th.appendChild(kblist); } var label = document.createElement('label'); var checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.title = "Dead keys: " + ((this.VKI_deadkeysOn) ? "On" : "Off"); checkbox.defaultChecked = this.VKI_deadkeysOn; checkbox.onclick = function() { self.VKI_deadkeysOn = this.checked; this.title = "Dead keys: " + ((this.checked) ? "On" : "Off"); self.VKI_modify(""); return true; }; label.appendChild(this.VKI_deadkeysElem = checkbox); checkbox.checked = this.VKI_deadkeysOn; th.appendChild(label); tr.appendChild(th); var td = document.createElement('td'); if (this.VKI_switcher) { var switcher = document.createElement('span'); switcher.id = "keyboardInputSwitch"; switcher.appendChild(document.createTextNode("\u21d1")); switcher.title = "Switch keyboard position"; switcher.onmousedown = function() { this.className = "pressed"; }; switcher.onmouseup = function() { this.className = ""; }; switcher.onclick = function() { self.VKI_position(self.VKI_above ^= 1); this.firstChild.nodeValue = (self.VKI_above) ? "\u21d3" : "\u21d1"; return false; }; td.appendChild(switcher); } var clearer = document.createElement('span'); clearer.id = "keyboardInputClear"; clearer.appendChild(document.createTextNode("Clear")); clearer.title = "Clear this input"; clearer.onmousedown = function() { this.className = "pressed"; }; clearer.onmouseup = function() { this.className = ""; }; clearer.onclick = function() { self.VKI_target.value = ""; self.VKI_target.focus(); return false; }; td.appendChild(clearer); var closer = document.createElement('span'); closer.id = "keyboardInputClose"; closer.appendChild(document.createTextNode('X')); closer.title = "Close this window"; closer.onmousedown = function() { this.className = "pressed"; }; closer.onmouseup = function() { this.className = ""; }; closer.onclick = function() { self.VKI_close(); }; td.appendChild(closer); tr.appendChild(td); thead.appendChild(tr); this.VKI_keyboard.appendChild(thead); var tbody = document.createElement('tbody'); var tr = document.createElement('tr'); var td = document.createElement('td'); td.colSpan = "2"; var div = document.createElement('div'); div.id = "keyboardInputLayout"; td.appendChild(div); if (this.VKI_showVersion) { var div = document.createElement('div'); var ver = document.createElement('var'); ver.appendChild(document.createTextNode("v" + this.VKI_version)); div.appendChild(ver); td.appendChild(div); } tr.appendChild(td); tbody.appendChild(tr); this.VKI_keyboard.appendChild(tbody); if (this.VKI_isIE6) { this.VKI_iframe = document.createElement('iframe'); this.VKI_iframe.style.position = "absolute"; this.VKI_iframe.style.border = "0px none"; this.VKI_iframe.style.filter = "mask()"; this.VKI_iframe.style.zIndex = "999999"; this.VKI_iframe.src = this.VKI_imageURI; } /* **************************************************************** * Build or rebuild the keyboard keys * */ this.VKI_buildKeys = function() { this.VKI_shift = this.VKI_shiftlock = this.VKI_altgr = this.VKI_altgrlock = this.VKI_dead = false; this.VKI_deadkeysOn = (this.VKI_layout[this.VKI_kt].DDK) ? false : this.VKI_keyboard.getElementsByTagName('label')[0].getElementsByTagName('input')[0].checked; var container = this.VKI_keyboard.tBodies[0].getElementsByTagName('div')[0]; while (container.firstChild) container.removeChild(container.firstChild); for (var x = 0, hasDeadKey = false, lyt; lyt = this.VKI_layout[this.VKI_kt][x++];) { var table = document.createElement('table'); table.cellSpacing = table.border = "0"; if (lyt.length <= this.VKI_keyCenter) table.className = "keyboardInputCenter"; var tbody = document.createElement('tbody'); var tr = document.createElement('tr'); for (var y = 0, lkey; lkey = lyt[y++];) { var td = document.createElement('td'); if (this.VKI_symbol[lkey[0]]) { var span = document.createElement('span'); span.className = lkey[0]; span.appendChild(document.createTextNode(this.VKI_symbol[lkey[0]])); td.appendChild(span); } else td.appendChild(document.createTextNode(lkey[0] || "\xa0")); var className = []; if (this.VKI_deadkeysOn) for (key in this.VKI_deadkey) if (key === lkey[0]) { className.push("alive"); break; } if (lyt.length > this.VKI_keyCenter && y == lyt.length) className.push("last"); if (lkey[0] == " ") className.push("space"); td.className = className.join(" "); td.VKI_clickless = 0; if (!td.click) { td.click = function() { var evt = this.ownerDocument.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null); this.dispatchEvent(evt); }; } td.onmouseover = function() { if (self.VKI_clickless) { var _self = this; clearTimeout(this.VKI_clickless); this.VKI_clickless = setTimeout(function() { _self.click(); }, self.VKI_clickless); } if ((this.firstChild.nodeValue || this.firstChild.className) != "\xa0") this.className += " hover"; }; td.onmouseout = function() { if (self.VKI_clickless) clearTimeout(this.VKI_clickless); this.className = this.className.replace(/ ?(hover|pressed)/g, ""); }; td.onmousedown = function() { if (self.VKI_clickless) clearTimeout(this.VKI_clickless); if ((this.firstChild.nodeValue || this.firstChild.className) != "\xa0") this.className += " pressed"; }; td.onmouseup = function() { if (self.VKI_clickless) clearTimeout(this.VKI_clickless); this.className = this.className.replace(/ ?pressed/g, ""); }; td.ondblclick = function() { return false; }; switch (lkey[1]) { case "Caps": case "Shift": case "Alt": case "AltGr": case "AltLk": td.onclick = (function(type) { return function() { self.VKI_modify(type); return false; }; })(lkey[1]); break; case "Tab": td.onclick = function() { self.VKI_insert("\t"); return false; }; break; case "Bksp": td.onclick = function() { self.VKI_target.focus(); if (self.VKI_target.setSelectionRange) { if (self.VKI_target.readOnly && self.VKI_isWebKit) { var rng = [self.VKI_target.selStart || 0, self.VKI_target.selEnd || 0]; } else var rng = [self.VKI_target.selectionStart, self.VKI_target.selectionEnd]; if (rng[0] < rng[1]) rng[0]++; self.VKI_target.value = self.VKI_target.value.substr(0, rng[0] - 1) + self.VKI_target.value.substr(rng[1]); self.VKI_target.setSelectionRange(rng[0] - 1, rng[0] - 1); if (self.VKI_target.readOnly && self.VKI_isWebKit) { var range = window.getSelection().getRangeAt(0); self.VKI_target.selStart = range.startOffset; self.VKI_target.selEnd = range.endOffset; } } else if (self.VKI_target.createTextRange) { try { self.VKI_target.range.select(); } catch(e) { self.VKI_target.range = document.selection.createRange(); } if (!self.VKI_target.range.text.length) self.VKI_target.range.moveStart('character', -1); self.VKI_target.range.text = ""; } else self.VKI_target.value = self.VKI_target.value.substr(0, self.VKI_target.value.length - 1); if (self.VKI_shift) self.VKI_modify("Shift"); if (self.VKI_altgr) self.VKI_modify("AltGr"); self.VKI_target.focus(); return true; }; break; case "Enter": td.onclick = function() { if (self.VKI_target.nodeName != "TEXTAREA") { self.VKI_close(); this.className = this.className.replace(/ ?(hover|pressed)/g, ""); } else self.VKI_insert("\n"); return true; }; break; default: td.onclick = function() { var character = this.firstChild.nodeValue || this.firstChild.className; if (self.VKI_deadkeysOn && self.VKI_dead) { if (self.VKI_dead != character) { for (key in self.VKI_deadkey) { if (key == self.VKI_dead) { if (character != " ") { for (var z = 0, rezzed = false, dk; dk = self.VKI_deadkey[key][z++];) { if (dk[0] == character) { self.VKI_insert(dk[1]); rezzed = true; break; } } } else { self.VKI_insert(self.VKI_dead); rezzed = true; } break; } } } else rezzed = true; } self.VKI_dead = false; if (!rezzed && character != "\xa0") { if (self.VKI_deadkeysOn) { for (key in self.VKI_deadkey) { if (key == character) { self.VKI_dead = key; this.className += " dead"; if (self.VKI_shift) self.VKI_modify("Shift"); if (self.VKI_altgr) self.VKI_modify("AltGr"); break; } } if (!self.VKI_dead) self.VKI_insert(character); } else self.VKI_insert(character); } self.VKI_modify(""); return false; }; } tr.appendChild(td); tbody.appendChild(tr); table.appendChild(tbody); for (var z = 0; z < 4; z++) if (this.VKI_deadkey[lkey[z] = lkey[z] || "\xa0"]) hasDeadKey = true; } container.appendChild(table); } this.VKI_deadkeysElem.style.display = (!this.VKI_layout[this.VKI_kt].DDK && hasDeadKey) ? "inline" : "none"; }; this.VKI_buildKeys(); VKI_disableSelection(this.VKI_keyboard); /* **************************************************************** * Controls modifier keys * */ this.VKI_modify = function(type) { switch (type) { case "Alt": case "AltGr": this.VKI_altgr = !this.VKI_altgr; razModify("Alt", this.VKI_altgr); break; case "AltLk": this.VKI_altgrlock = !this.VKI_altgrlock; break; case "Caps": this.VKI_shiftlock = !this.VKI_shiftlock; razModify("Caps", this.VKI_shiftlock); break; case "Shift": this.VKI_shift = !this.VKI_shift; razModify("Shift", this.VKI_shift); break; } var vchar = 0; if (!this.VKI_shift != !this.VKI_shiftlock) vchar += 1; if (!this.VKI_altgr != !this.VKI_altgrlock) vchar += 2; var tables = this.VKI_keyboard.getElementsByTagName('table'); for (var x = 0; x < tables.length; x++) { var tds = tables[x].getElementsByTagName('td'); for (var y = 0; y < tds.length; y++) { var className = [], lkey = this.VKI_layout[this.VKI_kt][x][y]; if (tds[y].className.indexOf('hover') > -1) className.push("hover"); switch (lkey[1]) { case "Alt": case "AltGr": if (this.VKI_altgr) className.push("dead"); break; case "AltLk": if (this.VKI_altgrlock) className.push("dead"); break; case "Shift": if (this.VKI_shift) className.push("dead"); break; case "Caps": if (this.VKI_shiftlock) className.push("dead"); break; case "Tab": case "Enter": case "Bksp": break; default: if (type) { tds[y].removeChild(tds[y].firstChild); if (this.VKI_symbol[lkey[vchar]]) { var span = document.createElement('span'); span.className = lkey[vchar]; span.appendChild(document.createTextNode(this.VKI_symbol[lkey[vchar]])); tds[y].appendChild(span); } else tds[y].appendChild(document.createTextNode(lkey[vchar])); } if (this.VKI_deadkeysOn) { var character = tds[y].firstChild.nodeValue || tds[y].firstChild.className; if (this.VKI_dead) { if (character == this.VKI_dead) className.push("dead"); for (var z = 0; z < this.VKI_deadkey[this.VKI_dead].length; z++) { if (character == this.VKI_deadkey[this.VKI_dead][z][0]) { className.push("target"); break; } } } for (key in this.VKI_deadkey) if (key === character) { className.push("alive"); break; } } } if (y == tds.length - 1 && tds.length > this.VKI_keyCenter) className.push("last"); if (lkey[0] == " ") className.push("space"); tds[y].className = className.join(" "); } } }; /* **************************************************************** * Insert text at the cursor * */ this.VKI_insert = function(text) { razInsert(text); this.VKI_target.focus(); if (this.VKI_target.maxLength) this.VKI_target.maxlength = this.VKI_target.maxLength; if (typeof this.VKI_target.maxlength == "undefined" || this.VKI_target.maxlength < 0 || this.VKI_target.value.length < this.VKI_target.maxlength) { if (this.VKI_target.setSelectionRange) { if (this.VKI_target.readOnly && this.VKI_isWebKit) { var rng = [this.VKI_target.selStart || 0, this.VKI_target.selEnd || 0]; } else var rng = [this.VKI_target.selectionStart, this.VKI_target.selectionEnd]; this.VKI_target.value = this.VKI_target.value.substr(0, rng[0]) + text + this.VKI_target.value.substr(rng[1]); if (text == "\n" && window.opera) rng[0]++; this.VKI_target.setSelectionRange(rng[0] + text.length, rng[0] + text.length); if (this.VKI_target.readOnly && this.VKI_isWebKit) { var range = window.getSelection().getRangeAt(0); this.VKI_target.selStart = range.startOffset; this.VKI_target.selEnd = range.endOffset; } } else if (this.VKI_target.createTextRange) { try { this.VKI_target.range.select(); } catch(e) { this.VKI_target.range = document.selection.createRange(); } this.VKI_target.range.text = text; this.VKI_target.range.collapse(true); this.VKI_target.range.select(); } else this.VKI_target.value += text; if (this.VKI_shift) this.VKI_modify("Shift"); if (this.VKI_altgr) this.VKI_modify("AltGr"); this.VKI_target.focus(); } else if (this.VKI_target.createTextRange && this.VKI_target.range) this.VKI_target.range.select(); }; /* **************************************************************** * Show the keyboard interface * */ this.VKI_show = function(elem) { if (this.VKI_target = elem) { if (this.VKI_visible != elem) { if (this.VKI_isIE) { if (!this.VKI_target.range) { this.VKI_target.range = this.VKI_target.createTextRange(); this.VKI_target.range.moveStart('character', this.VKI_target.value.length); } this.VKI_target.range.select(); } try { this.VKI_keyboard.parentNode.removeChild(this.VKI_keyboard); } catch (e) {} if (this.VKI_clearPasswords && this.VKI_target.type == "password") this.VKI_target.value = ""; var elem = this.VKI_target; this.VKI_target.keyboardPosition = "absolute"; do { if (VKI_getStyle(elem, "position") == "fixed") { this.VKI_target.keyboardPosition = "fixed"; break; } } while (elem = elem.offsetParent); if (this.VKI_isIE6) document.body.appendChild(this.VKI_iframe); document.body.appendChild(this.VKI_keyboard); this.VKI_keyboard.style.top = this.VKI_keyboard.style.right = this.VKI_keyboard.style.bottom = this.VKI_keyboard.style.left = "auto"; this.VKI_keyboard.style.position = this.VKI_target.keyboardPosition; this.VKI_visible = this.VKI_target; this.VKI_position(); this.VKI_target.focus(); } else this.VKI_close(); } }; /* **************************************************************** * Position the keyboard * */ this.VKI_position = function(above) { if (typeof above == "undefined") above = self.VKI_above; if (self.VKI_visible) { var inputElemPos = VKI_findPos(self.VKI_target); above = (above) ? -self.VKI_keyboard.offsetHeight - 3 : self.VKI_target.offsetHeight + 3; self.VKI_keyboard.style.top = inputElemPos[1] - ((self.VKI_target.keyboardPosition == "fixed" && !self.VKI_isIE && !self.VKI_isMoz) ? VKI_scrollDist()[1] : 0) + above + "px"; self.VKI_keyboard.style.left = Math.min(VKI_innerDimensions()[0] - self.VKI_keyboard.offsetWidth - 15, inputElemPos[0]) + "px"; if (self.VKI_isIE6) { self.VKI_iframe.style.width = self.VKI_keyboard.offsetWidth + "px"; self.VKI_iframe.style.height = self.VKI_keyboard.offsetHeight + "px"; self.VKI_iframe.style.top = self.VKI_keyboard.style.top; self.VKI_iframe.style.left = self.VKI_keyboard.style.left; } } }; if (window.addEventListener) { window.addEventListener('resize', this.VKI_position, false); } else if (window.attachEvent) window.attachEvent('onresize', this.VKI_position); /* **************************************************************** * Razvan's hacking... * */ var newdiv = document.createElement('div'); document.body.appendChild(newdiv); this.VKI_attachKeyboard(newdiv); this.VKI_show(newdiv); /* **************************************************************** * Close the keyboard interface * */ this.VKI_close = VKI_close = function() { if (this.VKI_visible) { try { this.VKI_keyboard.parentNode.removeChild(this.VKI_keyboard); if (this.VKI_isIE6) this.VKI_iframe.parentNode.removeChild(this.VKI_iframe); } catch (e) {} this.VKI_target.focus(); this.VKI_target = this.VKI_visible = false; } }; }; function VKI_findPos(obj) { var curleft = curtop = 0; do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); return [curleft, curtop]; } function VKI_innerDimensions() { if (self.innerHeight) { return [self.innerWidth, self.innerHeight]; } else if (document.documentElement && document.documentElement.clientHeight) { return [document.documentElement.clientWidth, document.documentElement.clientHeight]; } else if (document.body) return [document.body.clientWidth, document.body.clientHeight]; return [0, 0]; } function VKI_scrollDist() { var html = document.getElementsByTagName('html')[0]; if (html.scrollTop && document.documentElement.scrollTop) { return [html.scrollLeft, html.scrollTop]; } else if (html.scrollTop || document.documentElement.scrollTop) return [html.scrollLeft + document.documentElement.scrollLeft, html.scrollTop + document.documentElement.scrollTop]; return [0, 0]; } function VKI_getStyle(obj, styleProp) { if (obj.currentStyle) { var y = obj.currentStyle[styleProp]; } else if (window.getComputedStyle) var y = window.getComputedStyle(obj, null)[styleProp]; return y; } function VKI_disableSelection(elem) { elem.onselectstart = function() { return false; }; elem.unselectable = "on"; elem.style.MozUserSelect = "none"; elem.style.cursor = "default"; if (window.opera) elem.onmousedown = function() { return false; }; } /* ***** Attach this script to the onload event ****************** */ if (window.addEventListener) { window.addEventListener('load', VKI_buildKeyboardInputs, false); } else if (window.attachEvent) window.attachEvent('onload', VKI_buildKeyboardInputs);
JavaScript
var editor = CodeMirror.fromTextArea('code', { parserfile: ["tokenizejavascript.js", "parsejavascript.js"], stylesheet: "/public/cm/css/jscolors.css", path: "/public/cm/js/", continuousScanning: 200, lineNumbers: false }); function runSelection () { var scr = document.getElementById('code').getCode() }
JavaScript
// Inspired from a few places, like // http://www.codelifter.com // http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/CSS/Q_23151088.html function razMove (m,x,y) { try { razInvoke ('/mutant/robot/mousemove?dx='+x+'&dy='+y+'&tstamp='+m) } catch(e) {} } function razPress (which,x,y) { try { razInvoke ('/mutant/robot/mousedown?which='+which+'&dx='+x+'&dy='+y) } catch(e) {} } function razRelease (which,x,y) { try { razInvoke ('/mutant/robot/mouseup?which='+which+'&dx='+x+'&dy='+y) } catch(e) {} } function razClick (which,x,y) { try { razInvoke ('/mutant/robot/mouseclick?which='+which+'&dx='+x+'&dy='+y) } catch(e) {} } function mp_lc() {razClick("left", 0, 0) } function mp_ld() {razPress("left", 0, 0) } function mp_lu() {razRelease("left", 0, 0) } function mp_rc() {razClick("right", 0, 0) } function mp_rd() {razPress("right", 0, 0) } function mp_ru() {razRelease("right", 0, 0) } var mp_mdown, mp_mup, mp_mmove; var mp_tstart, mp_tend, mp_tmove; function MM_setup () { var self = this; MM_setup2(); } function MM_setup2 () { var self = this; this.VKI_isIE = /*@cc_on!@*/false; this.VKI_isIE6 = /*@if(@_jscript_version == 5.6)!@end@*/false; this.VKI_isIElt8 = /*@if(@_jscript_version < 5.8)!@end@*/false; this.VKI_isMoz = (navigator.product == "Gecko"); this.VKI_isWebKit = RegExp("KHTML").test(navigator.userAgent); var mainc = document.createElement('div'); document.body.appendChild(mainc); this.container = document.createElement('div'); //container.style.position = 'absolute'; this.container.id= 'mp_container'; this.container.style.width = '300px'; this.container.style.height = '200px'; this.container.style.left = '10px'; this.container.style.background = "darkgray"; this.container.style.top = '10px'; this.container.style.border = "5px solid navy"; //container.style.zIndex = 100; //document.body.appendChild(this.container); mainc.appendChild(this.container); var newDiv = document.createElement('DIV'); newDiv.style.position = 'absolute'; newDiv.style.width = '20px'; newDiv.style.height = '20px'; newDiv.style.left = '20px'; newDiv.style.top = '20px'; newDiv.style.border = "1px solid red"; newDiv.style.background = "red"; newDiv.style.zIndex = 100; this.container.appendChild(newDiv) var c1 = document.createElement('div'); c1.style.position = 'absolute'; c1.id= 'mp_lcontainer'; c1.style.width = '50px'; c1.style.height = '200px'; c1.style.left = '320px'; c1.style.top = '10px'; c1.style.background = "darkgray"; mainc.appendChild(c1); var b1 = document.createElement('DIV'); //b1.style.position = 'absolute'; b1.style.width = '50px'; b1.style.height = '100px'; b1.style.left = '0px'; b1.style.top = '0px'; b1.style.border = "1px solid red"; b1.style.background = "red"; b1.style.zIndex = 100; c1.appendChild(b1) var b2 = document.createElement('DIV'); //b2.style.position = 'absolute'; b2.style.width = '50px'; b2.style.height = '100px'; b2.style.left = '0px'; b2.style.top = '51px'; b2.style.border = "1px solid blue"; b2.style.background = "blue"; b2.style.zIndex = 100; c1.appendChild(b2) //if (!IE) document.captureEvents(Event.MOUSEMOVE) //document.onmousemove = xy; var tempX = 0; var tempY = 0; var lastMillis = 0; function rMove(tempX, tempY, forced) { var x = (new Date()).getTime(); if ((x-lastMillis) > 100 || forced) { lastMillis=x; newDiv.style.top=tempY+'px'; newDiv.style.left=tempX+'px'; var dx = tempX*1000/this.container.offsetWidth; var dy = tempY*1000/this.container.offsetHeight; razMove (lastMillis, dx, dy) } } function xy(e, forced) { if (this.VKI_isIE) { // grab the x-y pos.s if browser is IE tempX = event.clientX + document.body.scrollLeft; tempY = event.clientY + document.body.scrollTop; } else { // grab the x-y pos.s if browser is NS tempX = e.pageX; tempY = e.pageY; } if (tempX < 0){tempX = 0;} if (tempY < 0){tempY = 0;} rMove (tempX, tempY, forced) } mp_mmove = function rmMove (e) { e.preventDefault(); xy(e, false) } mp_mdown = function rmDown (e) { e.preventDefault(); document.getElementById('mp_container').onmousemove=mp_mmove; xy(e, true) } mp_mup = function rmUp (e) { document.getElementById('mp_container').onmousemove=null; xy(e, true) } document.getElementById('mp_container').onmousedown=mp_mdown; document.getElementById('mp_container').onmouseup=mp_mup; //b1.onmousedown=mp_ld; //b1.onmouseup=mp_lu; b1.onclick=mp_lc; //b2.onmousedown=mp_rd; //b2.onmouseup=mp_ru; b2.onclick=mp_rc; //------------------touch stuff on ipod function txy (e, forced) { //curX = e.targetTouches[0].pageX - startX; //curY = e.targetTouches[0].pageY - startY; curX = e.targetTouches[0].pageX; curY = e.targetTouches[0].pageY; rMove(curX, curY, forced) } mp_tstart = function touchStart (e) { e.preventDefault(); txy(e, true) } mp_tmove = function touchMove (e) { e.preventDefault(); txy(e, false) } mp_tend = function touchEnd (e) { e.preventDefault(); txy(e, true) } document.getElementById('mp_container').addEventListener("touchstart", mp_tstart, false); document.getElementById('mp_container').addEventListener("touchmove", mp_tmove, false); document.getElementById('mp_container').addEventListener("touchend", mp_tend, false); //c.addEventListener("touchcancel", touchCancel, false); //c.addEventListener("gesturestart", gestureStart, false); //c.addEventListener("gesturechange", gestureChange, false); //c.addEventListener("gestureend", gestureEnd, false); } /* ***** Attach this script to the onload event ****************** */ if (window.addEventListener) { window.addEventListener('load', MM_setup, false); } else if (window.attachEvent) window.attachEvent('onload', MM_setup);
JavaScript
function rezoom () { var z = screen.width/400; var a1 = document.createTextNode(" screen.width="+screen.width); var a2 = document.createTextNode(" rezoom at="+z); document.body.appendChild(a1); document.body.appendChild(a2); document.body.style.zoom=z; } /* from http://www.quirksmode.org/quirksmode.js */ function razInvoke(url) { sendRequest(url, nullFunc) } function nullFunc(req) { } /* XMLHTTP */ function sendRequest(url,callback,postData) { var req = createXMLHTTPObject(); if (!req) return; var method = (postData) ? "POST" : "GET"; req.open(method,url,true); req.setRequestHeader('User-Agent','XMLHTTP/1.0'); if (postData) req.setRequestHeader('Content-type','application/x-www-form-urlencoded'); req.onreadystatechange = function () { if (req.readyState != 4) return; if (req.status != 200 && req.status != 304) { // alert('HTTP error ' + req.status); return; } callback(req); } if (req.readyState == 4) return; req.send(postData); } function XMLHttpFactories() { return [ function () {return new XMLHttpRequest()}, function () {return new ActiveXObject("Msxml2.XMLHTTP")}, function () {return new ActiveXObject("Msxml3.XMLHTTP")}, function () {return new ActiveXObject("Microsoft.XMLHTTP")} ]; } function createXMLHTTPObject() { var xmlhttp = false; var factories = XMLHttpFactories(); for (var i=0;i<factories.length;i++) { try { xmlhttp = factories[i](); } catch (e) { continue; } break; } return xmlhttp; } /* ***** Attach this script to the onload event ****************** */ //if (window.addEventListener) { // window.addEventListener('load', rezoom, false); //} else if (window.attachEvent) { // window.attachEvent('onload', rezoom); //}
JavaScript
var zy_json_opid=1000; var zy_json_session=new Object; (function(g, h) { var j = g.document, navigator = g.navigator, location = g.location; var k = (function() { var e = function(a, b) { return new e.fn.init(a, b, rootjQuery) }, _jQuery = g.jQuery, _$ = g.$, rootjQuery, quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, toString = Object.prototype.toString; e.fn = e.prototype = { constructor : e, init : function(a, b, c) { var d, elem, ret, doc; return this }, selector : "", jquery : "1.6", length : 0, size : function() { return this.length }, toArray : function() { return slice.call(this, 0) } }; e.fn.init.prototype = e.fn; e.extend = e.fn.extend = function() { var a, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2 } if (typeof target !== "object" && !e.isFunction(target)) { target = {} } if (length === i) { target = this; --i } for (; i < length; i++) { if ((a = arguments[i]) != null) { for (name in a) { src = target[name]; copy = a[name]; if (target === copy) { continue } if (deep && copy && (e.isPlainObject(copy) || (copyIsArray = e .isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && e.isArray(src) ? src : [] } else { clone = src && e.isPlainObject(src) ? src : {} } target[name] = e.extend(deep, clone, copy) } else if (copy !== h) { target[name] = copy } } } } return target }; e.extend({ noConflict : function(a) { if (g.$ === e) { g.$ = _$ } if (a && g.jQuery === e) { g.jQuery = _jQuery } return e }, isPlainObject : function(a) { if (!a || e.type(a) !== "object" || a.nodeType || e.isWindow(a)) { return false } if (a.constructor && !hasOwn.call(a, "constructor") && !hasOwn.call(a.constructor.prototype, "isPrototypeOf")) { return false } var b; for (b in a) { } return b === h || hasOwn.call(a, b) }, noop : function() { }, guid : 1 }); rootjQuery = e(j); return e })(); k.extend({ ajaxJSONP : function(b) { var c = 'jsonp' + (++k.guid), script = j.createElement('script'); g[c] = function(a) { b.success(a); delete g[c] }; script.src = b.url.replace(/=\?/, '=' + c); j.getElementsByTagName("head")[0].appendChild(script) }, ajaxSettings : { type : 'GET', beforeSend : k.noop, success : k.noop, error : k.noop, complete : k.noop, accepts : { script : 'text/javascript, application/javascript', json : 'application/json', xml : 'application/xml, text/xml', html : 'text/html', text : 'text/plain' }, headers : [] }, ajax : function(b) { var c = k.extend({}, b); for (key in k.ajaxSettings) if (!c[key]) c[key] = k.ajaxSettings[key]; if (/=\?/.test(c.url)) return k.ajaxJSONP(c); if (!c.url) c.url = g.location.toString(); if (c.data && !c.contentType) c.contentType = 'application/x-www-form-urlencoded'; if (k.isPlainObject(c.data)) c.data = k.param(c.data); if (c.type.match(/get/i) && c.data) { var d = c.data; if (c.url.match(/\?.*=/)) { d = '&' + d } else if (d[0] != '?') { d = '?' + d } c.url += d } var f = c.accepts[c.dataType], xhr = new XMLHttpRequest(); if (!!xhr.onprogress) { xhr.onprogress = function(a) { if (c.downCallback) { c.downCallback(xhr, a) } else { return function() { } } } } xhr.onreadystatechange = function() { if (c.readyCallback) { c.readyCallback(xhr); return } if (xhr.readyState == 4) { var a, error = false; if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) { if (f == 'application/json') { try { a = JSON.parse(xhr.responseText) } catch (e) { error = e } } else a = xhr.responseText; if (error) c.error(xhr, 'parsererror', error); else c.success(a, 'success', xhr) } else { error = true; c.error(xhr, 'error') } c.complete(xhr, error ? 'error' : 'success') } }; xhr.open(c.type, c.url, true); if (c.beforeSend(xhr, c) === false) { xhr.abort(); return false } if (c.contentType) c.headers['Content-Type'] = c.contentType; for (name in c.headers) xhr.setRequestHeader(name, c.contentType); xhr.send(c.data); return xhr }, clearLS:function(a) { if(window.localStorage) { if(a) window.localStorage.removeItem(a); else window.localStorage.clear(); } }, getJSON : function(a, b,c,d,e,f,g) { c = c ||'json'; if(window.location.href.substring(0,7).toLowerCase()=="file://") { if(a.substring(0,4).toLowerCase()=="http") { uexXmlHttpMgr.onData = function (_opid, status, result) { var str = result; var st = parseInt(status); var json = ''; if(st==0) return; else if(st==-1) { str = '{"status":"-1", "message":"network error!"}'; str = JSON.parse(str); uexXmlHttpMgr.close(_opid); if(!(zy_json_session[_opid].errcb===undefined)) zy_json_session[_opid].errcb(str); delete zy_json_session[_opid]; return; } else if(result.indexOf('?(')>=0) { var s = result.indexOf('?('); var e = result.lastIndexOf(")"); str = result.substring(s+2,e); } if(c.toLowerCase()=="json"){ try{ json = JSON.parse(str); }catch(s){ str = '{"status":"-1", "message":"json parse failed!"}'; str = JSON.parse(str); uexXmlHttpMgr.close(_opid); if(!(zy_json_session[_opid].errcb===undefined)) zy_json_session[_opid].errcb(str); delete zy_json_session[_opid]; return; } } else json = result; if(zy_json_session[zy_json_opid].ol && window.localStorage) { window.localStorage[zy_json_session[zy_json_opid].url]=str; } uexXmlHttpMgr.close(_opid); if(!(zy_json_session[_opid].cb===undefined)) zy_json_session[_opid].cb(json); delete zy_json_session[_opid]; } if(g && window.localStorage) { var r=window.localStorage[a]; if(r) { r=(c.toLowerCase()=="json")?JSON.parse(r):r; if(r) return b(r); } } zy_json_opid++; zy_json_session[zy_json_opid] = new Object; zy_json_session[zy_json_opid].cb=b; zy_json_session[zy_json_opid].errcb= d; zy_json_session[zy_json_opid].ol=g; zy_json_session[zy_json_opid].url=a; uexXmlHttpMgr.open(zy_json_opid, !e?"GET":e, a,60000); if(f) { for(var it in f) { uexXmlHttpMgr.setPostData(zy_json_opid,f[it].type,f[it].key,f[it].value); } } uexXmlHttpMgr.send(zy_json_opid); } else { zy_json_opid++; zy_json_session[zy_json_opid] = new Object; zy_json_session[zy_json_opid].cb=b; zy_json_session[zy_json_opid].errcb= d; uexWidgetOne.cbError= function(inOpId,inErrorCode,inErrorDes){ { var str = '{"status":"-1", "message":"read file failed!"}'; str = JSON.parse(str); uexFileMgr.closeFile(inOpId); if(!(zy_json_session[inOpId].errcb===undefined)) zy_json_session[inOpId].errcb(str); delete zy_json_session[inOpId]; return; } } uexFileMgr.cbOpenFile = function(opId,dataType,data){ uexFileMgr.cbReadFile = function(_opid,_Type, _data){ if(_Type==0){ var json = _data; if(c.toLowerCase()=="json") { try{ json = JSON.parse(json); }catch(s){ var str = '{"status":"-1", "message":"json parse failed!"}'; str = JSON.parse(str); uexFileMgr.closeFile(_opid); if(!(zy_json_session[_opid].errcb===undefined)) zy_json_session[_opid].errcb(str); delete zy_json_session[_opid]; return; } } uexFileMgr.closeFile(_opid); if(!(zy_json_session[_opid].cb===undefined)) zy_json_session[_opid].cb(json); delete zy_json_session[_opid]; } } uexFileMgr.readFile(opId,-1); } uexFileMgr.cbIsFileExistByPath = function(opId,dataType,data){ if(dataType==2){ if(data==1){ uexFileMgr.openFile(zy_json_opid,a,1); } else{ var str = '{"status":"-1", "message":"file does not exist!"}'; str = JSON.parse(str); if(!(zy_json_session[inOpId].errcb===undefined)) zy_json_session[inOpId].errcb(str); delete zy_json_session[inOpId]; return; } } } uexFileMgr.isFileExistByPath(a); } } else { k.ajax({ url : a, success : b, dataType : c, error: d }); } } }); g.jQuery = g.$ = k })(window);
JavaScript
function zy_selectmenu(id){ var sl = document.getElementById(id); if (sl) { var sp = sl.parentElement; //<span> if (sp) { var ch = sp.getElementsByTagName("div")[0]; var t = sl.options[sl.selectedIndex].text; if (ch) { ch.innerHTML = t; } } } } function zy_for(e, cb){ var ch; if(e.currentTarget) ch = e.currentTarget.previousElementSibling; else ch = e.previousElementSibling; if (ch.nodeName == "INPUT") { if (ch.type == "checkbox") ch.checked = !ch.checked; if (ch.type == "radio" && !ch.checked) ch.checked = "checked"; } if (cb) cb(e, ch.checked); } function zy_fold(e, col){ var a = e.currentTarget.nextElementSibling; if (a.nodeName == "DIV") { if (col) a.className = a.className.replace("col-c", ""); else a.className += ' col-c'; } } function zy_touch(c, f){ var t = event.currentTarget; if (!t.zTouch) { t.zTouch = new zyClick(t, f, c); t.zTouch._touchStart(event); } } function zy_parse(){ var params = {}; var loc = String(document.location); if (loc.indexOf("?") > 0) loc = loc.substr(loc.indexOf('?') + 1); else loc = uexWindow.getUrlQuery(); var pieces = loc.split('&'); params.keys = []; for (var i = 0; i < pieces.length; i += 1) { var keyVal = pieces[i].split('='); params[keyVal[0]] = decodeURIComponent(keyVal[1]); params.keys.push(keyVal[0]); } return params; } function $$(id) { return document.getElementById(id); } function int(s) { return parseInt(s); } function zy_con(id,url,x,y) { var s=window.getComputedStyle($$(id),null); uexWindow.openPopover(id,"0",url,"",int(x),int(y),int(s.width),int(s.height),int(s.fontSize),"0"); } function zy_resize(id,x,y) { var s=window.getComputedStyle($$(id),null); uexWindow.setPopoverFrame(id,int(x),int(y),int(s.width),int(s.height)); } function zy_init() { if(window.navigator.platform=="Win32") document.body.style.fontSize=window.localStorage["defaultfontsize"]; }
JavaScript
function getSelector(s) { if (s.nodeType && s.nodeType == 1) { return s; } else if (typeof s == 'string') { return (document.getElementById(s) || document.querySelector(s)); } return null; } function zy_anim_listen(s,c) { var sel=getSelector(s); if(sel.animCB!=c) { if(sel.animCB) { sel.removeEventListener('webkitTransitionEnd', sel.animCB, true); } sel.animCB=c; if(c) { sel.addEventListener("webkitTransitionEnd", c, false); } } } function zy_anim_push(s,a) { var sel=getSelector(s); if(sel) { if(sel.className.indexOf(a)<0) sel.className+=" "+a; } } function zy_anim_pop(s,a) { var sel=getSelector(s); if(sel) { if (a) sel.className = sel.className.replace(a, ""); else { var n = sel.className.lastIndexOf(" "); if(sel.className.substr(n).indexOf(" a-")>=0) sel.className=sel.className.substr(0,n); } } }
JavaScript
var zy_tmpl_count=function(dd) { if(Object.prototype.toString.apply(dd)==="[object Array]") { return dd.length; } else { var c=0; for(var i in dd) c++; return c; } } var _f = function(d,c,k1,k2,l){ var q = c.match(/(first:|last:)(\"|\'*)([^\"\']*)(\"|\'*)/); if(!q) return; if(q[1]==k1){ if(q[2]=='\"'||q[2]=='\''){ return q[3]; } else return d[q[3]]; } else if(q[1]==k2 && l>1) return ""; } var t_f = function(t,d,i,l,cb){ return t.replace( /\$\{([^\}]*)\}/g,function(m,c){ if(c.match(/index:/)){ return i; } if(c.match(/cb:/) && cb){ return cb(d,c.match(/cb:(.*)/)); } if(i==0){ var s=_f(d,c,"first:","last:",l); if(s) return s; } if(i==(l-1)){ var s= _f(d,c,"last:","first:",l); if(s) return s; } var ar=c.split('.'); var res=d; for(var key in ar) res=res[ar[key]]; return res||""; }); } var zy_tmpl = function(t,dd,l,cb,scb){ var r = ""; { var index=0; for(var i in dd) { if(scb) scb(0,i,dd[i]); var rr=t_f(t,dd[i],index,l,cb); if(scb) scb(1,rr,dd[i]); r+=rr; index++; } } return r; } var zy_tmpl_s = function(t,dd,cb) { return t_f(t,dd,-1,-1,cb); }
JavaScript
/** * */ var zy_dl_opid=1000; var zy_dl_session=new Object; var zy_dl_taskcount=0; var zy_muticount=3; var lstor=(window.localStorage?window.localStorage:(new Object)); function zy_initcache(cb) { uexFileMgr.cbGetFileRealPath = function(opCode, dataType, path) { zy_dl_session.rp = path; if (cb) cb(); } uexFileMgr.getFileRealPath("wgt://"); } function zy_imgcache(sel,key,url,cb,err,dest,ext) { uexDownloaderMgr.onStatus = function(opCode, fileSize, percent, status) { switch (status) { case 0 : break; case 1 : var s = zy_dl_session[opCode]; uexDownloaderMgr.closeDownloader(opCode); uexDownloaderMgr.clearTask(s.rul); lstor[s.key] = s.dest.replace("wgt://", zy_dl_session.rp); setTimeout(function(){ if (s.cb) s.cb(s.sel, lstor[s.key]); else $$(s.sel).style.backgroundImage = "url(" + lstor[s.key] + ")"; zy_cleartask(opCode); },100); break; case 2 : uexDownloaderMgr.closeDownloader(opCode); if (zy_dl_session[opCode].err) zy_dl_session[opCode].err(); zy_cleartask(opCode); return; } }; uexDownloaderMgr.cbCreateDownloader = function(opCode, dataType, data) { if (data == 0) { var s = zy_dl_session[opCode]; if (!s.dest) { var d = new Date(); s.dest = "wgt://data/icache/" + d.valueOf() + opCode + "." + (s.ext ? s.ext : "jpg"); } else s.dest = "wgt://data/icache/"+s.dest; uexDownloaderMgr.download(opCode, s.url, s.dest, '0'); } else { uexDownloaderMgr.closeDownloader(opCode); if (zy_dl_session[opCode].err) zy_dl_session[opCode].err(); zy_cleartask(opId); } }; uexFileMgr.cbIsFileExistByPath=function(opId,dataType,data) { if(int(data)) { var s = zy_dl_session[opId]; setTimeout(function(){ if (s.cb) s.cb(s.sel,s.rp); else $$(s.sel).style.backgroundImage = "url(" + s.rp + ")"; zy_cleartask(opId); },100); } else{ uexDownloaderMgr.createDownloader(opId); } } { zy_dl_opid++; zy_dl_session[zy_dl_opid] = new Object; zy_dl_session[zy_dl_opid].sel = sel; zy_dl_session[zy_dl_opid].key = key; zy_dl_session[zy_dl_opid].cb = cb; zy_dl_session[zy_dl_opid].err = err; zy_dl_session[zy_dl_opid].url = url; zy_dl_session[zy_dl_opid].dest = dest; zy_dl_session[zy_dl_opid].ext = ext; zy_dl_session[zy_dl_opid].state=0; zy_runcache(); } if(lstor[key]) return lstor[key]; else return ""; } function zy_cleartask(id) { delete zy_dl_session[id]; zy_dl_taskcount--; zy_runcache(); } function zy_runcache(){ if (zy_dl_taskcount < zy_muticount) { for (var i in zy_dl_session) { var s=zy_dl_session[i]; if (s.state == 0) { s.state = 1; zy_dl_taskcount++; s.rp = lstor[s.key]; if (s.rp) uexFileMgr.isFileExistByPath("" + i, s.rp); else uexDownloaderMgr.createDownloader(i); return; } } } } function zy_clearcache() { lstor.clear(); uexFileMgr.deleteFileByPath("wgt://data/icache"); }
JavaScript
var $support = { transform3d: ('WebKitCSSMatrix' in window), touch: ('ontouchstart' in window) }; var $E = { start: $support.touch ? 'touchstart' : 'mousedown', move: $support.touch ? 'touchmove' : 'mousemove', end: $support.touch ? 'touchend' : 'mouseup', transEnd:'webkitTransitionEnd' }; function getPage (event, page) { return $support.touch ? event.changedTouches[0][page] : event[page]; } var zyEvent = function(selector,moveFun,endFun,lock,transEnd){ var self = this; var max = 50; self.Max = {X:max,Y:max}; self.endFun = endFun || null; self.moveFun = moveFun || null; self.transEnd = transEnd||null; self.type = ""; self._locked=lock; self.start = false; if(typeof selector == 'object') self.element = selector; else if(typeof selector == 'string') self.element = document.getElementById(selector); self.element.addEventListener($E.start, self, false); self.element.addEventListener($E.move, self, false); self.element.addEventListener($E.transEnd, self, false); document.addEventListener($E.end, self, false); return self; } zyEvent.prototype = { handleEvent: function(event) { var self = this; switch (event.type) { case $E.start: self._touchStart(event); break; case $E.move: self._touchMove(event); break; case $E.end: self._touchEnd(event); break; case 'click': self._click(event); break; case $E.transEnd: if(self.transEnd) self.transEnd(event); break; } }, _touchStart: function(event) { var self = this; self.start = true; if (!$support.touch) { event.preventDefault(); } if(self._locked) { event.stopPropagation(); } self.type = ""; self.startPageX = getPage(event, 'pageX'); self.startPageY = getPage(event, 'pageY'); self.startTime = event.timeStamp; }, _touchMove: function(event) { var self = this; if(!self.start) return; var pageX = getPage(event, 'pageX'), pageY = getPage(event, 'pageY'), deltaX = pageX - self.startPageX, deltaY = pageY - self.startPageY; if(self._locked) { event.preventDefault(); event.stopPropagation(); } if(Math.abs(deltaX)> Math.abs(deltaY) && deltaX<-self.Max.X) self.type = "left"; if(Math.abs(deltaX)> Math.abs(deltaY) && deltaX>self.Max.X) self.type = "right"; if(Math.abs(deltaX)< Math.abs(deltaY) && deltaY<-self.Max.Y) self.type = "up"; if(Math.abs(deltaX)< Math.abs(deltaY) && deltaY>self.Max.Y) self.type = "down"; if(self.moveFun) self.moveFun(self.element,deltaX,deltaY); }, _touchEnd: function(event) { var self = this; if(self._locked) { event.preventDefault(); event.stopPropagation(); } if(self.start == true) { var pageX = getPage(event, 'pageX'), pageY = getPage(event, 'pageY'), deltaX = pageX - self.startPageX, deltaY = pageY - self.startPageY; if(self.endFun) self.endFun(self.element,deltaX,deltaY,self.type); self.start = false; } }, _click: function(event) { var self = this; event.stopPropagation(); event.preventDefault(); }, destroy: function() { var self = this; self.element.parentNode.removeEventListener($E.start, self); self.element.parentNode.removeEventListener($E.move, self); self.element.removeEventListener($E.transEnd, self); document.removeEventListener($E.end, self); } }
JavaScript
var $support = { transform3d: ('WebKitCSSMatrix' in window), touch: ('ontouchstart' in window) }; var $E = { start: $support.touch ? 'touchstart' : 'mousedown', move: $support.touch ? 'touchmove' : 'mousemove', end: $support.touch ? 'touchend' : 'mouseup', transEnd:'webkitTransitionEnd' }; function getPage (event, page) { return $support.touch ? event.changedTouches[0][page] : event[page]; } var zyClick = function(selector,clickFun,css){ var self = this; self._clickFun = clickFun || null; self._click=false; self.css = css; if(typeof selector == 'object') self.element = selector; else if(typeof selector == 'string') self.element = document.getElementById(selector); self.attribute=self.element.getAttribute("onclick"); self.element.removeAttribute("onclick"); self.element.addEventListener($E.start, self, false); self.element.addEventListener($E.move, self, false); self.element.addEventListener($E.end, self, false); document.addEventListener($E.end, self, false); return self; } zyClick.prototype = { handleEvent: function(event) { var self = this; switch (event.type) { case $E.start: self._touchStart(event); break; case $E.move: self._touchMove(event); break; case $E.end: self._touchEnd(event); break; } }, _touchStart: function(event) { var self = this; self.start = true; self._click=true; self.startPageX = getPage(event, 'pageX'); self.startPageY = getPage(event, 'pageY'); self.startTime = event.timeStamp; if (self.css && !self.touchTime) { self.touchTime=setTimeout(function(){ if (self._click && self.element.className.indexOf(self.css)<0) self.element.className += (" " + self.css); }, 50); } }, _touchMove: function(event) { var self = this; if(!self.start) return; var pageX = getPage(event, 'pageX'), pageY = getPage(event, 'pageY'), deltaX = pageX - self.startPageX, deltaY = pageY - self.startPageY; if((Math.abs(deltaX)>10 || Math.abs(deltaY)>10) && self._click) { clearTimeout(self.touchTime); self.touchTime=null; self._click=false; if(self.css) self.element.className=self.element.className.replace(" "+self.css,""); } }, _touchEnd: function(event) { var self = this; if(self.start == true) { if (self.touchTime) { clearTimeout(self.touchTime); self.touchTime=null; } self.start = false; if(self.css) self.element.className=self.element.className.replace(" "+self.css,""); if(self._click) { self._click=false; if(event.timeStamp - self.startTime>1000) return; if(self._clickFun) self._clickFun(self.element); if(self.attribute) eval(self.attribute); } } }, destroy: function() { var self = this; self.element.removeEventListener($E.start, self); self.element.removeEventListener($E.move, self); self.element.removeEventListener($E.end, self); document.removeEventListener($E.end, self); } }
JavaScript
var $support = { transform3d: ('WebKitCSSMatrix' in window), touch: ('ontouchstart' in window) }; var $E = { start: $support.touch ? 'touchstart' : 'mousedown', move: $support.touch ? 'touchmove' : 'mousemove', end: $support.touch ? 'touchend' : 'mouseup', transEnd:'webkitTransitionEnd' }; function getTranslateX(x) { return $support.transform3d ? 'translate3d('+x+'px, 0, 0)' : 'translate('+x+'px, 0)'; } function getTranslateY(y) { return $support.transform3d ? 'translate3d(0,'+y+'px, 0)' : 'translate(0,'+y+'px)'; } function getPage (event, page) { return $support.touch ? event.changedTouches[0][page] : event[page]; } var zySlide = function(selector,dir,endFun,lock,transEnd){ var self = this; self._locked= lock; self.endFun = endFun || null; self.transEnd = transEnd||null; self.nodes = []; //V:vertical //H:horizontal self.dir = dir||"H"; if (selector.nodeType && selector.nodeType == 1) { self.element = selector; } else if (typeof selector == 'string') { self.id=selector; self.element = document.getElementById(selector) || document.querySelector(selector); } //self.element.style.display = '-webkit-box'; //self.element.style.webkitTransitionProperty = '-webkit-transform'; //self.element.style.webkitTransitionTimingFunction = 'cubic-bezier(0,0,0.25,1)'; //self.element.style.webkitTransitionDuration = '0'; if(self.dir=="H") self.element.style.webkitTransform = getTranslateX(0); else self.element.style.webkitTransform = getTranslateY(0); self.conf = {}; self.touchEnabled = true; self.currentPoint = 0; self.currentXY = 0; self.refresh(); // self.element.parentNode.addEventListener($E.start, self, false); self.element.parentNode.addEventListener($E.move, self, false); self.element.addEventListener($E.transEnd, self, false); document.addEventListener($E.end, self, false); return self; } zySlide.prototype = { handleEvent: function(event) { var self = this; switch (event.type) { case $E.start: self._touchStart(event); break; case $E.move: self._touchMove(event); break; case $E.end: self._touchEnd(event); break; case 'click': self._click(event); break; case $E.transEnd: if(self.transEnd) self.transEnd(event); break; } }, addSection : function(obj){ var self = this; self.element.appendChild(obj); self.refresh(); }, getSection : function(i){ var self = this; var obj = self.nodes[i]; if(obj.childNodes[1] && obj.childNodes[1].childNodes[1]) return obj.childNodes[1].childNodes[1].childNodes[1]; else return obj; }, refresh: function() { var self = this; var conf = self.conf; // setting max point self.maxPoint = conf.point || (function() { var childNodes = self.element.childNodes, itemLength = 0, i = 0, len = childNodes.length, node; for(; i < len; i++) { node = childNodes[i]; if (node.nodeType === 1) { self.nodes[itemLength]=node; itemLength++; } } if (itemLength > 0) { itemLength--; } return itemLength; })(); // setting distance if(self.dir=="H") self.distance = parseInt(conf.distance || window.getComputedStyle(self.element,null).width); else self.distance = parseInt(conf.distance || window.getComputedStyle(self.element,null).height); // setting maxX maxY self.maxXY = conf.maxXY ? - conf.maxXY : - self.distance * self.maxPoint; self.moveToPoint(self.currentPoint); }, hasNext: function() { var self = this; return self.currentPoint < self.maxPoint; }, hasPrev: function() { var self = this; return self.currentPoint > 0; }, toNext: function() { var self = this; if (!self.hasNext()) { return; } self.moveToPoint(self.currentPoint + 1); }, toPrev: function() { var self = this; if (!self.hasPrev()) { return; } self.moveToPoint(self.currentPoint - 1); }, moveToPoint: function(point) { var self = this; self.currentPoint = (point < 0) ? 0 : (point > self.maxPoint) ? self.maxPoint : parseInt(point); self.element.style.webkitTransitionDuration = '500ms'; self._setXY(- self.currentPoint * self.distance); var ev = document.createEvent('Event'); ev.initEvent('css3flip.moveend', true, false); self.element.dispatchEvent(ev); }, _setXY: function(xy) { var self = this; self.currentXY = xy; if(self.dir=="H") self.element.style.webkitTransform = getTranslateX(xy); else self.element.style.webkitTransform = getTranslateY(xy); }, _touchStart: function(event) { var self = this; if(self._locked) { event.preventDefault(); event.stopPropagation(); } if (!self.touchEnabled) { return; } if (!$support.touch) { event.preventDefault(); } self.element.style.webkitTransitionDuration = '0'; self.scrolling = true; self.moveReady = false; self.startPageX = getPage(event, 'pageX'); self.startPageY = getPage(event, 'pageY'); if(self.dir=="H") self.basePage = self.startPageX; else self.basePage = self.startPageY self.direction = 0; self.startTime = event.timeStamp; }, _touchMove: function(event) { var self = this; if(self._locked) { event.preventDefault(); event.stopPropagation(); } if (!self.scrolling) { return; } var pageX = getPage(event, 'pageX'), pageY = getPage(event, 'pageY'), distXY, newXY, deltaX, deltaY; if (!self.moveReady) { deltaX = Math.abs(pageX - self.startPageX); deltaY = Math.abs(pageY - self.startPageY); if(self.dir=="H"){ if (deltaX>deltaY && deltaX > 5) { //event.preventDefault(); //event.stopPropagation(); self.moveReady = true; self.element.parentNode.addEventListener('click', self, true); } else if (deltaY > 5) { self.scrolling = false; } }else{ if (deltaY>deltaX && deltaY> 5) { //event.preventDefault(); //event.stopPropagation(); self.moveReady = true; self.element.parentNode.addEventListener('click', self, true); } else if (deltaX > 5) { self.scrolling = false; } } } if (self.moveReady) { //event.preventDefault(); //event.stopPropagation(); if(self.dir=="H") distXY = pageX - self.basePage; else distXY = pageY - self.basePage; newXY = self.currentXY + distXY; if (newXY >= 0 || newXY < self.maxXY) { newXY = Math.round(self.currentXY + distXY / 3); } self._setXY(newXY); self.direction = distXY > 0 ? -1 : 1; } if(self.dir=="H") self.basePage = pageX; else self.basePage = pageY; }, _touchEnd: function(event) { var self = this; if(self._locked) { event.preventDefault(); event.stopPropagation(); } if (!self.scrolling) { return; } self.scrolling = false; var newPoint = -self.currentXY / self.distance; newPoint = (self.direction > 0) ? Math.ceil(newPoint) : (self.direction < 0) ? Math.floor(newPoint) : Math.round(newPoint); self.moveToPoint(newPoint); setTimeout(function() { self.element.parentNode.removeEventListener('click', self, true); }, 200); if(self.endFun) self.endFun(); }, _click: function(event) { var self = this; event.stopPropagation(); event.preventDefault(); }, destroy: function() { var self = this; self.element.parentNode.removeEventListener($E.start, self); self.element.parentNode.removeEventListener($E.move, self); self.element.removeEventListener($E.transEnd, self); document.removeEventListener($E.end, self); } }
JavaScript
function PLAYER_LIST_Command(data) { if (ig.game != null) { ig.game.updateUserList(data); } }; function GAME_START_Command(data){ console.log(data); if (ig.game != null) { ig.game.startPoker(data); } }; function WAIT_Command(){ if(ig.game != null){ ig.game.wait(); } }; function WAIT_OTHER_Command(){ if(ig.game != null){ ig.game.waitOther(); } }; function HIT_Command (data){ if(ig.game != null){ ig.game.hit(data); } }; function GAME_END_Command(data){ if(ig.game != null){ ig.game.endGame(data); } }; function RESTART_Command(data){ if(ig.game != null){ ig.game.resetGame(data); } }; function ERROR_Command(data) { alert(data); };
JavaScript
var global_host_id = 1; var Host = function(ip,port){ var that = this; window.WebSocket = window.WebSocket || window.MozWebSocket; var isWebSocket = !(!window.WebSocket); //var isWebSocket = false; if(ip == undefined) //ip = "127.0.0.1"; ip = "202.59.152.227"; if(port == undefined) port = isWebSocket ? "14503" : "12012"; var last_connect_date = new Date(); var can_send = false; var is_connecting = true; var id = global_host_id + ""; var first_com = true; global_host_id++; that.send = function(msg){ if (isWebSocket) { if(can_send) { try { if (socket != null) { socket.send(msg); } } catch (exception) { alert(exception); } } } else { if (!can_send && !first_com) { setTimeout("send('" + msg + "')", 100); return; } uexSocketMgr.sendData(id, msg + "\r\n"); } }; that.command = function(com, data){ if (data == undefined) that.send(com); else that.send(com + " " + data); }; that.disconnect = function(){ if(isWebSocket) { try { if(socket != null) { socket.close(); } } catch (exception) { alert(exception); } } else uexSocketMgr.closeSocket(id); }; var socket; if (isWebSocket) { var host = "ws://" + ip + ":" + port + "/"; socket = new WebSocket(host); socket.onopen = function () { can_send = true; }; socket.onmessage = function (msg) { var list = msg.data.split(" "); var com = list[0]; var data = msg.data.substring(com.length).trim(); try { var json_data = eval("(" + data + ")"); eval(com + "_Command(json_data)"); } catch (exception) { eval(com + "_Command(data)"); } }; //socket.onclose = onclose; //socket.onerror = onerror; } else { uexSocketMgr.createTCPSocket(id); uexSocketMgr.setInetAddressAndPort(id, ip, port); uexSocketMgr.cbSendData = function(opId, dataType, data){ if (first_com) { if (data == 0) { can_send = true; } else { alert("连接服务器失败!"); } } else { if (data == 1) { alert("发送指令失败!"); } } }; uexSocketMgr.onData = function(opId, msg){ var command_list = msg.split("\r\n"); for (var i = 0; i < command_list.length; i++) { var temp = command_list[i]; if (temp == "") break; if (temp.indexOf("{") == 0) temp = temp.substring(temp.indexOf("}") + 1); var list = temp.split(" "); var com = list[0]; var data = temp.substring(com.length).trim(); try { var json_data = eval("(" + data + ")"); eval(com + "_Command(json_data,that)"); } catch (exception) { eval(com + "_Command(data,that)"); } } }; that.command("Test"); } }; Host.prototype = {}; window.Host = Host; String.prototype.trim = function () { var str = this.replace(/^(\s|\u00A0)+/, ''); for (var i = str.length - 1; i >= 0; i--) { if (/\S/.test(str.charAt(i))) { str = str.substring(0, i + 1); break; } } return str; }
JavaScript
ig.module('game.main').requires('plugins.plugin', 'impact.game', 'plugins.tween', 'plugins.text', 'game.entities.button', 'game.entities.chair', 'game.entities.card'//, 'impact.debug.debug' ).defines(function(){ MyGame = ig.Game.extend({ chairs: null, host: null, background: new ig.Image('media/bg.jpg'), table: new ig.Image('media/table.png'), // Load a font //font: new ig.Font('media/04b03.font.png'), dealing: null, dealList: null, cardList: null, tipText: null, pointText: null, startButton: null, hitButton: null, standButton: null, resetButton:null, init: function(){ this.host = new Host(); ig.input.bind(ig.KEY.MOUSE1, 'click'); // Initialize your game here; bind keys etc. this.chairs = new Array(); this.chairs.push(this.spawnEntity(Chair, 30, 16, { type: Chair.LEFT_TOP, seat: 1 })); this.chairs.push(this.spawnEntity(Chair, 30, 580, { type: Chair.LEFT_BOTTOM, seat: 2 })); this.chairs.push(this.spawnEntity(Chair, 830, 16, { type: Chair.RIGHT_TOP, seat: 3 })); this.chairs.push(this.spawnEntity(Chair, 830, 580, { type: Chair.RIGHT_BOTTOM, seat: 4 })); this.tipText = new ig.Text('', 'white', "bold 1em Verdana"); this.tipText.baseLine = "middle"; this.tipText.align = "left"; this.pointText = new ig.Text('', 'white', "bold 1em Verdana"); this.pointText.baseLine = "middle"; this.pointText.align = "left"; this.resetButton = this.spawnEntity(Button,1024-220,808,{ text:"重启游戏", click:function(){ ig.game.host.command('RESTART'); }, enabled:true }); this.startButton = this.spawnEntity(Button, 1024 - 220, 748, { text: "开始", click: function(){ ig.game.host.command('START'); }, enabled: false }); this.hitButton = this.spawnEntity(Button, 1024 - 220 * 2, 748, { text: "拿牌", click: function(){ ig.game.host.command("HIT"); }, enabled: false }); this.standButton = this.spawnEntity(Button, 1024 - 220 * 2, 808, { text: "停牌", click: function(){ ig.game.host.command("STAND"); }, enabled: false }); }, update: function(){ // Update all entities and backgroundMaps this.parent(); for (var i = 0; i < ig.Tween.tweens.length; i++) ig.Tween.tweens[i].update(); // Add your own, additional update code here var temp = false; for (var i = 0; i < this.entities.length; i++) { if (this.entities[i].isMouseEnter) temp = true; } if (temp) document.body.style.cursor = 'pointer'; else document.body.style.cursor = 'default'; }, draw: function(){ // Draw all entities and backgroundMaps //this.parent(); // Add your own drawing code here this.background.draw(0, 0); this.table.draw(0, 0); this.drawEntities(); this.tipText.draw(30, 848); this.pointText.draw(30, 788); }, updateUserList: function(data){ for (var dataIndex = 0; dataIndex < data.list.length; dataIndex++) { for (var chairIndex = 0; chairIndex < this.chairs.length; chairIndex++) { if (data.list[dataIndex].Seat == this.chairs[chairIndex].seat) { this.chairs[chairIndex].enabled = false; this.chairs[chairIndex].player = data.list[dataIndex]; } if (data.list[dataIndex].IsSelf) { this.startButton.enabled = !data.list[dataIndex].IsStart; } } } }, starting: false, startPoker: function(data){ console.log("---------Start Game---------"); console.log(data); console.log("---------Start Game---------"); if (this.starting) return; else this.starting = true; this.cardList = new Array(); for (var i = 0; i < 52; i++) { var tmp = (i / 10) * 2; this.cardList.push(this.spawnEntity(Card, (ig.system.width / 2 - 107.3 / 2) - tmp, (ig.system.height / 2 - 160 / 2) - tmp)); } for (var i = 0; i < this.chairs.length; i++) { this.chairs[i].enabled = false; } this.dealList = data.info.DealList; if (this.dealList != null && this.dealList.length > 0) { this.dealPoker(0, function(){ ig.game.host.command("START_COMPLETE"); }); } }, dealCardPoss: [{ seat: 1, pos: { x: 200, y: 160 } }, { seat: 2, pos: { x: 200, y: 440 } }, { seat: 3, pos: { x: 620, y: 160 } }, { seat: 4, pos: { x: 620, y: 440 } }], currentDealPokerIndex: 0, dealPoker: function(index, dealPokerCompleted){ this.currentDealPokerIndex = index; var deal = this.dealList[index]; for (var ci = 0; ci < this.chairs.length; ci++) { var chair = this.chairs[ci]; if (chair.seat == deal.Seat) { var dealCardPos = this.dealCardPoss[chair.seat - 1]; var pos = { x: dealCardPos.pos.x + (chair.cardDataList.length * 30), y: dealCardPos.pos.y }; var card = this.cardList.pop(); chair.addCard({ dealCard: deal.Card, pos: pos, card: card }, function(){ if (ig.game.currentDealPokerIndex == ig.game.dealList.length - 1) dealPokerCompleted(); else ig.game.dealPoker(ig.game.currentDealPokerIndex + 1, dealPokerCompleted); }); card.zIndex += index; ig.game.sortEntities(); } } }, wait: function(){ this.tipText.text = "请选择"; this.hitButton.enabled = this.standButton.enabled = true; }, waitOther: function(){ this.tipText.text = "等待其他玩家决策"; this.hitButton.enabled = this.standButton.enabled = false; }, hit: function(data){ console.log("---------Hit---------"); console.log(data); console.log("---------Hit---------"); if (data.result.IsExplode) this.pointText.text = "爆了!"; else this.pointText.text = data.result.Point + " 点"; this.currentDealPokerIndex++; for (var ci = 0; ci < this.chairs.length; ci++) { var chair = this.chairs[ci]; if (chair.seat == data.result.Seat) { var dealCardPos = this.dealCardPoss[chair.seat - 1]; var pos = { x: dealCardPos.pos.x + (chair.cardDataList.length * 30), y: dealCardPos.pos.y }; var card = this.cardList.pop(); chair.addCard({ dealCard: data.result.Card, pos: pos, card: card }, function(){ }); card.zIndex += this.currentDealPokerIndex; ig.game.sortEntities(); } } }, endGame: function(data){ console.log("---------End Game---------"); console.log(data); console.log("---------End Game---------"); this.tipText.text = ''; this.pointText.text = '游戏结束'; setTimeout(function(){ ig.system.setGame(MyGame); }, 3000); }, resetGame:function(data){ ig.system.setGame(MyGame); } }); // Start the Game with 60fps, a resolution of 320x240, scaled // up by a factor of 2 window.onunload = function(){ }; var game_width = 1024; var game_height = 868; var game_scale = 0.75; var game_fps = 50; if (ig.ua.mobile) { game_fps = 30; } game_scale = Math.min(($('#container').width() / game_width), ($('#container').height() / game_height)); $(document).ready(function(){ ig.main('#canvas', MyGame, game_fps, game_width, game_height, game_scale, ig.ImpactSplashLoader); }); });
JavaScript
ig.module('game.entities.button').requires('impact.entity').defines(function(){ Button = ig.Entity.extend({ size: { x: 210, y: 60 }, isMouseEnter: false, enabled: true, visible:true, click: undefined, text: undefined, animSheet: new ig.AnimationSheet('media/button.png', 210, 60), init: function(x, y, settings){ this.parent(x, y, settings); this.addAnim('idle', 0.1, [0]); this.addAnim('hover', 0.1, [1]); this.click = settings.click; this.text = new ig.Text(settings.text,"#ffffff","bold 1em Verdana"); this.text.baseLine = "middle"; this.text.align = "center"; }, update: function(){ if (this.enabled && this.visible) { if ((ig.input.mouse.x > this.pos.x && ig.input.mouse.x < this.pos.x + this.size.x) && (ig.input.mouse.y > this.pos.y && ig.input.mouse.y < this.pos.y + this.size.y)) { if (!this.isMouseEnter) { this.isMouseEnter = true; this.mouseenter(); } } else { if (this.isMouseEnter) { this.isMouseEnter = false; this.mouseout(); } } if (ig.input.released('click') && this.isMouseEnter) { this.mouseclick(); } } else { if (this.isMouseEnter) { this.isMouseEnter = false; this.mouseout(); } } }, draw: function(){ if(!this.visible){ return; } this.parent(); this.text.draw(this.pos.x + this.size.x / 2, this.pos.y + this.size.y / 2, 200); }, mouseenter: function(){ this.currentAnim = this.anims.hover.rewind(); }, mouseout: function(){ this.currentAnim = this.anims.idle.rewind(); }, mouseclick: function(){ this.click(); } }); });
JavaScript
ig.module('game.entities.chair').requires('impact.entity').defines(function(){ Chair = ig.Entity.extend({ size: { x: 165, y: 165 }, isMouseEnter: false, seat: 0, player: null, enabled: true, cardDataList: null, animSheet: new ig.AnimationSheet('media/chair.png', 165, 165), init: function(x, y, settings){ this.parent(x, y, settings); switch (settings.type) { case Chair.LEFT_TOP: this.addAnim('idle', 0, [4]); this.addAnim('hover', 0, [0]); break; case Chair.LEFT_BOTTOM: this.addAnim('idle', 0, [7]); this.addAnim('hover', 0, [3]); break; case Chair.RIGHT_TOP: this.addAnim('idle', 0, [5]); this.addAnim('hover', 0, [1]); break; case Chair.RIGHT_BOTTOM: this.addAnim('idle', 0, [6]); this.addAnim('hover', 0, [2]); break; } this.seat = settings.seat; this.cardDataList = new Array(); }, update: function(){ if (this.enabled) { if ((ig.input.mouse.x > this.pos.x && ig.input.mouse.x < this.pos.x + this.size.x) && (ig.input.mouse.y > this.pos.y && ig.input.mouse.y < this.pos.y + this.size.y)) { if (!this.isMouseEnter) { this.isMouseEnter = true; } } else { if (this.isMouseEnter) { this.isMouseEnter = false; } } if (ig.input.released('click') && this.isMouseEnter) { this.mouseclick(); } } else { if (this.isMouseEnter) { this.isMouseEnter = false; } this.mouseenter(); } }, draw: function(){ this.parent(); }, mouseenter: function(){ this.currentAnim = this.anims.hover.rewind(); }, mouseout: function(){ this.currentAnim = this.anims.idle.rewind(); }, mouseclick: function(){ ig.game.host.command("JOIN", this.seat); }, addCard: function(cardData, completed){ this.cardDataList.push(cardData); new ig.Tween(cardData.card, { pos: { x: cardData.pos.x, y: cardData.pos.y } }, 0.25, function(){ if (cardData.dealCard != null) cardData.card.setData(cardData.dealCard.Number, cardData.dealCard.Type); completed(); }); } }); Chair.LEFT_TOP = 'left-top'; Chair.LEFT_BOTTOM = 'left-bottom'; Chair.RIGHT_TOP = 'right-top'; Chair.RIGHT_BOTTOM = 'right-bottom'; });
JavaScript
ig.module('game.entities.card').requires('impact.entity').defines(function(){ Card = ig.Entity.extend({ size: { x: 107.3, y: 160 }, cardType: undefined, cardNr: undefined, animSheet: new ig.AnimationSheet('media/card.png', 107.3, 160), init: function(x, y, settings){ this.parent(x, y, settings); this.addAnim('idle', 0, [54]); }, update: function(){ }, draw: function(){ this.parent(); }, setData: function(nr, type){ this.cardNr = nr; this.cardType = type; var tmp = 0; switch (this.cardType) { case 1: tmp = 0 + this.cardNr -1; break; case 2: tmp = 26 + this.cardNr -1; break; case 3: tmp = 13 + this.cardNr -1; break; case 4: tmp = 39 + this.cardNr -1; break; } this.addAnim('open', 0.1, [tmp]); this.currentAnim = this.anims.open.rewind(); } }); });
JavaScript
ig.module('plugins.tween').defines(function(){ "use strict"; /* Tween ------Create------ var entityTween = new ig.Tween(this.entity,{x:300,y:300},0.3); ------Use------ in game -> update:function(){ this.parent(); for(var i=0;i<ig.Tween.tweens.length;i++){ ig.Tween.tweens[i].update(); } } */ ig.Tween = ig.Class.extend({ target: undefined, duration: 0.3, props: undefined, lastUpdateTime: undefined, startTime: undefined, endTime: undefined, completed: undefined, init: function(target, props, duration, completed){ this.target = target; this.props = props; this.duration = duration * 1000; this.completed = completed || function(){ }; ig.Tween.tweens.push(this); }, update: function(){ if (!this.startTime) { this.startTime = new Date(); this.endTime = new Date().setMilliseconds(this.startTime.getMilliseconds() + this.duration); this.lastUpdateTime = this.startTime; } //剩余多少时间完成任务 var se_trace = this.endTime - this.lastUpdateTime; //上次任务与今次任务之间相隔的时间 var nl_trace = new Date() - this.lastUpdateTime; //按照上次任务与今次任务之间相隔的时间计算出有多少次任务需要执行 var trace_step = se_trace / nl_trace; if (nl_trace == 0) { return; } else { if (trace_step <= 0) { this._setPropValuesToTarget(this.props, this.target, trace_step); //强制完成任务 this._completed(); return; } else { //执行任务 this._setPropValues(this.props, this.target, trace_step); } } this.lastUpdateTime = new Date(); }, _setPropValuesToTarget: function(props, target, trace_step){ for (var prop in props) { if (typeof(props[prop]) == 'object') { for (var subProp in props[prop]) { target[prop][subProp] = props[prop][subProp]; } } else { target[prop] = props[prop]; } } }, _setPropValues: function(props, target, trace_step){ for (var prop in props) { if (typeof(props[prop]) == 'object') { for (var subProp in props[prop]) { this._setPropValue(props[prop], target[prop], subProp, trace_step); } } else { this._setPropValue(props, target, prop, trace_step); } } }, _setPropValue: function(props, target, prop, trace_step){ var target_value = props[prop]; var source_value = target[prop]; var trace_value = target_value - source_value; var each_step_value = Math.floor(trace_value / trace_step); if (trace_value > 0) { if (source_value + each_step_value > target_value) target[prop] = source_value; else target[prop] = source_value + each_step_value; } else { if (source_value + each_step_value < target_value) target[prop] = source_value; else target[prop] = source_value + each_step_value; } }, _completed: function(){ ig.Tween.tweens.erase(this); this.completed(); } }); ig.Tween.tweens = new Array(); });
JavaScript
ig.module('plugins.plugin').requires('impact.system').defines(function(){ "use strict"; /*2012/8/23 Vinson 改进Math.floor,增快速度*/ window.Math.floor = function(tmp){ return tmp >> 0; }; });
JavaScript
ig.module('plugins.text').requires('impact.system').defines(function(){ "use strict"; /* Text ------Create------ var text = new ig.Text('this is a text.'); var text = new ig.Text('this is a text.','#ffffff'); var text = new ig.Text('this is a text.','#ffffff','1.5em Verdana','center'); ------Use------ draw:function(){ this.text.draw(100,100); } draw:function(){ this.parent(); this.text.draw(100,100,300);//max width 300 } */ ig.Text = ig.Class.extend({ text: undefined, color: 'black', font: '1em Verdana', baseLine: 'top', align: 'left', init: function(text, color, font, align){ this.text = text || ''; this.color= color || this.color; this.font = font || this.font; this.align= align || this.align; }, draw: function(x, y, maxWidth){ if (!this.text) { return; } ig.system.context.fillStyle = this.color; ig.system.context.font = this.font; ig.system.context.textAlign = this.align; ig.system.context.textBaseline = this.baseLine; if (maxWidth) ig.system.context.fillText(this.text, ig.system.getDrawPos(x), ig.system.getDrawPos(y), maxWidth); else ig.system.context.fillText(this.text, ig.system.getDrawPos(x), ig.system.getDrawPos(y)); } }); });
JavaScript
ig.module( 'impact.input' ) .defines(function(){ "use strict"; ig.KEY = { 'MOUSE1': -1, 'MOUSE2': -3, 'MWHEEL_UP': -4, 'MWHEEL_DOWN': -5, 'BACKSPACE': 8, 'TAB': 9, 'ENTER': 13, 'PAUSE': 19, 'CAPS': 20, 'ESC': 27, 'SPACE': 32, 'PAGE_UP': 33, 'PAGE_DOWN': 34, 'END': 35, 'HOME': 36, 'LEFT_ARROW': 37, 'UP_ARROW': 38, 'RIGHT_ARROW': 39, 'DOWN_ARROW': 40, 'INSERT': 45, 'DELETE': 46, '_0': 48, '_1': 49, '_2': 50, '_3': 51, '_4': 52, '_5': 53, '_6': 54, '_7': 55, '_8': 56, '_9': 57, 'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72, 'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78, 'O': 79, 'P': 80, 'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85, 'V': 86, 'W': 87, 'X': 88, 'Y': 89, 'Z': 90, 'NUMPAD_0': 96, 'NUMPAD_1': 97, 'NUMPAD_2': 98, 'NUMPAD_3': 99, 'NUMPAD_4': 100, 'NUMPAD_5': 101, 'NUMPAD_6': 102, 'NUMPAD_7': 103, 'NUMPAD_8': 104, 'NUMPAD_9': 105, 'MULTIPLY': 106, 'ADD': 107, 'SUBSTRACT': 109, 'DECIMAL': 110, 'DIVIDE': 111, 'F1': 112, 'F2': 113, 'F3': 114, 'F4': 115, 'F5': 116, 'F6': 117, 'F7': 118, 'F8': 119, 'F9': 120, 'F10': 121, 'F11': 122, 'F12': 123, 'SHIFT': 16, 'CTRL': 17, 'ALT': 18, 'PLUS': 187, 'COMMA': 188, 'MINUS': 189, 'PERIOD': 190 }; ig.Input = ig.Class.extend({ bindings: {}, actions: {}, presses: {}, locks: {}, delayedKeyup: {}, isUsingMouse: false, isUsingKeyboard: false, isUsingAccelerometer: false, mouse: {x: 0, y: 0}, accel: {x: 0, y: 0, z: 0}, initMouse: function() { if( this.isUsingMouse ) { return; } this.isUsingMouse = true; var mouseWheelBound = this.mousewheel.bind(this); ig.system.canvas.addEventListener('mousewheel', mouseWheelBound, false ); ig.system.canvas.addEventListener('DOMMouseScroll', mouseWheelBound, false ); ig.system.canvas.addEventListener('contextmenu', this.contextmenu.bind(this), false ); ig.system.canvas.addEventListener('mousedown', this.keydown.bind(this), false ); ig.system.canvas.addEventListener('mouseup', this.keyup.bind(this), false ); ig.system.canvas.addEventListener('mousemove', this.mousemove.bind(this), false ); ig.system.canvas.addEventListener('touchstart', this.keydown.bind(this), false ); ig.system.canvas.addEventListener('touchend', this.keyup.bind(this), false ); ig.system.canvas.addEventListener('touchmove', this.mousemove.bind(this), false ); }, initKeyboard: function() { if( this.isUsingKeyboard ) { return; } this.isUsingKeyboard = true; window.addEventListener('keydown', this.keydown.bind(this), false ); window.addEventListener('keyup', this.keyup.bind(this), false ); }, initAccelerometer: function() { if( this.isUsingAccelerometer ) { return; } window.addEventListener('devicemotion', this.devicemotion.bind(this), false ); }, mousewheel: function( event ) { var delta = event.wheelDelta ? event.wheelDelta : (event.detail * -1); var code = delta > 0 ? ig.KEY.MWHEEL_UP : ig.KEY.MWHEEL_DOWN; var action = this.bindings[code]; if( action ) { this.actions[action] = true; this.presses[action] = true; this.delayedKeyup[action] = true; event.stopPropagation(); event.preventDefault(); } }, mousemove: function( event ) { var el = ig.system.canvas; var pos = {left: 0, top: 0}; while( el != null ) { pos.left += el.offsetLeft; pos.top += el.offsetTop; el = el.offsetParent; } var tx = event.pageX; var ty = event.pageY; if( event.touches ) { tx = event.touches[0].clientX; ty = event.touches[0].clientY; } this.mouse.x = (tx - pos.left) / ig.system.scale; this.mouse.y = (ty - pos.top) / ig.system.scale; }, contextmenu: function( event ) { if( this.bindings[ig.KEY.MOUSE2] ) { event.stopPropagation(); event.preventDefault(); } }, keydown: function( event ) { if( event.target.type == 'text' ) { return; } var code = event.type == 'keydown' ? event.keyCode : (event.button == 2 ? ig.KEY.MOUSE2 : ig.KEY.MOUSE1); if( event.type == 'touchstart' || event.type == 'mousedown' ) { this.mousemove( event ); } var action = this.bindings[code]; if( action ) { this.actions[action] = true; if( !this.locks[action] ) { this.presses[action] = true; this.locks[action] = true; } event.stopPropagation(); event.preventDefault(); } }, keyup: function( event ) { if( event.target.type == 'text' ) { return; } var code = event.type == 'keyup' ? event.keyCode : (event.button == 2 ? ig.KEY.MOUSE2 : ig.KEY.MOUSE1); var action = this.bindings[code]; if( action ) { this.delayedKeyup[action] = true; event.stopPropagation(); event.preventDefault(); } }, devicemotion: function( event ) { this.accel = event.accelerationIncludingGravity; }, bind: function( key, action ) { if( key < 0 ) { this.initMouse(); } else if( key > 0 ) { this.initKeyboard(); } this.bindings[key] = action; }, bindTouch: function( selector, action ) { var element = ig.$( selector ); var that = this; element.addEventListener('touchstart', function(ev) { that.touchStart( ev, action ); }, false); element.addEventListener('touchend', function(ev) { that.touchEnd( ev, action ); }, false); }, unbind: function( key ) { var action = this.bindings[key]; this.delayedKeyup[action] = true; this.bindings[key] = null; }, unbindAll: function() { this.bindings = {}; this.actions = {}; this.presses = {}; this.locks = {}; this.delayedKeyup = {}; }, state: function( action ) { return this.actions[action]; }, pressed: function( action ) { return this.presses[action]; }, released: function( action ) { return this.delayedKeyup[action]; }, clearPressed: function() { for( var action in this.delayedKeyup ) { this.actions[action] = false; this.locks[action] = false; } this.delayedKeyup = {}; this.presses = {}; }, touchStart: function( event, action ) { this.actions[action] = true; this.presses[action] = true; event.stopPropagation(); event.preventDefault(); return false; }, touchEnd: function( event, action ) { this.delayedKeyup[action] = true; event.stopPropagation(); event.preventDefault(); return false; } }); });
JavaScript
ig.module( 'impact.entity' ) .requires( 'impact.animation', 'impact.impact' ) .defines(function(){ "use strict"; ig.Entity = ig.Class.extend({ id: 0, settings: {}, size: {x: 16, y:16}, offset: {x: 0, y: 0}, pos: {x: 0, y:0}, last: {x: 0, y:0}, vel: {x: 0, y: 0}, accel: {x: 0, y: 0}, friction: {x: 0, y: 0}, maxVel: {x: 100, y: 100}, zIndex: 0, gravityFactor: 1, standing: false, bounciness: 0, minBounceVelocity: 40, anims: {}, animSheet: null, currentAnim: null, health: 10, type: 0, // TYPE.NONE checkAgainst: 0, // TYPE.NONE collides: 0, // COLLIDES.NEVER _killed: false, slopeStanding: {min: (44).toRad(), max: (136).toRad() }, init: function( x, y, settings ) { this.id = ++ig.Entity._lastId; this.pos.x = x; this.pos.y = y; ig.merge( this, settings ); }, addAnim: function( name, frameTime, sequence, stop ) { if( !this.animSheet ) { throw( 'No animSheet to add the animation '+name+' to.' ); } var a = new ig.Animation( this.animSheet, frameTime, sequence, stop ); this.anims[name] = a; if( !this.currentAnim ) { this.currentAnim = a; } return a; }, update: function() { this.last.x = this.pos.x; this.last.y = this.pos.y; this.vel.y += ig.game.gravity * ig.system.tick * this.gravityFactor; this.vel.x = this.getNewVelocity( this.vel.x, this.accel.x, this.friction.x, this.maxVel.x ); this.vel.y = this.getNewVelocity( this.vel.y, this.accel.y, this.friction.y, this.maxVel.y ); // movement & collision var mx = this.vel.x * ig.system.tick; var my = this.vel.y * ig.system.tick; var res = ig.game.collisionMap.trace( this.pos.x, this.pos.y, mx, my, this.size.x, this.size.y ); this.handleMovementTrace( res ); if( this.currentAnim ) { this.currentAnim.update(); } }, getNewVelocity: function( vel, accel, friction, max ) { if( accel ) { return ( vel + accel * ig.system.tick ).limit( -max, max ); } else if( friction ) { var delta = friction * ig.system.tick; if( vel - delta > 0) { return vel - delta; } else if( vel + delta < 0 ) { return vel + delta; } else { return 0; } } return vel.limit( -max, max ); }, handleMovementTrace: function( res ) { this.standing = false; if( res.collision.y ) { if( this.bounciness > 0 && Math.abs(this.vel.y) > this.minBounceVelocity ) { this.vel.y *= -this.bounciness; } else { if( this.vel.y > 0 ) { this.standing = true; } this.vel.y = 0; } } if( res.collision.x ) { if( this.bounciness > 0 && Math.abs(this.vel.x) > this.minBounceVelocity ) { this.vel.x *= -this.bounciness; } else { this.vel.x = 0; } } if( res.collision.slope ) { var s = res.collision.slope; if( this.bounciness > 0 ) { var proj = this.vel.x * s.nx + this.vel.y * s.ny; this.vel.x = (this.vel.x - s.nx * proj * 2) * this.bounciness; this.vel.y = (this.vel.y - s.ny * proj * 2) * this.bounciness; } else { var lengthSquared = s.x * s.x + s.y * s.y; var dot = (this.vel.x * s.x + this.vel.y * s.y)/lengthSquared; this.vel.x = s.x * dot; this.vel.y = s.y * dot; var angle = Math.atan2( s.x, s.y ); if( angle > this.slopeStanding.min && angle < this.slopeStanding.max ) { this.standing = true; } } } this.pos = res.pos; }, draw: function() { if( this.currentAnim ) { this.currentAnim.draw( this.pos.x - this.offset.x - ig.game._rscreen.x, this.pos.y - this.offset.y - ig.game._rscreen.y ); } }, kill: function() { ig.game.removeEntity( this ); }, receiveDamage: function( amount, from ) { this.health -= amount; if( this.health <= 0 ) { this.kill(); } }, touches: function( other ) { return !( this.pos.x >= other.pos.x + other.size.x || this.pos.x + this.size.x <= other.pos.x || this.pos.y >= other.pos.y + other.size.y || this.pos.y + this.size.y <= other.pos.y ); }, distanceTo: function( other ) { var xd = (this.pos.x + this.size.x/2) - (other.pos.x + other.size.x/2); var yd = (this.pos.y + this.size.y/2) - (other.pos.y + other.size.y/2); return Math.sqrt( xd*xd + yd*yd ); }, angleTo: function( other ) { return Math.atan2( (other.pos.y + other.size.y/2) - (this.pos.y + this.size.y/2), (other.pos.x + other.size.x/2) - (this.pos.x + this.size.x/2) ); }, check: function( other ) {}, collideWith: function( other, axis ) {}, ready: function() {} }); // Last used entity id; incremented with each spawned entity ig.Entity._lastId = 0; // Collision Types - Determine if and how entities collide with each other // In ACTIVE vs. LITE or FIXED vs. ANY collisions, only the "weak" entity moves, // while the other one stays fixed. In ACTIVE vs. ACTIVE and ACTIVE vs. PASSIVE // collisions, both entities are moved. LITE or PASSIVE entities don't collide // with other LITE or PASSIVE entities at all. The behaiviour for FIXED vs. // FIXED collisions is undefined. ig.Entity.COLLIDES = { NEVER: 0, LITE: 1, PASSIVE: 2, ACTIVE: 4, FIXED: 8 }; // Entity Types - used for checks ig.Entity.TYPE = { NONE: 0, A: 1, B: 2, BOTH: 3 }; ig.Entity.checkPair = function( a, b ) { // Do these entities want checks? if( a.checkAgainst & b.type ) { a.check( b ); } if( b.checkAgainst & a.type ) { b.check( a ); } // If this pair allows collision, solve it! At least one entity must // collide ACTIVE or FIXED, while the other one must not collide NEVER. if( a.collides && b.collides && a.collides + b.collides > ig.Entity.COLLIDES.ACTIVE ) { ig.Entity.solveCollision( a, b ); } }; ig.Entity.solveCollision = function( a, b ) { // If one entity is FIXED, or the other entity is LITE, the weak // (FIXED/NON-LITE) entity won't move in collision response var weak = null; if( a.collides == ig.Entity.COLLIDES.LITE || b.collides == ig.Entity.COLLIDES.FIXED ) { weak = a; } else if( b.collides == ig.Entity.COLLIDES.LITE || a.collides == ig.Entity.COLLIDES.FIXED ) { weak = b; } // Did they already overlap on the X-axis in the last frame? If so, // this must be a vertical collision! if( a.last.x + a.size.x > b.last.x && a.last.x < b.last.x + b.size.x ) { // Which one is on top? if( a.last.y < b.last.y ) { ig.Entity.seperateOnYAxis( a, b, weak ); } else { ig.Entity.seperateOnYAxis( b, a, weak ); } a.collideWith( b, 'y' ); b.collideWith( a, 'y' ); } // Horizontal collision else if( a.last.y + a.size.y > b.last.y && a.last.y < b.last.y + b.size.y ){ // Which one is on the left? if( a.last.x < b.last.x ) { ig.Entity.seperateOnXAxis( a, b, weak ); } else { ig.Entity.seperateOnXAxis( b, a, weak ); } a.collideWith( b, 'x' ); b.collideWith( a, 'x' ); } }; // FIXME: This is a mess. Instead of doing all the movements here, the entities // should get notified of the collision (with all details) and resolve it // themselfs. ig.Entity.seperateOnXAxis = function( left, right, weak ) { var nudge = (left.pos.x + left.size.x - right.pos.x); // We have a weak entity, so just move this one if( weak ) { var strong = left === weak ? right : left; weak.vel.x = -weak.vel.x * weak.bounciness + strong.vel.x; var resWeak = ig.game.collisionMap.trace( weak.pos.x, weak.pos.y, weak == left ? -nudge : nudge, 0, weak.size.x, weak.size.y ); weak.pos.x = resWeak.pos.x; } // Normal collision - both move else { var v2 = (left.vel.x - right.vel.x)/2; left.vel.x = -v2; right.vel.x = v2; var resLeft = ig.game.collisionMap.trace( left.pos.x, left.pos.y, -nudge/2, 0, left.size.x, left.size.y ); left.pos.x = Math.floor(resLeft.pos.x); var resRight = ig.game.collisionMap.trace( right.pos.x, right.pos.y, nudge/2, 0, right.size.x, right.size.y ); right.pos.x = Math.ceil(resRight.pos.x); } }; ig.Entity.seperateOnYAxis = function( top, bottom, weak ) { var nudge = (top.pos.y + top.size.y - bottom.pos.y); // We have a weak entity, so just move this one if( weak ) { var strong = top === weak ? bottom : top; weak.vel.y = -weak.vel.y * weak.bounciness + strong.vel.y; // Riding on a platform? var nudgeX = 0; if( weak == top && Math.abs(weak.vel.y - strong.vel.y) < weak.minBounceVelocity ) { weak.standing = true; nudgeX = strong.vel.x * ig.system.tick; } var resWeak = ig.game.collisionMap.trace( weak.pos.x, weak.pos.y, nudgeX, weak == top ? -nudge : nudge, weak.size.x, weak.size.y ); weak.pos.y = resWeak.pos.y; weak.pos.x = resWeak.pos.x; } // Bottom entity is standing - just bounce the top one else if( ig.game.gravity && (bottom.standing || top.vel.y > 0) ) { var resTop = ig.game.collisionMap.trace( top.pos.x, top.pos.y, 0, -(top.pos.y + top.size.y - bottom.pos.y), top.size.x, top.size.y ); top.pos.y = resTop.pos.y; if( top.bounciness > 0 && top.vel.y > top.minBounceVelocity ) { top.vel.y *= -top.bounciness; } else { top.standing = true; top.vel.y = 0; } } // Normal collision - both move else { var v2 = (top.vel.y - bottom.vel.y)/2; top.vel.y = -v2; bottom.vel.y = v2; var nudgeX = bottom.vel.x * ig.system.tick; var resTop = ig.game.collisionMap.trace( top.pos.x, top.pos.y, nudgeX, -nudge/2, top.size.x, top.size.y ); top.pos.y = resTop.pos.y; var resBottom = ig.game.collisionMap.trace( bottom.pos.x, bottom.pos.y, 0, nudge/2, bottom.size.x, bottom.size.y ); bottom.pos.y = resBottom.pos.y; } }; });
JavaScript
// ----------------------------------------------------------------------------- // Impact Game Engine 1.20 // http://impactjs.com/ // ----------------------------------------------------------------------------- (function(window){ "use strict"; // ----------------------------------------------------------------------------- // Native Object extensions Number.prototype.map = function(istart, istop, ostart, ostop) { return ostart + (ostop - ostart) * ((this - istart) / (istop - istart)); }; Number.prototype.limit = function(min, max) { return Math.min(max, Math.max(min, this)); }; Number.prototype.round = function(precision) { precision = Math.pow(10, precision || 0); return Math.round(this * precision) / precision; }; Number.prototype.floor = function() { return Math.floor(this); }; Number.prototype.ceil = function() { return Math.ceil(this); }; Number.prototype.toInt = function() { return (this | 0); }; Number.prototype.toRad = function() { return (this / 180) * Math.PI; }; Number.prototype.toDeg = function() { return (this * 180) / Math.PI; }; Array.prototype.erase = function(item) { for( var i = this.length; i--; ) { if( this[i] === item ) { this.splice(i, 1); } } return this; }; Array.prototype.random = function() { return this[ Math.floor(Math.random() * this.length) ]; }; Function.prototype.bind = Function.prototype.bind || function(bind) { var self = this; return function(){ var args = Array.prototype.slice.call(arguments); return self.apply(bind || null, args); }; }; // ----------------------------------------------------------------------------- // ig Namespace window.ig = { game: null, debug: null, version: '1.20', global: window, modules: {}, resources: [], ready: false, baked: false, nocache: '', ua: {}, prefix: (window.ImpactPrefix || ''), lib: 'lib/', _current: null, _loadQueue: [], _waitForOnload: 0, $: function( selector ) { return selector.charAt(0) == '#' ? document.getElementById( selector.substr(1) ) : document.getElementsByTagName( selector ); }, $new: function( name ) { return document.createElement( name ); }, copy: function( object ) { if( !object || typeof(object) != 'object' || object instanceof HTMLElement || object instanceof ig.Class ) { return object; } else if( object instanceof Array ) { var c = []; for( var i = 0, l = object.length; i < l; i++) { c[i] = ig.copy(object[i]); } return c; } else { var c = {}; for( var i in object ) { c[i] = ig.copy(object[i]); } return c; } }, merge: function( original, extended ) { for( var key in extended ) { var ext = extended[key]; if( typeof(ext) != 'object' || ext instanceof HTMLElement || ext instanceof ig.Class ) { original[key] = ext; } else { if( !original[key] || typeof(original[key]) != 'object' ) { original[key] = (ext instanceof Array) ? [] : {}; } ig.merge( original[key], ext ); } } return original; }, ksort: function( obj ) { if( !obj || typeof(obj) != 'object' ) { return []; } var keys = [], values = []; for( var i in obj ) { keys.push(i); } keys.sort(); for( var i = 0; i < keys.length; i++ ) { values.push( obj[keys[i]] ); } return values; }, module: function( name ) { if( ig._current ) { throw( "Module '"+ig._current.name+"' defines nothing" ); } if( ig.modules[name] && ig.modules[name].body ) { throw( "Module '"+name+"' is already defined" ); } ig._current = {name: name, requires: [], loaded: false, body: null}; ig.modules[name] = ig._current; ig._loadQueue.push(ig._current); return ig; }, requires: function() { ig._current.requires = Array.prototype.slice.call(arguments); return ig; }, defines: function( body ) { ig._current.body = body; ig._current = null; ig._initDOMReady(); }, addResource: function( resource ) { ig.resources.push( resource ); }, setNocache: function( set ) { ig.nocache = set ? '?' + Date.now() : ''; }, // Stubs for ig.Debug log: function() {}, assert: function( condition, msg ) {}, show: function( name, number ) {}, mark: function( msg, color ) {}, _loadScript: function( name, requiredFrom ) { ig.modules[name] = {name: name, requires:[], loaded: false, body: null}; ig._waitForOnload++; var path = ig.prefix + ig.lib + name.replace(/\./g, '/') + '.js' + ig.nocache; var script = ig.$new('script'); script.type = 'text/javascript'; script.src = path; script.onload = function() { ig._waitForOnload--; ig._execModules(); }; script.onerror = function() { throw( 'Failed to load module '+name+' at ' + path + ' ' + 'required from ' + requiredFrom ); }; ig.$('head')[0].appendChild(script); }, _execModules: function() { var modulesLoaded = false; for( var i = 0; i < ig._loadQueue.length; i++ ) { var m = ig._loadQueue[i]; var dependenciesLoaded = true; for( var j = 0; j < m.requires.length; j++ ) { var name = m.requires[j]; if( !ig.modules[name] ) { dependenciesLoaded = false; ig._loadScript( name, m.name ); } else if( !ig.modules[name].loaded ) { dependenciesLoaded = false; } } if( dependenciesLoaded && m.body ) { ig._loadQueue.splice(i, 1); m.loaded = true; m.body(); modulesLoaded = true; i--; } } if( modulesLoaded ) { ig._execModules(); } // No modules executed, no more files to load but loadQueue not empty? // Must be some unresolved dependencies! else if( !ig.baked && ig._waitForOnload == 0 && ig._loadQueue.length != 0 ) { var unresolved = []; for( var i = 0; i < ig._loadQueue.length; i++ ) { // Which dependencies aren't loaded? var unloaded = []; var requires = ig._loadQueue[i].requires; for( var j = 0; j < requires.length; j++ ) { var m = ig.modules[ requires[j] ]; if( !m || !m.loaded ) { unloaded.push( requires[j] ); } } unresolved.push( ig._loadQueue[i].name + ' (requires: ' + unloaded.join(', ') + ')'); } throw( 'Unresolved (circular?) dependencies. ' + "Most likely there's a name/path mismatch for one of the listed modules:\n" + unresolved.join('\n') ); } }, _DOMReady: function() { if( !ig.modules['dom.ready'].loaded ) { if ( !document.body ) { return setTimeout( ig._DOMReady, 13 ); } ig.modules['dom.ready'].loaded = true; ig._waitForOnload--; ig._execModules(); } return 0; }, _boot: function() { if( document.location.href.match(/\?nocache/) ) { ig.setNocache( true ); } // Probe user agent string ig.ua.pixelRatio = window.devicePixelRatio || 1; ig.ua.viewport = { width: window.innerWidth, height: window.innerHeight }; ig.ua.screen = { width: window.screen.availWidth * ig.ua.pixelRatio, height: window.screen.availHeight * ig.ua.pixelRatio }; ig.ua.iPhone = /iPhone/i.test(navigator.userAgent); ig.ua.iPhone4 = (ig.ua.iPhone && ig.ua.pixelRatio == 2); ig.ua.iPad = /iPad/i.test(navigator.userAgent); ig.ua.android = /android/i.test(navigator.userAgent); ig.ua.iOS = ig.ua.iPhone || ig.ua.iPad; ig.ua.mobile = ig.ua.iOS || ig.ua.android; }, _initDOMReady: function() { if( ig.modules['dom.ready'] ) { ig._execModules(); return; } ig._boot(); ig.modules['dom.ready'] = { requires: [], loaded: false, body: null }; ig._waitForOnload++; if ( document.readyState === 'complete' ) { ig._DOMReady(); } else { document.addEventListener( 'DOMContentLoaded', ig._DOMReady, false ); window.addEventListener( 'load', ig._DOMReady, false ); } } }; // ----------------------------------------------------------------------------- // Provide ig.setAnimation and ig.clearAnimation as a compatible way to use // requestAnimationFrame if available or setInterval otherwise // Find vendor prefix, if any var vendors = ['ms', 'moz', 'webkit', 'o']; for( var i = 0; i < vendors.length && !window.requestAnimationFrame; i++ ) { window.requestAnimationFrame = window[vendors[i]+'RequestAnimationFrame']; } // Use requestAnimationFrame if available if( window.requestAnimationFrame ) { var next = 1, anims = {}; window.ig.setAnimation = function( callback, element ) { var current = next++; anims[current] = true; var animate = function() { if( !anims[current] ) { return; } // deleted? window.requestAnimationFrame( animate, element ); callback(); }; window.requestAnimationFrame( animate, element ); return current; }; window.ig.clearAnimation = function( id ) { delete anims[id]; }; } // [set/clear]Interval fallback else { window.ig.setAnimation = function( callback, element ) { return window.setInterval( callback, 1000/60 ); }; window.ig.clearAnimation = function( id ) { window.clearInterval( id ); }; } // ----------------------------------------------------------------------------- // Class object based on John Resigs code; inspired by base2 and Prototype // http://ejohn.org/blog/simple-javascript-inheritance/ var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\bparent\b/ : /.*/; window.ig.Class = function(){}; var inject = function(prop) { var proto = this.prototype; var parent = {}; for( var name in prop ) { if( typeof(prop[name]) == "function" && typeof(proto[name]) == "function" && fnTest.test(prop[name]) ) { parent[name] = proto[name]; // save original function proto[name] = (function(name, fn){ return function() { var tmp = this.parent; this.parent = parent[name]; var ret = fn.apply(this, arguments); this.parent = tmp; return ret; }; })( name, prop[name] ); } else { proto[name] = prop[name]; } } }; window.ig.Class.extend = function(prop) { var parent = this.prototype; initializing = true; var prototype = new this(); initializing = false; for( var name in prop ) { if( typeof(prop[name]) == "function" && typeof(parent[name]) == "function" && fnTest.test(prop[name]) ) { prototype[name] = (function(name, fn){ return function() { var tmp = this.parent; this.parent = parent[name]; var ret = fn.apply(this, arguments); this.parent = tmp; return ret; }; })( name, prop[name] ); } else { prototype[name] = prop[name]; } } function Class() { if( !initializing ) { // If this class has a staticInstantiate method, invoke it // and check if we got something back. If not, the normal // constructor (init) is called. if( this.staticInstantiate ) { var obj = this.staticInstantiate.apply(this, arguments); if( obj ) { return obj; } } for( var p in this ) { if( typeof(this[p]) == 'object' ) { this[p] = ig.copy(this[p]); // deep copy! } } if( this.init ) { this.init.apply(this, arguments); } } return this; } Class.prototype = prototype; Class.constructor = Class; Class.extend = window.ig.Class.extend; Class.inject = inject; return Class; }; })(window); // ----------------------------------------------------------------------------- // The main() function creates the system, input, sound and game objects, // creates a preloader and starts the run loop ig.module( 'impact.impact' ) .requires( 'dom.ready', 'impact.loader', 'impact.system', 'impact.input', 'impact.sound' ) .defines(function(){ "use strict"; ig.main = function( canvasId, gameClass, fps, width, height, scale, loaderClass ) { ig.system = new ig.System( canvasId, fps, width, height, scale || 1 ); ig.input = new ig.Input(); ig.soundManager = new ig.SoundManager(); ig.music = new ig.Music(); ig.ready = true; var loader = new (loaderClass || ig.Loader)( gameClass, ig.resources ); loader.load(); }; });
JavaScript
ig.module( 'impact.sound' ) .defines(function(){ "use strict"; ig.SoundManager = ig.Class.extend({ clips: {}, volume: 1, format: null, init: function() { // Probe sound formats and determine the file extension to load var probe = new Audio(); for( var i = 0; i < ig.Sound.use.length; i++ ) { var format = ig.Sound.use[i]; if( probe.canPlayType(format.mime) ) { this.format = format; break; } } // No compatible format found? -> Disable sound if( !this.format ) { ig.Sound.enabled = false; } }, load: function( path, multiChannel, loadCallback ) { // Path to the soundfile with the right extension (.ogg or .mp3) var realPath = ig.prefix + path.replace(/[^\.]+$/, this.format.ext) + ig.nocache; // Sound file already loaded? if( this.clips[path] ) { // Only loaded as single channel and now requested as multichannel? if( multiChannel && this.clips[path].length < ig.Sound.channels ) { for( var i = this.clips[path].length; i < ig.Sound.channels; i++ ) { var a = new Audio( realPath ); a.load(); this.clips[path].push( a ); } } return this.clips[path][0]; } var clip = new Audio( realPath ); if( loadCallback ) { // The canplaythrough event is dispatched when the browser determines // that the sound can be played without interuption, provided the // download rate doesn't change. // FIXME: Mobile Safari doesn't seem to dispatch this event at all? clip.addEventListener( 'canplaythrough', function cb(ev){ clip.removeEventListener('canplaythrough', cb, false); loadCallback( path, true, ev ); }, false ); clip.addEventListener( 'error', function(ev){ loadCallback( path, false, ev ); }, false); } clip.preload = 'auto'; clip.load(); this.clips[path] = [clip]; if( multiChannel ) { for( var i = 1; i < ig.Sound.channels; i++ ) { var a = new Audio(realPath); a.load(); this.clips[path].push( a ); } } return clip; }, get: function( path ) { // Find and return a channel that is not currently playing var channels = this.clips[path]; for( var i = 0, clip; clip = channels[i++]; ) { if( clip.paused || clip.ended ) { if( clip.ended ) { clip.currentTime = 0; } return clip; } } // Still here? Pause and rewind the first channel channels[0].pause(); channels[0].currentTime = 0; return channels[0]; } }); ig.Music = ig.Class.extend({ tracks: [], namedTracks: {}, currentTrack: null, currentIndex: 0, random: false, _volume: 1, _loop: false, _fadeInterval: 0, _fadeTimer: null, _endedCallbackBound: null, init: function() { this._endedCallbackBound = this._endedCallback.bind(this); if( Object.defineProperty ) { // Standard Object.defineProperty(this,"volume", { get: this.getVolume.bind(this), set: this.setVolume.bind(this) }); Object.defineProperty(this,"loop", { get: this.getLooping.bind(this), set: this.setLooping.bind(this) }); } else if( this.__defineGetter__ ) { // Non-standard this.__defineGetter__('volume', this.getVolume.bind(this)); this.__defineSetter__('volume', this.setVolume.bind(this)); this.__defineGetter__('loop', this.getLooping.bind(this)); this.__defineSetter__('loop', this.setLooping.bind(this)); } }, add: function( music, name ) { if( !ig.Sound.enabled ) { return; } var path = music instanceof ig.Sound ? music.path : music; var track = ig.soundManager.load(path, false); track.loop = this._loop; track.volume = this._volume; track.addEventListener( 'ended', this._endedCallbackBound, false ); this.tracks.push( track ); if( name ) { this.namedTracks[name] = track; } if( !this.currentTrack ) { this.currentTrack = track; } }, next: function() { if( !this.tracks.length ) { return; } this.stop(); this.currentIndex = this.random ? Math.floor(Math.random() * this.tracks.length) : (this.currentIndex + 1) % this.tracks.length; this.currentTrack = this.tracks[this.currentIndex]; this.play(); }, pause: function() { if( !this.currentTrack ) { return; } this.currentTrack.pause(); }, stop: function() { if( !this.currentTrack ) { return; } this.currentTrack.pause(); this.currentTrack.currentTime = 0; }, play: function( name ) { // If a name was provided, stop playing the current track (if any) // and play the named track if( name && this.namedTracks[name] ) { var newTrack = this.namedTracks[name]; if( newTrack != this.currentTrack ) { this.stop(); this.currentTrack = newTrack; } } else if( !this.currentTrack ) { return; } this.currentTrack.play(); }, getLooping: function() { return this._loop; }, setLooping: function( l ) { this._loop = l; for( var i in this.tracks ) { this.tracks[i].loop = l; } }, getVolume: function() { return this._volume; }, setVolume: function( v ) { this._volume = v.limit(0,1); for( var i in this.tracks ) { this.tracks[i].volume = this._volume; } }, fadeOut: function( time ) { if( !this.currentTrack ) { return; } clearInterval( this._fadeInterval ); this.fadeTimer = new ig.Timer( time ); this._fadeInterval = setInterval( this._fadeStep.bind(this), 50 ); }, _fadeStep: function() { var v = this.fadeTimer.delta() .map(-this.fadeTimer.target, 0, 1, 0) .limit( 0, 1 ) * this._volume; if( v <= 0.01 ) { this.stop(); this.currentTrack.volume = this._volume; clearInterval( this._fadeInterval ); } else { this.currentTrack.volume = v; } }, _endedCallback: function() { if( this._loop ) { this.play(); } else { this.next(); } } }); ig.Sound = ig.Class.extend({ path: '', volume: 1, currentClip: null, multiChannel: true, init: function( path, multiChannel ) { this.path = path; this.multiChannel = (multiChannel !== false); this.load(); }, load: function( loadCallback ) { if( !ig.Sound.enabled ) { if( loadCallback ) { loadCallback( this.path, true ); } return; } if( ig.ready ) { ig.soundManager.load( this.path, this.multiChannel, loadCallback ); } else { ig.addResource( this ); } }, play: function() { if( !ig.Sound.enabled ) { return; } this.currentClip = ig.soundManager.get( this.path ); this.currentClip.volume = ig.soundManager.volume * this.volume; this.currentClip.play(); }, stop: function() { if( this.currentClip ) { this.currentClip.pause(); this.currentClip.currentTime = 0; } } }); ig.Sound.FORMAT = { MP3: {ext: 'mp3', mime: 'audio/mpeg'}, M4A: {ext: 'm4a', mime: 'audio/mp4; codecs=mp4a'}, OGG: {ext: 'ogg', mime: 'audio/ogg; codecs=vorbis'}, WEBM: {ext: 'webm', mime: 'audio/webm; codecs=vorbis'}, CAF: {ext: 'caf', mime: 'audio/x-caf'} }; ig.Sound.use = [ig.Sound.FORMAT.OGG, ig.Sound.FORMAT.MP3]; ig.Sound.channels = 4; ig.Sound.enabled = true; });
JavaScript
ig.module( 'impact.loader' ) .requires( 'impact.image', 'impact.font', 'impact.sound' ) .defines(function(){ "use strict"; ig.Loader = ig.Class.extend({ resources: [], gameClass: null, status: 0, done: false, _unloaded: [], _drawStatus: 0, _intervalId: 0, _loadCallbackBound: null, init: function( gameClass, resources ) { this.gameClass = gameClass; this.resources = resources; this._loadCallbackBound = this._loadCallback.bind(this); for( var i = 0; i < this.resources.length; i++ ) { this._unloaded.push( this.resources[i].path ); } }, load: function() { ig.system.clear( '#000' ); if( !this.resources.length ) { this.end(); return; } for( var i = 0; i < this.resources.length; i++ ) { this.loadResource( this.resources[i] ); } this._intervalId = setInterval( this.draw.bind(this), 16 ); }, loadResource: function( res ) { res.load( this._loadCallbackBound ); }, end: function() { if( this.done ) { return; } this.done = true; clearInterval( this._intervalId ); ig.system.setGame( this.gameClass ); }, draw: function() { this._drawStatus += (this.status - this._drawStatus)/5; var s = ig.system.scale; var w = ig.system.width * 0.6; var h = ig.system.height * 0.1; var x = ig.system.width * 0.5-w/2; var y = ig.system.height * 0.5-h/2; ig.system.context.fillStyle = '#000'; ig.system.context.fillRect( 0, 0, 480, 320 ); ig.system.context.fillStyle = '#fff'; ig.system.context.fillRect( x*s, y*s, w*s, h*s ); ig.system.context.fillStyle = '#000'; ig.system.context.fillRect( x*s+s, y*s+s, w*s-s-s, h*s-s-s ); ig.system.context.fillStyle = '#fff'; ig.system.context.fillRect( x*s, y*s, w*s*this._drawStatus, h*s ); }, _loadCallback: function( path, status ) { if( status ) { this._unloaded.erase( path ); } else { throw( 'Failed to load resource: ' + path ); } this.status = 1 - (this._unloaded.length / this.resources.length); if( this._unloaded.length == 0 ) { // all done? setTimeout( this.end.bind(this), 250 ); } } }); });
JavaScript
ig.module( 'impact.animation' ) .requires( 'impact.timer', 'impact.image' ) .defines(function(){ "use strict"; ig.AnimationSheet = ig.Class.extend({ width: 8, height: 8, image: null, init: function( path, width, height ) { this.width = width; this.height = height; this.image = new ig.Image( path ); } }); ig.Animation = ig.Class.extend({ sheet: null, timer: null, sequence: [], flip: {x: false, y: false}, pivot: {x: 0, y: 0}, frame: 0, tile: 0, loopCount: 0, alpha: 1, angle: 0, init: function( sheet, frameTime, sequence, stop ) { this.sheet = sheet; this.pivot = {x: sheet.width/2, y: sheet.height/2 }; this.timer = new ig.Timer(); this.frameTime = frameTime; this.sequence = sequence; this.stop = !!stop; this.tile = this.sequence[0]; }, rewind: function() { this.timer.reset(); this.loopCount = 0; this.tile = this.sequence[0]; return this; }, gotoFrame: function( f ) { this.timer.set( this.frameTime * -f ); this.update(); }, gotoRandomFrame: function() { this.gotoFrame( Math.floor(Math.random() * this.sequence.length) ) }, update: function() { var frameTotal = Math.floor(this.timer.delta() / this.frameTime); this.loopCount = Math.floor(frameTotal / this.sequence.length); if( this.stop && this.loopCount > 0 ) { this.frame = this.sequence.length - 1; } else { this.frame = frameTotal % this.sequence.length; } this.tile = this.sequence[ this.frame ]; }, draw: function( targetX, targetY ) { var bbsize = Math.max(this.sheet.width, this.sheet.height); // On screen? if( targetX > ig.system.width || targetY > ig.system.height || targetX + bbsize < 0 || targetY + bbsize < 0 ) { return; } if( this.alpha != 1) { ig.system.context.globalAlpha = this.alpha; } if( this.angle == 0 ) { this.sheet.image.drawTile( targetX, targetY, this.tile, this.sheet.width, this.sheet.height, this.flip.x, this.flip.y ); } else { ig.system.context.save(); ig.system.context.translate( ig.system.getDrawPos(targetX + this.pivot.x), ig.system.getDrawPos(targetY + this.pivot.y) ); ig.system.context.rotate( this.angle ); this.sheet.image.drawTile( -this.pivot.x, -this.pivot.y, this.tile, this.sheet.width, this.sheet.height, this.flip.x, this.flip.y ); ig.system.context.restore(); } if( this.alpha != 1) { ig.system.context.globalAlpha = 1; } } }); });
JavaScript
ig.module( 'impact.map' ) .defines(function(){ "use strict"; ig.Map = ig.Class.extend({ tilesize: 8, width: 1, height: 1, data: [[]], name: null, init: function( tilesize, data ) { this.tilesize = tilesize; this.data = data; this.height = data.length; this.width = data[0].length; }, getTile: function( x, y ) { var tx = Math.floor( x / this.tilesize ); var ty = Math.floor( y / this.tilesize ); if( (tx >= 0 && tx < this.width) && (ty >= 0 && ty < this.height) ) { return this.data[ty][tx]; } else { return 0; } }, setTile: function( x, y, tile ) { var tx = Math.floor( x / this.tilesize ); var ty = Math.floor( y / this.tilesize ); if( (tx >= 0 && tx < this.width) && (ty >= 0 && ty < this.height) ) { this.data[ty][tx] = tile; } } }); });
JavaScript
ig.module( 'impact.background-map' ) .requires( 'impact.map', 'impact.image' ) .defines(function(){ "use strict"; ig.BackgroundMap = ig.Map.extend({ tiles: null, scroll: {x: 0, y:0}, distance: 1, repeat: false, tilesetName: '', foreground: false, enabled: true, preRender: false, preRenderedChunks: null, chunkSize: 512, debugChunks: false, anims: {}, init: function( tilesize, data, tileset ) { this.parent( tilesize, data ); this.setTileset( tileset ); }, setTileset: function( tileset ) { this.tilesetName = tileset instanceof ig.Image ? tileset.path : tileset; this.tiles = new ig.Image( this.tilesetName ); this.preRenderedChunks = null; }, setScreenPos: function( x, y ) { this.scroll.x = x / this.distance; this.scroll.y = y / this.distance; }, preRenderMapToChunks: function() { var totalWidth = this.width * this.tilesize * ig.system.scale, totalHeight = this.height * this.tilesize * ig.system.scale; var chunkCols = Math.ceil(totalWidth / this.chunkSize), chunkRows = Math.ceil(totalHeight / this.chunkSize); this.preRenderedChunks = []; for( var y = 0; y < chunkRows; y++ ) { this.preRenderedChunks[y] = []; for( var x = 0; x < chunkCols; x++ ) { var chunkWidth = (x == chunkCols-1) ? totalWidth - x * this.chunkSize : this.chunkSize; var chunkHeight = (y == chunkRows-1) ? totalHeight - y * this.chunkSize : this.chunkSize; this.preRenderedChunks[y][x] = this.preRenderChunk( x, y, chunkWidth, chunkHeight ); } } }, preRenderChunk: function( cx, cy, w, h ) { var tw = w / this.tilesize / ig.system.scale + 1, th = h / this.tilesize / ig.system.scale + 1; var nx = (cx * this.chunkSize / ig.system.scale) % this.tilesize, ny = (cy * this.chunkSize / ig.system.scale) % this.tilesize; var tx = Math.floor(cx * this.chunkSize / this.tilesize / ig.system.scale), ty = Math.floor(cy * this.chunkSize / this.tilesize / ig.system.scale); var chunk = ig.$new( 'canvas'); chunk.width = w; chunk.height = h; var oldContext = ig.system.context; ig.system.context = chunk.getContext("2d"); for( var x = 0; x < tw; x++ ) { for( var y = 0; y < th; y++ ) { if( x + tx < this.width && y + ty < this.height ) { var tile = this.data[y+ty][x+tx]; if( tile ) { this.tiles.drawTile( x * this.tilesize - nx, y * this.tilesize - ny, tile - 1, this.tilesize ); } } } } ig.system.context = oldContext; return chunk; }, draw: function() { if( !this.tiles.loaded || !this.enabled ) { return; } if( this.preRender ) { this.drawPreRendered(); } else { this.drawTiled(); } }, drawPreRendered: function() { if( !this.preRenderedChunks ) { this.preRenderMapToChunks(); } var dx = ig.system.getDrawPos(this.scroll.x), dy = ig.system.getDrawPos(this.scroll.y); if( this.repeat ) { dx %= this.width * this.tilesize * ig.system.scale; dy %= this.height * this.tilesize * ig.system.scale; } var minChunkX = Math.max( Math.floor(dx / this.chunkSize), 0 ), minChunkY = Math.max( Math.floor(dy / this.chunkSize), 0 ), maxChunkX = Math.ceil((dx+ig.system.realWidth) / this.chunkSize), maxChunkY = Math.ceil((dy+ig.system.realHeight) / this.chunkSize), maxRealChunkX = this.preRenderedChunks[0].length, maxRealChunkY = this.preRenderedChunks.length; if( !this.repeat ) { maxChunkX = Math.min( maxChunkX, maxRealChunkX ); maxChunkY = Math.min( maxChunkY, maxRealChunkY ); } var nudgeY = 0; for( var cy = minChunkY; cy < maxChunkY; cy++ ) { var nudgeX = 0; for( var cx = minChunkX; cx < maxChunkX; cx++ ) { var chunk = this.preRenderedChunks[cy % maxRealChunkY][cx % maxRealChunkX]; var x = -dx + cx * this.chunkSize - nudgeX; var y = -dy + cy * this.chunkSize - nudgeY; ig.system.context.drawImage( chunk, x, y); ig.Image.drawCount++; if( this.debugChunks ) { ig.system.context.strokeStyle = '#f0f'; ig.system.context.strokeRect( x, y, this.chunkSize, this.chunkSize ); } // If we repeat in X and this chunks width wasn't the full chunk size // and the screen is not already filled, we need to draw anohter chunk // AND nudge it to be flush with the last chunk if( this.repeat && chunk.width < this.chunkSize && x + chunk.width < ig.system.realWidth ) { nudgeX = this.chunkSize - chunk.width; maxChunkX++; } } // Same as above, but for Y if( this.repeat && chunk.height < this.chunkSize && y + chunk.height < ig.system.realHeight ) { nudgeY = this.chunkSize - chunk.height; maxChunkY++; } } }, drawTiled: function() { var tile = 0, anim = null, tileOffsetX = (this.scroll.x / this.tilesize).toInt(), tileOffsetY = (this.scroll.y / this.tilesize).toInt(), pxOffsetX = this.scroll.x % this.tilesize, pxOffsetY = this.scroll.y % this.tilesize, pxMinX = -pxOffsetX - this.tilesize, pxMinY = -pxOffsetY - this.tilesize, pxMaxX = ig.system.width + this.tilesize - pxOffsetX, pxMaxY = ig.system.height + this.tilesize - pxOffsetY; // FIXME: could be sped up for non-repeated maps: restrict the for loops // to the map size instead of to the screen size and skip the 'repeat' // checks inside the loop. for( var mapY = -1, pxY = pxMinY; pxY < pxMaxY; mapY++, pxY += this.tilesize) { var tileY = mapY + tileOffsetY; // Repeat Y? if( tileY >= this.height || tileY < 0 ) { if( !this.repeat ) { continue; } tileY = tileY > 0 ? tileY % this.height : ((tileY+1) % this.height) + this.height - 1; } for( var mapX = -1, pxX = pxMinX; pxX < pxMaxX; mapX++, pxX += this.tilesize ) { var tileX = mapX + tileOffsetX; // Repeat X? if( tileX >= this.width || tileX < 0 ) { if( !this.repeat ) { continue; } tileX = tileX > 0 ? tileX % this.width : ((tileX+1) % this.width) + this.width - 1; } // Draw! if( (tile = this.data[tileY][tileX]) ) { if( (anim = this.anims[tile-1]) ) { anim.draw( pxX, pxY ); } else { this.tiles.drawTile( pxX, pxY, tile-1, this.tilesize ); } } } // end for x } // end for y } }); });
JavaScript
ig.module( 'impact.timer' ) .defines(function(){ "use strict"; ig.Timer = ig.Class.extend({ target: 0, base: 0, last: 0, pausedAt: 0, init: function( seconds ) { this.base = ig.Timer.time; this.last = ig.Timer.time; this.target = seconds || 0; }, set: function( seconds ) { this.target = seconds || 0; this.base = ig.Timer.time; this.pausedAt = 0; }, reset: function() { this.base = ig.Timer.time; this.pausedAt = 0; }, tick: function() { var delta = ig.Timer.time - this.last; this.last = ig.Timer.time; return (this.pausedAt ? 0 : delta); }, delta: function() { return (this.pausedAt || ig.Timer.time) - this.base - this.target; }, pause: function() { if( !this.pausedAt ) { this.pausedAt = ig.Timer.time; } }, unpause: function() { if( this.pausedAt ) { this.base += ig.Timer.time - this.pausedAt; this.pausedAt = 0; } } }); ig.Timer._last = 0; ig.Timer.time = 0; ig.Timer.timeScale = 1; ig.Timer.maxStep = 0.05; ig.Timer.step = function() { var current = Date.now(); var delta = (current - ig.Timer._last) / 1000; ig.Timer.time += Math.min(delta, ig.Timer.maxStep) * ig.Timer.timeScale; ig.Timer._last = current; }; });
JavaScript
ig.module( 'impact.font' ) .requires( 'impact.image' ) .defines(function(){ "use strict"; ig.Font = ig.Image.extend({ widthMap: [], indices: [], firstChar: 32, alpha: 1, letterSpacing: 1, lineSpacing: 0, onload: function( ev ) { this._loadMetrics( this.data ); this.parent( ev ); }, widthForString: function( text ) { // Multiline? if( text.indexOf('\n') !== -1 ) { var lines = text.split( '\n' ); var width = 0; for( var i = 0; i < lines.length; i++ ) { width = Math.max( width, this._widthForLine(lines[i]) ); } return width; } else { return this._widthForLine( text ); } }, _widthForLine: function( text ) { var width = 0; for( var i = 0; i < text.length; i++ ) { width += this.widthMap[text.charCodeAt(i) - this.firstChar] + this.letterSpacing; } return width; }, heightForString: function( text ) { return text.split('\n').length * (this.height + this.lineSpacing); }, draw: function( text, x, y, align ) { if( typeof(text) != 'string' ) { text = text.toString(); } // Multiline? if( text.indexOf('\n') !== -1 ) { var lines = text.split( '\n' ); var lineHeight = this.height + this.lineSpacing; for( var i = 0; i < lines.length; i++ ) { this.draw( lines[i], x, y + i * lineHeight, align ); } return; } if( align == ig.Font.ALIGN.RIGHT || align == ig.Font.ALIGN.CENTER ) { var width = this._widthForLine( text ); x -= align == ig.Font.ALIGN.CENTER ? width/2 : width; } if( this.alpha !== 1 ) { ig.system.context.globalAlpha = this.alpha; } for( var i = 0; i < text.length; i++ ) { var c = text.charCodeAt(i); x += this._drawChar( c - this.firstChar, x, y ); } if( this.alpha !== 1 ) { ig.system.context.globalAlpha = 1; } ig.Image.drawCount += text.length; }, _drawChar: function( c, targetX, targetY ) { if( !this.loaded || c < 0 || c >= this.indices.length ) { return 0; } var scale = ig.system.scale; var charX = this.indices[c] * scale; var charY = 0; var charWidth = this.widthMap[c] * scale; var charHeight = (this.height-2) * scale; ig.system.context.drawImage( this.data, charX, charY, charWidth, charHeight, ig.system.getDrawPos(targetX), ig.system.getDrawPos(targetY), charWidth, charHeight ); return this.widthMap[c] + this.letterSpacing; }, _loadMetrics: function( image ) { // Draw the bottommost line of this font image into an offscreen canvas // and analyze it pixel by pixel. // A run of non-transparent pixels represents a character and its width this.height = image.height-1; this.widthMap = []; this.indices = []; var canvas = ig.$new('canvas'); canvas.width = image.width; canvas.height = image.height; var ctx = canvas.getContext('2d'); ctx.drawImage( image, 0, 0 ); var px = ctx.getImageData(0, image.height-1, image.width, 1); var currentChar = 0; var currentWidth = 0; for( var x = 0; x < image.width; x++ ) { var index = x * 4 + 3; // alpha component of this pixel if( px.data[index] != 0 ) { currentWidth++; } else if( px.data[index] == 0 && currentWidth ) { this.widthMap.push( currentWidth ); this.indices.push( x-currentWidth ); currentChar++; currentWidth = 0; } } this.widthMap.push( currentWidth ); this.indices.push( x-currentWidth ); } }); ig.Font.ALIGN = { LEFT: 0, RIGHT: 1, CENTER: 2 }; });
JavaScript
ig.module( 'impact.image' ) .defines(function(){ "use strict"; ig.Image = ig.Class.extend({ data: null, width: 0, height: 0, loaded: false, failed: false, loadCallback: null, path: '', staticInstantiate: function( path ) { return ig.Image.cache[path] || null; }, init: function( path ) { this.path = path; this.load(); }, load: function( loadCallback ) { if( this.loaded ) { if( loadCallback ) { loadCallback( this.path, true ); } return; } else if( !this.loaded && ig.ready ) { this.loadCallback = loadCallback || null; this.data = new Image(); this.data.onload = this.onload.bind(this); this.data.onerror = this.onerror.bind(this); this.data.src = ig.prefix + this.path + ig.nocache; } else { ig.addResource( this ); } ig.Image.cache[this.path] = this; }, reload: function() { this.loaded = false; this.data = new Image(); this.data.onload = this.onload.bind(this); this.data.src = this.path + '?' + Date.now(); }, onload: function( event ) { this.width = this.data.width; this.height = this.data.height; this.loaded = true; if( ig.system.scale != 1 ) { this.resize( ig.system.scale ); } if( this.loadCallback ) { this.loadCallback( this.path, true ); } }, onerror: function( event ) { this.failed = true; if( this.loadCallback ) { this.loadCallback( this.path, false ); } }, resize: function( scale ) { // Nearest-Neighbor scaling // The original image is drawn into an offscreen canvas of the same size // and copied into another offscreen canvas with the new size. // The scaled offscreen canvas becomes the image (data) of this object. /* 2012/8/23 Vinson 修改非0.5倍数缩放问题 var widthScaled = this.width * scale; var heightScaled = this.height * scale; */ var widthScaled = Math.floor(this.width * scale); var heightScaled = Math.floor(this.height * scale); var orig = ig.$new('canvas'); orig.width = this.width; orig.height = this.height; var origCtx = orig.getContext('2d'); origCtx.drawImage( this.data, 0, 0, this.width, this.height, 0, 0, this.width, this.height ); var origPixels = origCtx.getImageData(0, 0, this.width, this.height); var scaled = ig.$new('canvas'); scaled.width = widthScaled; scaled.height = heightScaled; var scaledCtx = scaled.getContext('2d'); var scaledPixels = scaledCtx.getImageData( 0, 0, widthScaled, heightScaled ); for( var y = 0; y < heightScaled; y++ ) { for( var x = 0; x < widthScaled; x++ ) { var index = (Math.floor(y / scale) * this.width + Math.floor(x / scale)) * 4; var indexScaled = (y * widthScaled + x) * 4; scaledPixels.data[ indexScaled ] = origPixels.data[ index ]; scaledPixels.data[ indexScaled+1 ] = origPixels.data[ index+1 ]; scaledPixels.data[ indexScaled+2 ] = origPixels.data[ index+2 ]; scaledPixels.data[ indexScaled+3 ] = origPixels.data[ index+3 ]; } } scaledCtx.putImageData( scaledPixels, 0, 0 ); this.data = scaled; }, draw: function( targetX, targetY, sourceX, sourceY, width, height ) { if( !this.loaded ) { return; } var scale = ig.system.scale; /* 2012/8/23 Vinson 修改非0.5倍数缩放问题 sourceX = sourceX ? sourceX * scale : 0; sourceY = sourceY ? sourceY * scale : 0; width = (width ? width : this.width) * scale; height = (height ? height : this.height) * scale; */ sourceX = sourceX ? Math.floor(sourceX * scale) : 0; sourceY = sourceY ? Math.floor(sourceY * scale) : 0; width = Math.floor((width ? width : this.width) * scale); height = Math.floor((height ? height : this.height) * scale); ig.system.context.drawImage( this.data, sourceX, sourceY, width, height, ig.system.getDrawPos(targetX), ig.system.getDrawPos(targetY), width, height ); ig.Image.drawCount++; }, drawTile: function( targetX, targetY, tile, tileWidth, tileHeight, flipX, flipY ) { tileHeight = tileHeight ? tileHeight : tileWidth; if( !this.loaded || tileWidth > this.width || tileHeight > this.height ) { return; } var scale = ig.system.scale; var tileWidthScaled = Math.floor(tileWidth * scale); var tileHeightScaled = Math.floor(tileHeight * scale); var scaleX = flipX ? -1 : 1; var scaleY = flipY ? -1 : 1; if( flipX || flipY ) { ig.system.context.save(); ig.system.context.scale( scaleX, scaleY ); } /* 2012/8/26 Vinson 修改Error: INDEX_SIZE_ERR: DOM Exception 1问题 ig.system.context.drawImage( this.data, ( Math.floor(tile * tileWidth) % this.width ) * scale, ( Math.floor(tile * tileWidth / this.width) * tileHeight ) * scale, tileWidthScaled, tileHeightScaled, ig.system.getDrawPos(targetX) * scaleX - (flipX ? tileWidthScaled : 0), ig.system.getDrawPos(targetY) * scaleY - (flipY ? tileHeightScaled : 0), tileWidthScaled, tileHeightScaled ); */ ig.system.context.drawImage( this.data, Math.floor(( Math.floor(tile * tileWidth) % this.width ) * scale), Math.floor(( Math.floor(tile * tileWidth / this.width) * tileHeight ) * scale), tileWidthScaled, tileHeightScaled, Math.floor(ig.system.getDrawPos(targetX) * scaleX - (flipX ? tileWidthScaled : 0)), Math.floor(ig.system.getDrawPos(targetY) * scaleY - (flipY ? tileHeightScaled : 0)), tileWidthScaled, tileHeightScaled ); if( flipX || flipY ) { ig.system.context.restore(); } ig.Image.drawCount++; } }); ig.Image.drawCount = 0; ig.Image.cache = {}; ig.Image.reloadCache = function() { for( var path in ig.Image.cache ) { ig.Image.cache[path].reload(); } }; });
JavaScript
ig.module( 'impact.system' ) .requires( 'impact.timer', 'impact.image' ) .defines(function(){ "use strict"; ig.System = ig.Class.extend({ fps: 30, width: 320, height: 240, realWidth: 320, realHeight: 240, scale: 1, tick: 0, animationId: 0, newGameClass: null, running: false, delegate: null, clock: null, canvas: null, context: null, init: function( canvasId, fps, width, height, scale ) { this.fps = fps; this.clock = new ig.Timer(); this.canvas = ig.$(canvasId); this.resize( width, height, scale ); this.context = this.canvas.getContext('2d'); this.getDrawPos = ig.System.drawMode; }, resize: function( width, height, scale ) { this.width = width; this.height = height; this.scale = scale || this.scale; this.realWidth = this.width * this.scale; this.realHeight = this.height * this.scale; this.canvas.width = this.realWidth; this.canvas.height = this.realHeight; }, setGame: function( gameClass ) { if( this.running ) { this.newGameClass = gameClass; } else { this.setGameNow( gameClass ); } }, setGameNow: function( gameClass ) { ig.game = new (gameClass)(); ig.system.setDelegate( ig.game ); }, setDelegate: function( object ) { if( typeof(object.run) == 'function' ) { this.delegate = object; this.startRunLoop(); } else { throw( 'System.setDelegate: No run() function in object' ); } }, stopRunLoop: function() { ig.clearAnimation( this.animationId ); this.running = false; }, startRunLoop: function() { this.stopRunLoop(); this.animationId = ig.setAnimation( this.run.bind(this), this.canvas ); this.running = true; }, clear: function( color ) { this.context.fillStyle = color; this.context.fillRect( 0, 0, this.realWidth, this.realHeight ); }, run: function() { ig.Timer.step(); this.tick = this.clock.tick(); this.delegate.run(); ig.input.clearPressed(); if( this.newGameClass ) { this.setGameNow( this.newGameClass ); this.newGameClass = null; } }, getDrawPos: null, // Set through constructor }); ig.System.DRAW = { AUTHENTIC: function( p ) { return Math.round(p) * this.scale; }, SMOOTH: function( p ) { return Math.round(p * this.scale); }, SUBPIXEL: function( p ) { return p * this.scale; } }; ig.System.drawMode = ig.System.DRAW.SMOOTH; });
JavaScript
ig.module( 'impact.game' ) .requires( 'impact.impact', 'impact.entity', 'impact.collision-map', 'impact.background-map' ) .defines(function(){ "use strict"; ig.Game = ig.Class.extend({ clearColor: '#000000', gravity: 0, screen: {x: 0, y: 0}, _rscreen: {x: 0, y: 0}, entities: [], namedEntities: {}, collisionMap: ig.CollisionMap.staticNoCollision, backgroundMaps: [], backgroundAnims: {}, autoSort: false, sortBy: null, cellSize: 64, _deferredKill: [], _levelToLoad: null, _doSortEntities: false, staticInstantiate: function() { this.sortBy = this.sortBy || ig.Game.SORT.Z_INDEX; ig.game = this; return null; }, loadLevel: function( data ) { this.screen = {x: 0, y: 0}; // Entities this.entities = []; this.namedEntities = {}; for( var i = 0; i < data.entities.length; i++ ) { var ent = data.entities[i]; this.spawnEntity( ent.type, ent.x, ent.y, ent.settings ); } this.sortEntities(); // Map Layer this.collisionMap = ig.CollisionMap.staticNoCollision; this.backgroundMaps = []; for( var i = 0; i < data.layer.length; i++ ) { var ld = data.layer[i]; if( ld.name == 'collision' ) { this.collisionMap = new ig.CollisionMap(ld.tilesize, ld.data ); } else { var newMap = new ig.BackgroundMap(ld.tilesize, ld.data, ld.tilesetName); newMap.anims = this.backgroundAnims[ld.tilesetName] || {}; newMap.repeat = ld.repeat; newMap.distance = ld.distance; newMap.foreground = !!ld.foreground; newMap.preRender = !!ld.preRender; newMap.name = ld.name; this.backgroundMaps.push( newMap ); } } // Call post-init ready function on all entities for( var i = 0; i < this.entities.length; i++ ) { this.entities[i].ready(); } }, loadLevelDeferred: function( data ) { this._levelToLoad = data; }, getMapByName: function( name ) { if( name == 'collision' ) { return this.collisionMap; } for( var i = 0; i < this.backgroundMaps.length; i++ ) { if( this.backgroundMaps[i].name == name ) { return this.backgroundMaps[i]; } } return null; }, getEntityByName: function( name ) { return this.namedEntities[name]; }, getEntitiesByType: function( type ) { var entityClass = typeof(type) === 'string' ? ig.global[type] : type; var a = []; for( var i = 0; i < this.entities.length; i++ ) { var ent = this.entities[i]; if( ent instanceof entityClass && !ent._killed ) { a.push( ent ); } } return a; }, spawnEntity: function( type, x, y, settings ) { var entityClass = typeof(type) === 'string' ? ig.global[type] : type; if( !entityClass ) { throw("Can't spawn entity of type " + type); } var ent = new (entityClass)( x, y, settings || {} ); this.entities.push( ent ); if( ent.name ) { this.namedEntities[ent.name] = ent; } return ent; }, sortEntities: function() { this.entities.sort( this.sortBy ); }, sortEntitiesDeferred: function() { this._doSortEntities = true; }, removeEntity: function( ent ) { // Remove this entity from the named entities if( ent.name ) { delete this.namedEntities[ent.name]; } // We can not remove the entity from the entities[] array in the midst // of an update cycle, so remember all killed entities and remove // them later. // Also make sure this entity doesn't collide anymore and won't get // updated or checked ent._killed = true; ent.type = ig.Entity.TYPE.NONE; ent.checkAgainst = ig.Entity.TYPE.NONE; ent.collides = ig.Entity.COLLIDES.NEVER; this._deferredKill.push( ent ); }, run: function() { this.update(); this.draw(); }, update: function(){ // load new level? if( this._levelToLoad ) { this.loadLevel( this._levelToLoad ); this._levelToLoad = null; } // sort entities? if( this._doSortEntities || this.autoSort ) { this.sortEntities(); this._doSortEntities = false; } // update entities this.updateEntities(); this.checkEntities(); // remove all killed entities for( var i = 0; i < this._deferredKill.length; i++ ) { this.entities.erase( this._deferredKill[i] ); } this._deferredKill = []; // update background animations for( var tileset in this.backgroundAnims ) { var anims = this.backgroundAnims[tileset]; for( var a in anims ) { anims[a].update(); } } }, updateEntities: function() { for( var i = 0; i < this.entities.length; i++ ) { var ent = this.entities[i]; if( !ent._killed ) { ent.update(); } } }, draw: function(){ if( this.clearColor ) { ig.system.clear( this.clearColor ); } // This is a bit of a circle jerk. Entities reference game._rscreen // instead of game.screen when drawing themselfs in order to be // "synchronized" to the rounded(?) screen position this._rscreen.x = ig.system.getDrawPos(this.screen.x)/ig.system.scale; this._rscreen.y = ig.system.getDrawPos(this.screen.y)/ig.system.scale; var mapIndex; for( mapIndex = 0; mapIndex < this.backgroundMaps.length; mapIndex++ ) { var map = this.backgroundMaps[mapIndex]; if( map.foreground ) { // All foreground layers are drawn after the entities break; } map.setScreenPos( this.screen.x, this.screen.y ); map.draw(); } this.drawEntities(); for( mapIndex; mapIndex < this.backgroundMaps.length; mapIndex++ ) { var map = this.backgroundMaps[mapIndex]; map.setScreenPos( this.screen.x, this.screen.y ); map.draw(); } }, drawEntities: function() { for( var i = 0; i < this.entities.length; i++ ) { this.entities[i].draw(); } }, checkEntities: function() { // Insert all entities into a spatial hash and check them against any // other entity that already resides in the same cell. Entities that are // bigger than a single cell, are inserted into each one they intersect // with. // A list of entities, which the current one was already checked with, // is maintained for each entity. var hash = {}; for( var e = 0; e < this.entities.length; e++ ) { var entity = this.entities[e]; // Skip entities that don't check, don't get checked and don't collide if( entity.type == ig.Entity.TYPE.NONE && entity.checkAgainst == ig.Entity.TYPE.NONE && entity.collides == ig.Entity.COLLIDES.NEVER ) { continue; } var checked = {}, xmin = Math.floor( entity.pos.x/this.cellSize ), ymin = Math.floor( entity.pos.y/this.cellSize ), xmax = Math.floor( (entity.pos.x+entity.size.x)/this.cellSize ) + 1, ymax = Math.floor( (entity.pos.y+entity.size.y)/this.cellSize ) + 1; for( var x = xmin; x < xmax; x++ ) { for( var y = ymin; y < ymax; y++ ) { // Current cell is empty - create it and insert! if( !hash[x] ) { hash[x] = {}; hash[x][y] = [entity]; } else if( !hash[x][y] ) { hash[x][y] = [entity]; } // Check against each entity in this cell, then insert else { var cell = hash[x][y]; for( var c = 0; c < cell.length; c++ ) { // Intersects and wasn't already checkd? if( entity.touches(cell[c]) && !checked[cell[c].id] ) { checked[cell[c].id] = true; ig.Entity.checkPair( entity, cell[c] ); } } cell.push(entity); } } // end for y size } // end for x size } // end for entities } }); ig.Game.SORT = { Z_INDEX: function( a, b ){ return a.zIndex - b.zIndex; }, POS_X: function( a, b ){ return (a.pos.x+a.size.x) - (b.pos.x+b.size.x); }, POS_Y: function( a, b ){ return (a.pos.y+a.size.y) - (b.pos.y+b.size.y); } }; });
JavaScript
ig.module( 'impact.collision-map' ) .requires( 'impact.map' ) .defines(function(){ "use strict"; ig.CollisionMap = ig.Map.extend({ lastSlope: 1, tiledef: null, init: function( tilesize, data, tiledef ) { this.parent( tilesize, data ); this.tiledef = tiledef || ig.CollisionMap.defaultTileDef; for( var t in this.tiledef ) { if( t|0 > this.lastSlope ) { this.lastSlope = t|0; } } }, trace: function( x, y, vx, vy, objectWidth, objectHeight ) { // Set up the trace-result var res = { collision: {x: false, y: false, slope: false}, pos: {x: x, y: y}, tile: {x: 0, y: 0} }; // Break the trace down into smaller steps if necessary var steps = Math.ceil(Math.max(Math.abs(vx), Math.abs(vy)) / this.tilesize); if( steps > 1 ) { var sx = vx / steps; var sy = vy / steps; for( var i = 0; i < steps && (sx || sy); i++ ) { this._traceStep( res, x, y, sx, sy, objectWidth, objectHeight, vx, vy, i ); x = res.pos.x; y = res.pos.y; if( res.collision.x ) { sx = 0; vx = 0; } if( res.collision.y ) { sy = 0; vy = 0; } if( res.collision.slope ) { break; } } } // Just one step else { this._traceStep( res, x, y, vx, vy, objectWidth, objectHeight, vx, vy, 0 ); } return res; }, _traceStep: function( res, x, y, vx, vy, width, height, rvx, rvy, step ) { res.pos.x += vx; res.pos.y += vy; var t = 0; // Horizontal collision (walls) if( vx ) { var pxOffsetX = (vx > 0 ? width : 0); var tileOffsetX = (vx < 0 ? this.tilesize : 0); var firstTileY = Math.max( Math.floor(y / this.tilesize), 0 ); var lastTileY = Math.min( Math.ceil((y + height) / this.tilesize), this.height ); var tileX = Math.floor( (res.pos.x + pxOffsetX) / this.tilesize ); // We need to test the new tile position as well as the current one, as we // could still collide with the current tile if it's a line def. // We can skip this test if this is not the first step or the new tile position // is the same as the current one. var prevTileX = Math.floor( (x + pxOffsetX) / this.tilesize ); if( step > 0 || tileX == prevTileX || prevTileX < 0 || prevTileX >= this.width ) { prevTileX = -1; } // Still inside this collision map? if( tileX >= 0 && tileX < this.width ) { for( var tileY = firstTileY; tileY < lastTileY; tileY++ ) { if( prevTileX != -1 ) { t = this.data[tileY][prevTileX]; if( t > 1 && t <= this.lastSlope && this._checkTileDef(res, t, x, y, rvx, rvy, width, height, prevTileX, tileY) ) { break; } } t = this.data[tileY][tileX]; if( t == 1 || t > this.lastSlope || // fully solid tile? (t > 1 && this._checkTileDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY)) // slope? ) { if( t > 1 && t <= this.lastSlope && res.collision.slope ) { break; } // full tile collision! res.collision.x = true; res.tile.x = t; x = res.pos.x = tileX * this.tilesize - pxOffsetX + tileOffsetX; rvx = 0; break; } } } } // Vertical collision (floor, ceiling) if( vy ) { var pxOffsetY = (vy > 0 ? height : 0); var tileOffsetY = (vy < 0 ? this.tilesize : 0); var firstTileX = Math.max( Math.floor(res.pos.x / this.tilesize), 0 ); var lastTileX = Math.min( Math.ceil((res.pos.x + width) / this.tilesize), this.width ); var tileY = Math.floor( (res.pos.y + pxOffsetY) / this.tilesize ); var prevTileY = Math.floor( (y + pxOffsetY) / this.tilesize ); if( step > 0 || tileY == prevTileY || prevTileY < 0 || prevTileY >= this.height ) { prevTileY = -1; } // Still inside this collision map? if( tileY >= 0 && tileY < this.height ) { for( var tileX = firstTileX; tileX < lastTileX; tileX++ ) { if( prevTileY != -1 ) { t = this.data[prevTileY][tileX]; if( t > 1 && t <= this.lastSlope && this._checkTileDef(res, t, x, y, rvx, rvy, width, height, tileX, prevTileY) ) { break; } } t = this.data[tileY][tileX]; if( t == 1 || t > this.lastSlope || // fully solid tile? (t > 1 && this._checkTileDef(res, t, x, y, rvx, rvy, width, height, tileX, tileY)) // slope? ) { if( t > 1 && t <= this.lastSlope && res.collision.slope ) { break; } // full tile collision! res.collision.y = true; res.tile.y = t; res.pos.y = tileY * this.tilesize - pxOffsetY + tileOffsetY; break; } } } } // res is changed in place, nothing to return }, _checkTileDef: function( res, t, x, y, vx, vy, width, height, tileX, tileY ) { var def = this.tiledef[t]; if( !def ) { return false; } var lx = (tileX + def[0]) * this.tilesize, ly = (tileY + def[1]) * this.tilesize, lvx = (def[2] - def[0]) * this.tilesize, lvy = (def[3] - def[1]) * this.tilesize, solid = def[4]; // Find the box corner to test, relative to the line var tx = x + vx + (lvy < 0 ? width : 0) - lx, ty = y + vy + (lvx > 0 ? height : 0) - ly; // Is the box corner behind the line? if( lvx * ty - lvy * tx > 0 ) { // Lines are only solid from one side - find the dot product of // line normal and movement vector and dismiss if wrong side if( vx * -lvy + vy * lvx < 0 ) { return solid; } // Find the line normal var length = Math.sqrt(lvx * lvx + lvy * lvy); var nx = lvy/length, ny = -lvx/length; // Project out of the line var proj = tx * nx + ty * ny; var px = nx * proj, py = ny * proj; // If we project further out than we moved in, then this is a full // tile collision for solid tiles. // For non-solid tiles, make sure we were in front of the line. if( px*px+py*py >= vx*vx+vy*vy ) { return solid || (lvx * (ty-vy) - lvy * (tx-vx) < 0.5); } res.pos.x = x + vx - px; res.pos.y = y + vy - py; res.collision.slope = {x: lvx, y: lvy, nx: nx, ny: ny}; return true; } return false; } }); // Default Slope Tile definition. Each tile is defined by an array of 5 vars: // - 4 for the line in tile coordinates (0 -- 1) // - 1 specifing whether the tile is 'filled' behind the line or not // [ x1, y1, x2, y2, solid ] // Defining 'half', 'one third' and 'two thirds' as vars makes it a bit // easier to read... I hope. var H = 1/2, N = 1/3, M = 2/3, SOLID = true, NON_SOLID = false; ig.CollisionMap.defaultTileDef = { /* 15 NE */ 5: [0,1, 1,M, SOLID], 6: [0,M, 1,N, SOLID], 7: [0,N, 1,0, SOLID], /* 22 NE */ 3: [0,1, 1,H, SOLID], 4: [0,H, 1,0, SOLID], /* 45 NE */ 2: [0,1, 1,0, SOLID], /* 67 NE */ 10: [H,1, 1,0, SOLID], 21: [0,1, H,0, SOLID], /* 75 NE */ 32: [M,1, 1,0, SOLID], 43: [N,1, M,0, SOLID], 54: [0,1, N,0, SOLID], /* 15 SE */ 27: [0,0, 1,N, SOLID], 28: [0,N, 1,M, SOLID], 29: [0,M, 1,1, SOLID], /* 22 SE */ 25: [0,0, 1,H, SOLID], 26: [0,H, 1,1, SOLID], /* 45 SE */ 24: [0,0, 1,1, SOLID], /* 67 SE */ 11: [0,0, H,1, SOLID], 22: [H,0, 1,1, SOLID], /* 75 SE */ 33: [0,0, N,1, SOLID], 44: [N,0, M,1, SOLID], 55: [M,0, 1,1, SOLID], /* 15 NW */ 16: [1,N, 0,0, SOLID], 17: [1,M, 0,N, SOLID], 18: [1,1, 0,M, SOLID], /* 22 NW */ 14: [1,H, 0,0, SOLID], 15: [1,1, 0,H, SOLID], /* 45 NW */ 13: [1,1, 0,0, SOLID], /* 67 NW */ 8: [H,1, 0,0, SOLID], 19: [1,1, H,0, SOLID], /* 75 NW */ 30: [N,1, 0,0, SOLID], 41: [M,1, N,0, SOLID], 52: [1,1, M,0, SOLID], /* 15 SW */ 38: [1,M, 0,1, SOLID], 39: [1,N, 0,M, SOLID], 40: [1,0, 0,N, SOLID], /* 22 SW */ 36: [1,H, 0,1, SOLID], 37: [1,0, 0,H, SOLID], /* 45 SW */ 35: [1,0, 0,1, SOLID], /* 67 SW */ 9: [1,0, H,1, SOLID], 20: [H,0, 0,1, SOLID], /* 75 SW */ 31: [1,0, M,1, SOLID], 42: [M,0, N,1, SOLID], 53: [N,0, 0,1, SOLID], /* Go N */ 12: [0,0, 1,0, NON_SOLID], /* Go S */ 23: [1,1, 0,1, NON_SOLID], /* Go E */ 34: [1,0, 1,1, NON_SOLID], /* Go W */ 45: [0,1, 0,0, NON_SOLID] // Now that was fun! }; // Static Dummy CollisionMap; never collides ig.CollisionMap.staticNoCollision = { trace: function( x, y, vx, vy ) { return { collision: {x: false, y: false, slope: false}, pos: {x: x+vx, y: y+vy}, tile: {x: 0, y: 0} }; }}; });
JavaScript
var CONFIG = { AVAILABLE_DBS: ["mysql", "sqlite", "web2py", "mssql", "postgresql", "oracle", "sqlalchemy", "vfp9", "cubrid"], DEFAULT_DB: "mysql", AVAILABLE_LOCALES: ["ar", "cs", "de", "el", "en", "eo", "es", "fr", "hu", "it", "ja", "pl", "pt_BR", "ro", "ru", "sv", "zh"], DEFAULT_LOCALE: "en", AVAILABLE_BACKENDS: ["php-mysql", "php-blank", "php-file", "php-sqlite", "php-mysql+file", "php-postgresql", "php-pdo", "perl-file", "php-cubrid"], DEFAULT_BACKEND: ["php-mysql"], RELATION_THICKNESS: 2, RELATION_SPACING: 15, RELATION_COLORS: ["#000", "#800", "#080", "#008", "#088", "#808", "#088"], STATIC_PATH: "", XHR_PATH: "" }
JavaScript
/* (c) 2007 - now() Ondrej Zara, 1.7 */ var OZ = { $:function(x) { return typeof(x) == "string" ? document.getElementById(x) : x; }, select: function(x) { return document.querySelectorAll(x); }, opera:!!window.opera, ie:!!document.attachEvent && !window.opera, gecko:!!document.getAnonymousElementByAttribute, webkit:!!navigator.userAgent.match(/webkit/i), khtml:!!navigator.userAgent.match(/khtml/i) || !!navigator.userAgent.match(/konqueror/i), Event:{ _id:0, _byName:{}, _byID:{}, add:function(elm,event,cb) { var id = OZ.Event._id++; var element = OZ.$(elm); var fnc = (element && element.attachEvent ? function() { return cb.apply(element,arguments); } : cb); var rec = [element,event,fnc]; var parts = event.split(" "); while (parts.length) { var e = parts.pop(); if (element) { if (element.addEventListener) { element.addEventListener(e,fnc,false); } else if (element.attachEvent) { element.attachEvent("on"+e,fnc); } } if (!(e in OZ.Event._byName)) { OZ.Event._byName[e] = {}; } OZ.Event._byName[e][id] = rec; } OZ.Event._byID[id] = rec; return id; }, remove:function(id) { var rec = OZ.Event._byID[id]; if (!rec) { return; } var elm = rec[0]; var parts = rec[1].split(" "); while (parts.length) { var e = parts.pop(); if (elm) { if (elm.removeEventListener) { elm.removeEventListener(e,rec[2],false); } else if (elm.detachEvent) { elm.detachEvent("on"+e,rec[2]); } } delete OZ.Event._byName[e][id]; } delete OZ.Event._byID[id]; }, stop:function(e) { e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; }, prevent:function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; }, target:function(e) { return e.target || e.srcElement; } }, Class:function() { var c = function() { var init = arguments.callee.prototype.init; if (init) { init.apply(this,arguments); } }; c.implement = function(parent) { for (var p in parent.prototype) { this.prototype[p] = parent.prototype[p]; } return this; }; c.extend = function(parent) { var tmp = function(){}; tmp.prototype = parent.prototype; this.prototype = new tmp(); this.prototype.constructor = this; return this; }; c.prototype.bind = function(fnc) { return fnc.bind(this); }; c.prototype.dispatch = function(type, data) { var obj = { type:type, target:this, timeStamp:(new Date()).getTime(), data:data } var tocall = []; var list = OZ.Event._byName[type]; for (var id in list) { var item = list[id]; if (!item[0] || item[0] == this) { tocall.push(item[2]); } } var len = tocall.length; for (var i=0;i<len;i++) { tocall[i](obj); } } return c; }, DOM:{ elm:function(name, opts) { var elm = document.createElement(name); for (var p in opts) { var val = opts[p]; if (p == "class") { p = "className"; } if (p in elm) { elm[p] = val; } } OZ.Style.set(elm, opts); return elm; }, text:function(str) { return document.createTextNode(str); }, clear:function(node) { while (node.firstChild) {node.removeChild(node.firstChild);} }, pos:function(elm) { /* relative to _viewport_ */ var cur = OZ.$(elm); var html = cur.ownerDocument.documentElement; var parent = cur.parentNode; var x = y = 0; if (cur == html) { return [x,y]; } while (1) { if (OZ.Style.get(cur,"position") == "fixed") { x += cur.offsetLeft; y += cur.offsetTop; return [x,y]; } if (OZ.opera && (parent == html || OZ.Style.get(cur,"display") != "block")) { } else { x -= parent.scrollLeft; y -= parent.scrollTop; } if (parent == cur.offsetParent || cur.parentNode == html) { x += cur.offsetLeft; y += cur.offsetTop; cur = parent; } if (parent == html) { return [x,y]; } parent = parent.parentNode; } }, scroll:function() { var x = document.documentElement.scrollLeft || document.body.scrollLeft || 0; var y = document.documentElement.scrollTop || document.body.scrollTop || 0; return [x,y]; }, win:function(avail) { return (avail ? [window.innerWidth,window.innerHeight] : [document.documentElement.clientWidth,document.documentElement.clientHeight]); }, hasClass:function(node, className) { var cn = OZ.$(node).className; var arr = (cn ? cn.split(" ") : []); return (arr.indexOf(className) != -1); }, addClass:function(node,className) { if (OZ.DOM.hasClass(node, className)) { return; } var cn = OZ.$(node).className; var arr = (cn ? cn.split(" ") : []); arr.push(className); OZ.$(node).className = arr.join(" "); }, removeClass:function(node, className) { if (!OZ.DOM.hasClass(node, className)) { return; } var cn = OZ.$(node).className; var arr = (cn ? cn.split(" ") : []); var arr = arr.filter(function($){ return $ != className; }); OZ.$(node).className = arr.join(" "); }, append:function() { if (arguments.length == 1) { var arr = arguments[0]; var root = OZ.$(arr[0]); for (var i=1;i<arr.length;i++) { root.appendChild(OZ.$(arr[i])); } } else for (var i=0;i<arguments.length;i++) { OZ.DOM.append(arguments[i]); } } }, Style:{ get:function(elm, prop) { if (document.defaultView && document.defaultView.getComputedStyle) { try { var cs = elm.ownerDocument.defaultView.getComputedStyle(elm,""); } catch(e) { return false; } if (!cs) { return false; } return cs[prop]; } else { return elm.currentStyle[prop]; } }, set:function(elm, obj) { for (var p in obj) { var val = obj[p]; if (p == "opacity" && OZ.ie) { p = "filter"; val = "alpha(opacity="+Math.round(100*val)+")"; elm.style.zoom = 1; } else if (p == "float") { p = (OZ.ie ? "styleFloat" : "cssFloat"); } if (p in elm.style) { elm.style[p] = val; } } } }, Request:function(url, callback, options) { var o = {data:false, method:"get", headers:{}, xml:false} for (var p in options) { o[p] = options[p]; } o.method = o.method.toUpperCase(); var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else { return false; } xhr.open(o.method, url, true); xhr.onreadystatechange = function() { if (xhr.readyState != 4) { return; } if (!callback) { return; } var data = (o.xml ? xhr.responseXML : xhr.responseText); var headers = {}; var h = xhr.getAllResponseHeaders(); if (h) { h = h.split(/[\r\n]/); for (var i=0;i<h.length;i++) if (h[i]) { var v = h[i].match(/^([^:]+): *(.*)$/); headers[v[1]] = v[2]; } } callback(data,xhr.status,headers); }; if (o.method == "POST") { xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } for (var p in o.headers) { xhr.setRequestHeader(p,o.headers[p]); } xhr.send(o.data || null); return xhr; } } if (!Function.prototype.bind) { Function.prototype.bind = function(thisObj) { var fn = this; var args = Array.prototype.slice.call(arguments, 1); return function() { return fn.apply(thisObj, args.concat(Array.prototype.slice.call(arguments))); } } }; if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(item, from) { var len = this.length; var i = from || 0; if (i < 0) { i += len; } for (;i<len;i++) { if (i in this && this[i] === item) { return i; } } return -1; } } if (!Array.indexOf) { Array.indexOf = function(obj, item, from) { return Array.prototype.indexOf.call(obj, item, from); } } if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function(item, from) { var len = this.length; var i = from || len-1; if (i < 0) { i += len; } for (;i>-1;i--) { if (i in this && this[i] === item) { return i; } } return -1; } } if (!Array.lastIndexOf) { Array.lastIndexOf = function(obj, item, from) { return Array.prototype.lastIndexOf.call(obj, item, from); } } if (!Array.prototype.forEach) { Array.prototype.forEach = function(cb, _this) { var len = this.length; for (var i=0;i<len;i++) { if (i in this) { cb.call(_this, this[i], i, this); } } } } if (!Array.forEach) { Array.forEach = function(obj, cb, _this) { Array.prototype.forEach.call(obj, cb, _this); } } if (!Array.prototype.every) { Array.prototype.every = function(cb, _this) { var len = this.length; for (var i=0;i<len;i++) { if (i in this && !cb.call(_this, this[i], i, this)) { return false; } } return true; } } if (!Array.every) { Array.every = function(obj, cb, _this) { return Array.prototype.every.call(obj, cb, _this); } } if (!Array.prototype.some) { Array.prototype.some = function(cb, _this) { var len = this.length; for (var i=0;i<len;i++) { if (i in this && cb.call(_this, this[i], i, this)) { return true; } } return false; } } if (!Array.some) { Array.some = function(obj, cb, _this) { return Array.prototype.some.call(obj, cb, _this); } } if (!Array.prototype.map) { Array.prototype.map = function(cb, _this) { var len = this.length; var res = new Array(len); for (var i=0;i<len;i++) { if (i in this) { res[i] = cb.call(_this, this[i], i, this); } } return res; } } if (!Array.map) { Array.map = function(obj, cb, _this) { return Array.prototype.map.call(obj, cb, _this); } } if (!Array.prototype.filter) { Array.prototype.filter = function(cb, _this) { var len = this.length; var res = []; for (var i=0;i<len;i++) { if (i in this) { var val = this[i]; if (cb.call(_this, val, i, this)) { res.push(val); } } } return res; } } if (!Array.filter) { Array.filter = function(obj, cb, _this) { return Array.prototype.filter.call(obj, cb, _this); } }
JavaScript
function _(str) { /* getText */ if (!(str in window.LOCALE)) { return str; } return window.LOCALE[str]; } var DATATYPES = false; var LOCALE = {}; var SQL = {}; /* -------------------- base visual element -------------------- */ SQL.Visual = OZ.Class(); /* abstract parent */ SQL.Visual.prototype.init = function() { this._init(); this._build(); } SQL.Visual.prototype._init = function() { this.dom = { container: null, title: null }; this.data = { title:"" } } SQL.Visual.prototype._build = function() {} SQL.Visual.prototype.toXML = function() {} SQL.Visual.prototype.fromXML = function(node) {} SQL.Visual.prototype.destroy = function() { /* "destructor" */ var p = this.dom.container.parentNode; if (p && p.nodeType == 1) { p.removeChild(this.dom.container); } } SQL.Visual.prototype.setTitle = function(text) { if (!text) { return; } this.data.title = text; this.dom.title.innerHTML = text; } SQL.Visual.prototype.getTitle = function() { return this.data.title; } SQL.Visual.prototype.redraw = function() {} /* --------------------- table row ( = db column) ------------ */ SQL.Row = OZ.Class().extend(SQL.Visual); SQL.Row.prototype.init = function(owner, title, data) { this.owner = owner; this.relations = []; this.keys = []; this.selected = false; this.expanded = false; SQL.Visual.prototype.init.apply(this); this.data.type = 0; this.data.size = ""; this.data.def = null; this.data.nll = true; this.data.ai = false; this.data.comment = ""; if (data) { this.update(data); } this.setTitle(title); } SQL.Row.prototype._build = function() { this.dom.container = OZ.DOM.elm("tbody"); this.dom.content = OZ.DOM.elm("tr"); this.dom.selected = OZ.DOM.elm("div", {className:"selected",innerHTML:"&raquo;&nbsp;"}); this.dom.title = OZ.DOM.elm("div", {className:"title"}); var td1 = OZ.DOM.elm("td"); var td2 = OZ.DOM.elm("td", {className:"typehint"}); this.dom.typehint = td2; OZ.DOM.append( [this.dom.container, this.dom.content], [this.dom.content, td1, td2], [td1, this.dom.selected, this.dom.title] ); this.enter = this.bind(this.enter); this.changeComment = this.bind(this.changeComment); OZ.Event.add(this.dom.container, "click",this.bind(this.click)); OZ.Event.add(this.dom.container, "dblclick",this.bind(this.dblclick)); } SQL.Row.prototype.select = function() { if (this.selected) { return; } this.selected = true; this.redraw(); } SQL.Row.prototype.deselect = function() { if (!this.selected) { return; } this.selected = false; this.redraw(); this.collapse(); } SQL.Row.prototype.setTitle = function(t) { var old = this.getTitle(); for (var i=0;i<this.relations.length;i++) { var r = this.relations[i]; if (r.row1 != this) { continue; } var tt = r.row2.getTitle().replace(new RegExp(old,"g"),t); if (tt != r.row2.getTitle()) { r.row2.setTitle(tt); } } SQL.Visual.prototype.setTitle.apply(this, [t]); } SQL.Row.prototype.click = function(e) { /* clicked on row */ this.dispatch("rowclick", this); this.owner.owner.rowManager.select(this); } SQL.Row.prototype.dblclick = function(e) { /* dblclicked on row */ OZ.Event.prevent(e); OZ.Event.stop(e); this.expand(); } SQL.Row.prototype.update = function(data) { /* update subset of row data */ var des = SQL.Designer; if (data.nll && data.def && data.def.match(/^null$/i)) { data.def = null; } for (var p in data) { this.data[p] = data[p]; } if (!this.data.nll && this.data.def === null) { this.data.def = ""; } var elm = this.getDataType(); for (var i=0;i<this.relations.length;i++) { var r = this.relations[i]; if (r.row1 == this) { r.row2.update({type:des.getFKTypeFor(this.data.type),size:this.data.size}); } } this.redraw(); } SQL.Row.prototype.up = function() { /* shift up */ var r = this.owner.rows; var idx = r.indexOf(this); if (!idx) { return; } r[idx-1].dom.container.parentNode.insertBefore(this.dom.container,r[idx-1].dom.container); r.splice(idx,1); r.splice(idx-1,0,this); this.redraw(); } SQL.Row.prototype.down = function() { /* shift down */ var r = this.owner.rows; var idx = r.indexOf(this); if (idx+1 == this.owner.rows.length) { return; } r[idx].dom.container.parentNode.insertBefore(this.dom.container,r[idx+1].dom.container.nextSibling); r.splice(idx,1); r.splice(idx+1,0,this); this.redraw(); } SQL.Row.prototype.buildEdit = function() { OZ.DOM.clear(this.dom.container); var elms = []; this.dom.name = OZ.DOM.elm("input"); this.dom.name.type = "text"; elms.push(["name",this.dom.name]); OZ.Event.add(this.dom.name, "keypress", this.enter); this.dom.type = this.buildTypeSelect(this.data.type); elms.push(["type",this.dom.type]); this.dom.size = OZ.DOM.elm("input"); this.dom.size.type = "text"; elms.push(["size",this.dom.size]); this.dom.def = OZ.DOM.elm("input"); this.dom.def.type = "text"; elms.push(["def",this.dom.def]); this.dom.ai = OZ.DOM.elm("input"); this.dom.ai.type = "checkbox"; elms.push(["ai",this.dom.ai]); this.dom.nll = OZ.DOM.elm("input"); this.dom.nll.type = "checkbox"; elms.push(["null",this.dom.nll]); this.dom.comment = OZ.DOM.elm("span",{className:"comment"}); this.dom.comment.innerHTML = this.data.comment; this.dom.commentbtn = OZ.DOM.elm("input"); this.dom.commentbtn.type = "button"; this.dom.commentbtn.value = _("comment"); OZ.Event.add(this.dom.commentbtn, "click", this.changeComment); for (var i=0;i<elms.length;i++) { var row = elms[i]; var tr = OZ.DOM.elm("tr"); var td1 = OZ.DOM.elm("td"); var td2 = OZ.DOM.elm("td"); var l = OZ.DOM.text(_(row[0])+": "); OZ.DOM.append( [tr, td1, td2], [td1, l], [td2, row[1]] ); this.dom.container.appendChild(tr); } var tr = OZ.DOM.elm("tr"); var td1 = OZ.DOM.elm("td"); var td2 = OZ.DOM.elm("td"); OZ.DOM.append( [tr, td1, td2], [td1, this.dom.comment], [td2, this.dom.commentbtn] ); this.dom.container.appendChild(tr); } SQL.Row.prototype.changeComment = function(e) { var c = prompt(_("commenttext"),this.data.comment); if (c === null) { return; } this.data.comment = c; this.dom.comment.innerHTML = this.data.comment; } SQL.Row.prototype.expand = function() { if (this.expanded) { return; } this.expanded = true; this.buildEdit(); this.load(); this.redraw(); this.dom.name.focus(); this.dom.name.select(); } SQL.Row.prototype.collapse = function() { if (!this.expanded) { return; } this.expanded = false; var data = { type: this.dom.type.selectedIndex, def: this.dom.def.value, size: this.dom.size.value, nll: this.dom.nll.checked, ai: this.dom.ai.checked } OZ.DOM.clear(this.dom.container); this.dom.container.appendChild(this.dom.content); this.update(data); this.setTitle(this.dom.name.value); } SQL.Row.prototype.load = function() { /* put data to expanded form */ this.dom.name.value = this.getTitle(); var def = this.data.def; if (def === null) { def = "NULL"; } this.dom.def.value = def; this.dom.size.value = this.data.size; this.dom.nll.checked = this.data.nll; this.dom.ai.checked = this.data.ai; } SQL.Row.prototype.redraw = function() { var color = this.getColor(); this.dom.container.style.backgroundColor = color; OZ.DOM.removeClass(this.dom.title, "primary"); OZ.DOM.removeClass(this.dom.title, "key"); if (this.isPrimary()) { OZ.DOM.addClass(this.dom.title, "primary"); } if (this.isKey()) { OZ.DOM.addClass(this.dom.title, "key"); } this.dom.selected.style.display = (this.selected ? "" : "none"); this.dom.container.title = this.data.comment; var typehint = []; if (this.owner.owner.getOption("showtype")) { var elm = this.getDataType(); typehint.push(elm.getAttribute("sql")); } if (this.owner.owner.getOption("showsize") && this.data.size) { typehint.push("(" + this.data.size + ")"); } this.dom.typehint.innerHTML = typehint.join(" "); this.owner.redraw(); this.owner.owner.rowManager.redraw(); } SQL.Row.prototype.addRelation = function(r) { this.relations.push(r); } SQL.Row.prototype.removeRelation = function(r) { var idx = this.relations.indexOf(r); if (idx == -1) { return; } this.relations.splice(idx,1); } SQL.Row.prototype.addKey = function(k) { this.keys.push(k); this.redraw(); } SQL.Row.prototype.removeKey = function(k) { var idx = this.keys.indexOf(k); if (idx == -1) { return; } this.keys.splice(idx,1); this.redraw(); } SQL.Row.prototype.getDataType = function() { var type = this.data.type; var elm = DATATYPES.getElementsByTagName("type")[type]; return elm; } SQL.Row.prototype.getColor = function() { var elm = this.getDataType(); var g = this.getDataType().parentNode; return elm.getAttribute("color") || g.getAttribute("color") || "#fff"; } SQL.Row.prototype.buildTypeSelect = function(id) { /* build selectbox with avail datatypes */ var s = OZ.DOM.elm("select"); var gs = DATATYPES.getElementsByTagName("group"); for (var i=0;i<gs.length;i++) { var g = gs[i]; var og = OZ.DOM.elm("optgroup"); og.style.backgroundColor = g.getAttribute("color") || "#fff"; og.label = g.getAttribute("label"); s.appendChild(og); var ts = g.getElementsByTagName("type"); for (var j=0;j<ts.length;j++) { var t = ts[j]; var o = OZ.DOM.elm("option"); if (t.getAttribute("color")) { o.style.backgroundColor = t.getAttribute("color"); } if (t.getAttribute("note")) { o.title = t.getAttribute("note"); } o.innerHTML = t.getAttribute("label"); og.appendChild(o); } } s.selectedIndex = id; return s; } SQL.Row.prototype.destroy = function() { SQL.Visual.prototype.destroy.apply(this); while (this.relations.length) { this.owner.owner.removeRelation(this.relations[0]); } for (var i=0;i<this.keys.length;i++){ this.keys[i].removeRow(this); } } SQL.Row.prototype.toXML = function() { var xml = ""; var t = this.getTitle().replace(/"/g,"&quot;"); var nn = (this.data.nll ? "1" : "0"); var ai = (this.data.ai ? "1" : "0"); xml += '<row name="'+t+'" null="'+nn+'" autoincrement="'+ai+'">\n'; var elm = this.getDataType(); var t = elm.getAttribute("sql"); if (this.data.size.length) { t += "("+this.data.size+")"; } xml += "<datatype>"+t+"</datatype>\n"; if (this.data.def || this.data.def === null) { var q = elm.getAttribute("quote"); var d = this.data.def; if (d === null) { d = "NULL"; } else if (d != "CURRENT_TIMESTAMP") { d = q+d+q; } xml += "<default>"+d+"</default>"; } for (var i=0;i<this.relations.length;i++) { var r = this.relations[i]; if (r.row2 != this) { continue; } xml += '<relation table="'+r.row1.owner.getTitle()+'" row="'+r.row1.getTitle()+'" />\n'; } if (this.data.comment) { var escaped = this.data.comment.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;"); xml += "<comment>"+escaped+"</comment>\n"; } xml += "</row>\n"; return xml; } SQL.Row.prototype.fromXML = function(node) { var name = node.getAttribute("name"); var obj = { type:0, size:"" }; obj.nll = (node.getAttribute("null") == "1"); obj.ai = (node.getAttribute("autoincrement") == "1"); var cs = node.getElementsByTagName("comment"); if (cs.length && cs[0].firstChild) { obj.comment = cs[0].firstChild.nodeValue; } var d = node.getElementsByTagName("datatype"); if (d.length && d[0].firstChild) { var s = d[0].firstChild.nodeValue; var r = s.match(/^([^\(]+)(\((.*)\))?.*$/); var type = r[1]; if (r[3]) { obj.size = r[3]; } var types = window.DATATYPES.getElementsByTagName("type"); for (var i=0;i<types.length;i++) { var sql = types[i].getAttribute("sql"); var re = types[i].getAttribute("re"); if (sql == type || (re && new RegExp(re).exec(type)) ) { obj.type = i; } } } var elm = DATATYPES.getElementsByTagName("type")[obj.type]; var d = node.getElementsByTagName("default"); if (d.length && d[0].firstChild) { var def = d[0].firstChild.nodeValue; obj.def = def; var q = elm.getAttribute("quote"); if (q) { var re = new RegExp("^"+q+"(.*)"+q+"$"); var r = def.match(re); if (r) { obj.def = r[1]; } } } this.update(obj); this.setTitle(name); } SQL.Row.prototype.isPrimary = function() { for (var i=0;i<this.keys.length;i++) { var k = this.keys[i]; if (k.getType() == "PRIMARY") { return true; } } return false; } SQL.Row.prototype.isUnique = function() { for (var i=0;i<this.keys.length;i++) { var k = this.keys[i]; var t = k.getType(); if (t == "PRIMARY" || t == "UNIQUE") { return true; } } return false; } SQL.Row.prototype.isKey = function() { return this.keys.length > 0; } SQL.Row.prototype.enter = function(e) { if (e.keyCode == 13) { this.collapse(); } } /* --------------------------- relation (connector) ----------- */ SQL.Relation = OZ.Class().extend(SQL.Visual); SQL.Relation._counter = 0; SQL.Relation.prototype.init = function(owner, row1, row2) { this.owner = owner; this.row1 = row1; this.row2 = row2; this.color = "#000"; this.hidden = false; SQL.Visual.prototype.init.apply(this); /* if one of the rows already has relations, inherit color */ var all = row1.relations.concat(row2.relations); if (all.length) { /* inherit */ this.color = all[0].getColor(); } else if (CONFIG.RELATION_COLORS) { /* pick next */ this.constructor._counter++; var colorIndex = this.constructor._counter - 1; this.color = CONFIG.RELATION_COLORS[colorIndex % CONFIG.RELATION_COLORS.length]; } this.row1.addRelation(this); this.row2.addRelation(this); this.dom = []; if (this.owner.vector) { var path = document.createElementNS(this.owner.svgNS, "path"); path.setAttribute("stroke", this.color); path.setAttribute("stroke-width", CONFIG.RELATION_THICKNESS); path.setAttribute("fill", "none"); this.owner.dom.svg.appendChild(path); this.dom.push(path); } else { for (var i=0;i<3;i++) { var div = OZ.DOM.elm("div",{position:"absolute",className:"relation",backgroundColor:color}); this.dom.push(div); if (i & 1) { /* middle */ OZ.Style.set(div, {width:CONFIG.RELATION_THICKNESS+"px"}); } else { /* first & last */ OZ.Style.set(div, {height:CONFIG.RELATION_THICKNESS+"px"}); } this.owner.dom.container.appendChild(div); } } this.redraw(); } SQL.Relation.prototype.getColor = function() { return this.color; } SQL.Relation.prototype.show = function() { this.hidden = false; for (var i=0;i<this.dom.length;i++) { this.dom[i].style.visibility = ""; } } SQL.Relation.prototype.hide = function() { this.hidden = true; for (var i=0;i<this.dom.length;i++) { this.dom[i].style.visibility = "hidden"; } } SQL.Relation.prototype.redrawNormal = function(p1, p2, half) { if (this.owner.vector) { var str = "M "+p1[0]+" "+p1[1]+" C "+(p1[0] + half)+" "+p1[1]+" "; str += (p2[0]-half)+" "+p2[1]+" "+p2[0]+" "+p2[1]; this.dom[0].setAttribute("d",str); } else { this.dom[0].style.left = p1[0]+"px"; this.dom[0].style.top = p1[1]+"px"; this.dom[0].style.width = half+"px"; this.dom[1].style.left = (p1[0] + half) + "px"; this.dom[1].style.top = Math.min(p1[1],p2[1]) + "px"; this.dom[1].style.height = (Math.abs(p1[1] - p2[1])+CONFIG.RELATION_THICKNESS)+"px"; this.dom[2].style.left = (p1[0]+half+1)+"px"; this.dom[2].style.top = p2[1]+"px"; this.dom[2].style.width = half+"px"; } } SQL.Relation.prototype.redrawSide = function(p1, p2, x) { if (this.owner.vector) { var str = "M "+p1[0]+" "+p1[1]+" C "+x+" "+p1[1]+" "; str += x+" "+p2[1]+" "+p2[0]+" "+p2[1]; this.dom[0].setAttribute("d",str); } else { this.dom[0].style.left = Math.min(x,p1[0])+"px"; this.dom[0].style.top = p1[1]+"px"; this.dom[0].style.width = Math.abs(p1[0]-x)+"px"; this.dom[1].style.left = x+"px"; this.dom[1].style.top = Math.min(p1[1],p2[1]) + "px"; this.dom[1].style.height = (Math.abs(p1[1] - p2[1])+CONFIG.RELATION_THICKNESS)+"px"; this.dom[2].style.left = Math.min(x,p2[0])+"px"; this.dom[2].style.top = p2[1]+"px"; this.dom[2].style.width = Math.abs(p2[0]-x)+"px"; } } SQL.Relation.prototype.redraw = function() { /* draw connector */ if (this.hidden) { return; } var t1 = this.row1.owner.dom.container; var t2 = this.row2.owner.dom.container; var l1 = t1.offsetLeft; var l2 = t2.offsetLeft; var r1 = l1 + t1.offsetWidth; var r2 = l2 + t2.offsetWidth; var t1 = t1.offsetTop + this.row1.dom.container.offsetTop + Math.round(this.row1.dom.container.offsetHeight/2); var t2 = t2.offsetTop + this.row2.dom.container.offsetTop + Math.round(this.row2.dom.container.offsetHeight/2); if (this.row1.owner.selected) { t1++; l1++; r1--; } if (this.row2.owner.selected) { t2++; l2++; r2--; } var p1 = [0,0]; var p2 = [0,0]; if (r1 < l2 || r2 < l1) { /* between tables */ if (Math.abs(r1 - l2) < Math.abs(r2 - l1)) { p1 = [r1,t1]; p2 = [l2,t2]; } else { p1 = [r2,t2]; p2 = [l1,t1]; } var half = Math.floor((p2[0] - p1[0])/2); this.redrawNormal(p1, p2, half); } else { /* next to tables */ var x = 0; var l = 0; if (Math.abs(l1 - l2) < Math.abs(r1 - r2)) { /* left of tables */ p1 = [l1,t1]; p2 = [l2,t2]; x = Math.min(l1,l2) - CONFIG.RELATION_SPACING; } else { /* right of tables */ p1 = [r1,t1]; p2 = [r2,t2]; x = Math.max(r1,r2) + CONFIG.RELATION_SPACING; } this.redrawSide(p1, p2, x); } /* line next to tables */ } SQL.Relation.prototype.destroy = function() { this.row1.removeRelation(this); this.row2.removeRelation(this); for (var i=0;i<this.dom.length;i++) { this.dom[i].parentNode.removeChild(this.dom[i]); } } /* --------------------- db table ------------ */ SQL.Table = OZ.Class().extend(SQL.Visual); SQL.Table.prototype.init = function(owner, name, x, y, z) { this.owner = owner; this.rows = []; this.keys = []; this.zIndex = 0; this._ec = []; this.flag = false; this.selected = false; SQL.Visual.prototype.init.apply(this); this.data.comment = ""; this.setTitle(name); this.x = x || 0; this.y = y || 0; this.setZ(z); this.snap(); } SQL.Table.prototype._build = function() { this.dom.container = OZ.DOM.elm("div", {className:"table"}); this.dom.content = OZ.DOM.elm("table"); var thead = OZ.DOM.elm("thead"); var tr = OZ.DOM.elm("tr"); this.dom.title = OZ.DOM.elm("td", {className:"title", colSpan:2}); OZ.DOM.append( [this.dom.container, this.dom.content], [this.dom.content, thead], [thead, tr], [tr, this.dom.title] ); this.dom.mini = OZ.DOM.elm("div", {className:"mini"}); this.owner.map.dom.container.appendChild(this.dom.mini); this._ec.push(OZ.Event.add(this.dom.container, "click", this.bind(this.click))); this._ec.push(OZ.Event.add(this.dom.container, "dblclick", this.bind(this.dblclick))); this._ec.push(OZ.Event.add(this.dom.container, "mousedown", this.bind(this.down))); this._ec.push(OZ.Event.add(this.dom.container, "touchstart", this.bind(this.down))); this._ec.push(OZ.Event.add(this.dom.container, "touchmove", OZ.Event.prevent)); } SQL.Table.prototype.setTitle = function(t) { var old = this.getTitle(); for (var i=0;i<this.rows.length;i++) { var row = this.rows[i]; for (var j=0;j<row.relations.length;j++) { var r = row.relations[j]; if (r.row1 != row) { continue; } var tt = row.getTitle().replace(new RegExp(old,"g"),t); if (tt != row.getTitle()) { row.setTitle(tt); } } } SQL.Visual.prototype.setTitle.apply(this, [t]); } SQL.Table.prototype.getRelations = function() { var arr = []; for (var i=0;i<this.rows.length;i++) { var row = this.rows[i]; for (var j=0;j<row.relations.length;j++) { var r = row.relations[j]; if (arr.indexOf(r) == -1) { arr.push(r); } } } return arr; } SQL.Table.prototype.showRelations = function() { var rs = this.getRelations(); for (var i=0;i<rs.length;i++) { rs[i].show(); } } SQL.Table.prototype.hideRelations = function() { var rs = this.getRelations(); for (var i=0;i<rs.length;i++) { rs[i].hide(); } } SQL.Table.prototype.click = function(e) { OZ.Event.stop(e); var t = OZ.Event.target(e); this.owner.tableManager.select(this); if (t != this.dom.title) { return; } /* click on row */ this.dispatch("tableclick",this); this.owner.rowManager.select(false); } SQL.Table.prototype.dblclick = function(e) { var t = OZ.Event.target(e); if (t == this.dom.title) { this.owner.tableManager.edit(); } } SQL.Table.prototype.select = function() { if (this.selected) { return; } this.selected = true; OZ.DOM.addClass(this.dom.container, "selected"); OZ.DOM.addClass(this.dom.mini, "mini_selected"); this.redraw(); } SQL.Table.prototype.deselect = function() { if (!this.selected) { return; } this.selected = false; OZ.DOM.removeClass(this.dom.container, "selected"); OZ.DOM.removeClass(this.dom.mini, "mini_selected"); this.redraw(); } SQL.Table.prototype.addRow = function(title, data) { var r = new SQL.Row(this, title, data); this.rows.push(r); this.dom.content.appendChild(r.dom.container); this.redraw(); return r; } SQL.Table.prototype.removeRow = function(r) { var idx = this.rows.indexOf(r); if (idx == -1) { return; } r.destroy(); this.rows.splice(idx,1); this.redraw(); } SQL.Table.prototype.addKey = function(name) { var k = new SQL.Key(this, name); this.keys.push(k); return k; } SQL.Table.prototype.removeKey = function(i) { var idx = this.keys.indexOf(k); if (idx == -1) { return; } k.destroy(); this.keys.splice(idx,1); } SQL.Table.prototype.redraw = function() { var x = this.x; var y = this.y; if (this.selected) { x--; y--; } this.dom.container.style.left = x+"px"; this.dom.container.style.top = y+"px"; var ratioX = this.owner.map.width / this.owner.width; var ratioY = this.owner.map.height / this.owner.height; var w = this.dom.container.offsetWidth * ratioX; var h = this.dom.container.offsetHeight * ratioY; var x = this.x * ratioX; var y = this.y * ratioY; this.dom.mini.style.width = Math.round(w)+"px"; this.dom.mini.style.height = Math.round(h)+"px"; this.dom.mini.style.left = Math.round(x)+"px"; this.dom.mini.style.top = Math.round(y)+"px"; this.width = this.dom.container.offsetWidth; this.height = this.dom.container.offsetHeight; var rs = this.getRelations(); for (var i=0;i<rs.length;i++) { rs[i].redraw(); } } SQL.Table.prototype.moveBy = function(dx, dy) { this.x += dx; this.y += dy; this.snap(); this.redraw(); } SQL.Table.prototype.moveTo = function(x, y) { this.x = x; this.y = y; this.snap(); this.redraw(); } SQL.Table.prototype.snap = function() { var snap = parseInt(SQL.Designer.getOption("snap")); if (snap) { this.x = Math.round(this.x / snap) * snap; this.y = Math.round(this.y / snap) * snap; } } SQL.Table.prototype.down = function(e) { /* mousedown - start drag */ OZ.Event.stop(e); var t = OZ.Event.target(e); if (t != this.dom.title) { return; } /* on a row */ /* touch? */ if (e.type == "touchstart") { var event = e.touches[0]; var moveEvent = "touchmove"; var upEvent = "touchend"; } else { var event = e; var moveEvent = "mousemove"; var upEvent = "mouseup"; } /* a non-shift click within a selection preserves the selection */ if (e.shiftKey || ! this.selected) { this.owner.tableManager.select(this, e.shiftKey); } var t = SQL.Table; t.active = this.owner.tableManager.selection; var n = t.active.length; t.x = new Array(n); t.y = new Array(n); for (var i=0;i<n;i++) { /* position relative to mouse cursor */ t.x[i] = t.active[i].x - event.clientX; t.y[i] = t.active[i].y - event.clientY; } if (this.owner.getOption("hide")) { for (var i=0;i<n;i++) { t.active[i].hideRelations(); } } this.documentMove = OZ.Event.add(document, moveEvent, this.bind(this.move)); this.documentUp = OZ.Event.add(document, upEvent, this.bind(this.up)); } SQL.Table.prototype.toXML = function() { var t = this.getTitle().replace(/"/g,"&quot;"); var xml = ""; xml += '<table x="'+this.x+'" y="'+this.y+'" name="'+t+'">\n'; for (var i=0;i<this.rows.length;i++) { xml += this.rows[i].toXML(); } for (var i=0;i<this.keys.length;i++) { xml += this.keys[i].toXML(); } var c = this.getComment(); if (c) { c = c.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;"); xml += "<comment>"+c+"</comment>\n"; } xml += "</table>\n"; return xml; } SQL.Table.prototype.fromXML = function(node) { var name = node.getAttribute("name"); this.setTitle(name); var x = parseInt(node.getAttribute("x")) || 0; var y = parseInt(node.getAttribute("y")) || 0; this.moveTo(x, y); var rows = node.getElementsByTagName("row"); for (var i=0;i<rows.length;i++) { var row = rows[i]; var r = this.addRow(""); r.fromXML(row); } var keys = node.getElementsByTagName("key"); for (var i=0;i<keys.length;i++) { var key = keys[i]; var k = this.addKey(); k.fromXML(key); } for (var i=0;i<node.childNodes.length;i++) { var ch = node.childNodes[i]; if (ch.tagName && ch.tagName.toLowerCase() == "comment" && ch.firstChild) { this.setComment(ch.firstChild.nodeValue); } } } SQL.Table.prototype.getZ = function() { return this.zIndex; } SQL.Table.prototype.setZ = function(z) { this.zIndex = z; this.dom.container.style.zIndex = z; } SQL.Table.prototype.findNamedRow = function(n) { /* return row with a given name */ for (var i=0;i<this.rows.length;i++) { if (this.rows[i].getTitle() == n) { return this.rows[i]; } } return false; } SQL.Table.prototype.addKey = function(type, name) { var i = new SQL.Key(this, type, name); this.keys.push(i); return i; } SQL.Table.prototype.removeKey = function(i) { var idx = this.keys.indexOf(i); if (idx == -1) { return; } i.destroy(); this.keys.splice(idx,1); } SQL.Table.prototype.setComment = function(c) { this.data.comment = c; this.dom.title.title = this.data.comment; } SQL.Table.prototype.getComment = function() { return this.data.comment; } SQL.Table.prototype.move = function(e) { /* mousemove */ var t = SQL.Table; SQL.Designer.removeSelection(); if (e.type == "touchmove") { if (e.touches.length > 1) { return; } var event = e.touches[0]; } else { var event = e; } for (var i=0;i<t.active.length;i++) { var x = t.x[i] + event.clientX; var y = t.y[i] + event.clientY; x = Math.max(x, 0); y = Math.max(y, 0); t.active[i].moveTo(x,y); } } SQL.Table.prototype.up = function(e) { var t = SQL.Table; var d = SQL.Designer; if (d.getOption("hide")) { for (var i=0;i<t.active.length;i++) { t.active[i].showRelations(); t.active[i].redraw(); } } t.active = false; OZ.Event.remove(this.documentMove); OZ.Event.remove(this.documentUp); this.owner.sync(); } SQL.Table.prototype.destroy = function() { SQL.Visual.prototype.destroy.apply(this); this.dom.mini.parentNode.removeChild(this.dom.mini); while (this.rows.length) { this.removeRow(this.rows[0]); } this._ec.forEach(OZ.Event.remove, OZ.Event); } /* --------------------- db index ------------ */ SQL.Key = OZ.Class().extend(SQL.Visual); SQL.Key.prototype.init = function(owner, type, name) { this.owner = owner; this.rows = []; this.type = type || "INDEX"; this.name = name || ""; SQL.Visual.prototype.init.apply(this); } SQL.Key.prototype.setName = function(n) { this.name = n; } SQL.Key.prototype.getName = function() { return this.name; } SQL.Key.prototype.setType = function(t) { if (!t) { return; } this.type = t; for (var i=0;i<this.rows.length;i++) { this.rows[i].redraw(); } } SQL.Key.prototype.getType = function() { return this.type; } SQL.Key.prototype.addRow = function(r) { if (r.owner != this.owner) { return; } this.rows.push(r); r.addKey(this); } SQL.Key.prototype.removeRow = function(r) { var idx = this.rows.indexOf(r); if (idx == -1) { return; } r.removeKey(this); this.rows.splice(idx,1); } SQL.Key.prototype.destroy = function() { for (var i=0;i<this.rows.length;i++) { this.rows[i].removeKey(this); } } SQL.Key.prototype.getLabel = function() { return this.name || this.type; } SQL.Key.prototype.toXML = function() { var xml = ""; xml += '<key type="'+this.getType()+'" name="'+this.getName()+'">\n'; for (var i=0;i<this.rows.length;i++) { var r = this.rows[i]; xml += '<part>'+r.getTitle()+'</part>\n'; } xml += '</key>\n'; return xml; } SQL.Key.prototype.fromXML = function(node) { this.setType(node.getAttribute("type")); this.setName(node.getAttribute("name")); var parts = node.getElementsByTagName("part"); for (var i=0;i<parts.length;i++) { var name = parts[i].firstChild.nodeValue; var row = this.owner.findNamedRow(name); this.addRow(row); } } /* --------------------- rubberband -------------------- */ SQL.Rubberband = OZ.Class().extend(SQL.Visual); SQL.Rubberband.prototype.init = function(owner) { this.owner = owner; SQL.Visual.prototype.init.apply(this); this.dom.container = OZ.$("rubberband"); OZ.Event.add("area", "mousedown", this.bind(this.down)); } SQL.Rubberband.prototype.down = function(e) { OZ.Event.prevent(e); var scroll = OZ.DOM.scroll(); this.x = this.x0 = e.clientX + scroll[0]; this.y = this.y0 = e.clientY + scroll[1]; this.width = 0; this.height = 0; this.redraw(); this.documentMove = OZ.Event.add(document, "mousemove", this.bind(this.move)); this.documentUp = OZ.Event.add(document, "mouseup", this.bind(this.up)); } SQL.Rubberband.prototype.move = function(e) { var scroll = OZ.DOM.scroll(); var x = e.clientX + scroll[0]; var y = e.clientY + scroll[1]; this.width = Math.abs(x-this.x0); this.height = Math.abs(y-this.y0); if (x<this.x0) { this.x = x; } else { this.x = this.x0; } if (y<this.y0) { this.y = y; } else { this.y = this.y0; } this.redraw(); this.dom.container.style.visibility = "visible"; } SQL.Rubberband.prototype.up = function(e) { OZ.Event.prevent(e); this.dom.container.style.visibility = "hidden"; OZ.Event.remove(this.documentMove); OZ.Event.remove(this.documentUp); this.owner.tableManager.selectRect(this.x, this.y, this.width, this.height); } SQL.Rubberband.prototype.redraw = function() { this.dom.container.style.left = this.x+"px"; this.dom.container.style.top = this.y+"px"; this.dom.container.style.width = this.width+"px"; this.dom.container.style.height = this.height+"px"; } /* --------------------- minimap ------------ */ SQL.Map = OZ.Class().extend(SQL.Visual); SQL.Map.prototype.init = function(owner) { this.owner = owner; SQL.Visual.prototype.init.apply(this); this.dom.container = OZ.$("minimap"); this.width = this.dom.container.offsetWidth - 2; this.height = this.dom.container.offsetHeight - 2; this.dom.port = OZ.DOM.elm("div",{className:"port", zIndex:1}); this.dom.container.appendChild(this.dom.port); this.sync = this.bind(this.sync); this.flag = false; this.sync(); OZ.Event.add(window, "resize", this.sync); OZ.Event.add(window, "scroll", this.sync); OZ.Event.add(this.dom.container, "mousedown", this.bind(this.down)); OZ.Event.add(this.dom.container, "touchstart", this.bind(this.down)); OZ.Event.add(this.dom.container, "touchmove", OZ.Event.prevent); } SQL.Map.prototype.down = function(e) { /* mousedown - move view and start drag */ this.flag = true; this.dom.container.style.cursor = "move"; var pos = OZ.DOM.pos(this.dom.container); this.x = Math.round(pos[0] + this.l + this.w/2); this.y = Math.round(pos[1] + this.t + this.h/2); this.move(e); if (e.type == "touchstart") { var eventMove = "touchmove"; var eventUp = "touchend"; } else { var eventMove = "mousemove"; var eventUp = "mouseup"; } this.documentMove = OZ.Event.add(document, eventMove, this.bind(this.move)); this.documentUp = OZ.Event.add(document, eventUp, this.bind(this.up)); } SQL.Map.prototype.move = function(e) { /* mousemove */ if (!this.flag) { return; } OZ.Event.prevent(e); if (e.type.match(/touch/)) { if (e.touches.length > 1) { return; } var event = e.touches[0]; } else { var event = e; } var dx = event.clientX - this.x; var dy = event.clientY - this.y; if (this.l + dx < 0) { dx = -this.l; } if (this.t + dy < 0) { dy = -this.t; } if (this.l + this.w + 4 + dx > this.width) { dx = this.width - 4 - this.l - this.w; } if (this.t + this.h + 4 + dy > this.height) { dy = this.height - 4 - this.t - this.h; } this.x += dx; this.y += dy; this.l += dx; this.t += dy; var coefX = this.width / this.owner.width; var coefY = this.height / this.owner.height; var left = this.l / coefX; var top = this.t / coefY; if (OZ.webkit) { document.body.scrollLeft = Math.round(left); document.body.scrollTop = Math.round(top); } else { document.documentElement.scrollLeft = Math.round(left); document.documentElement.scrollTop = Math.round(top); } this.redraw(); } SQL.Map.prototype.up = function(e) { /* mouseup */ this.flag = false; this.dom.container.style.cursor = ""; OZ.Event.remove(this.documentMove); OZ.Event.remove(this.documentUp); } SQL.Map.prototype.sync = function() { /* when window changes, adjust map */ var dims = OZ.DOM.win(); var scroll = OZ.DOM.scroll(); var scaleX = this.width / this.owner.width; var scaleY = this.height / this.owner.height; var w = dims[0] * scaleX - 4 - 0; var h = dims[1] * scaleY - 4 - 0; var x = scroll[0] * scaleX; var y = scroll[1] * scaleY; this.w = Math.round(w); this.h = Math.round(h); this.l = Math.round(x); this.t = Math.round(y); this.redraw(); } SQL.Map.prototype.redraw = function() { this.dom.port.style.width = this.w+"px"; this.dom.port.style.height = this.h+"px"; this.dom.port.style.left = this.l+"px"; this.dom.port.style.top = this.t+"px"; } /* --------------------- io ------------ */ SQL.IO = OZ.Class(); SQL.IO.prototype.init = function(owner) { this.owner = owner; this._name = ""; /* last used keyword */ this.dom = { container:OZ.$("io") }; var ids = ["saveload","clientlocalsave", "clientsave", "clientlocalload","clientload", "clientsql", "quicksave", "serversave", "serverload", "serverlist", "serverimport"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); this.dom[id] = elm; elm.value = _(id); } this.dom.quicksave.value += " (F2)"; var ids = ["client","server","output","backendlabel"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); elm.innerHTML = _(id); } this.dom.ta = OZ.$("textarea"); this.dom.backend = OZ.$("backend"); this.dom.container.parentNode.removeChild(this.dom.container); this.dom.container.style.visibility = ""; this.saveresponse = this.bind(this.saveresponse); this.loadresponse = this.bind(this.loadresponse); this.listresponse = this.bind(this.listresponse); this.importresponse = this.bind(this.importresponse); OZ.Event.add(this.dom.saveload, "click", this.bind(this.click)); OZ.Event.add(this.dom.clientlocalsave, "click", this.bind(this.clientlocalsave)); OZ.Event.add(this.dom.clientsave, "click", this.bind(this.clientsave)); OZ.Event.add(this.dom.clientlocalload, "click", this.bind(this.clientlocalload)); OZ.Event.add(this.dom.clientload, "click", this.bind(this.clientload)); OZ.Event.add(this.dom.clientsql, "click", this.bind(this.clientsql)); OZ.Event.add(this.dom.quicksave, "click", this.bind(this.quicksave)); OZ.Event.add(this.dom.serversave, "click", this.bind(this.serversave)); OZ.Event.add(this.dom.serverload, "click", this.bind(this.serverload)); OZ.Event.add(this.dom.serverlist, "click", this.bind(this.serverlist)); OZ.Event.add(this.dom.serverimport, "click", this.bind(this.serverimport)); OZ.Event.add(document, "keydown", this.bind(this.press)); this.build(); } SQL.IO.prototype.build = function() { OZ.DOM.clear(this.dom.backend); var bs = CONFIG.AVAILABLE_BACKENDS; var be = CONFIG.DEFAULT_BACKEND; var r = window.location.search.substring(1).match(/backend=([^&]*)/); if (r) { req = r[1]; if (bs.indexOf(req) != -1) { be = req; } } for (var i=0;i<bs.length;i++) { var o = OZ.DOM.elm("option"); o.value = bs[i]; o.innerHTML = bs[i]; this.dom.backend.appendChild(o); if (bs[i] == be) { this.dom.backend.selectedIndex = i; } } } SQL.IO.prototype.click = function() { /* open io dialog */ this.build(); this.dom.ta.value = ""; this.dom.clientsql.value = _("clientsql") + " (" + window.DATATYPES.getAttribute("db") + ")"; this.owner.window.open(_("saveload"),this.dom.container); } SQL.IO.prototype.fromXML = function(xmlDoc) { if (!xmlDoc || !xmlDoc.documentElement) { alert(_("xmlerror")+': Null document'); return false; } this.owner.fromXML(xmlDoc.documentElement); this.owner.window.close(); return true; } SQL.IO.prototype.clientsave = function() { var xml = this.owner.toXML(); this.dom.ta.value = xml; } SQL.IO.prototype.clientload = function() { var xml = this.dom.ta.value; if (!xml) { alert(_("empty")); return; } try { if (window.DOMParser) { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xml, "text/xml"); } else if (window.ActiveXObject) { var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(xml); } else { throw new Error("No XML parser available."); } } catch(e) { alert(_("xmlerror")+': '+e.message); return; } this.fromXML(xmlDoc); } SQL.IO.prototype.clientlocalsave = function() { if (!window.localStorage) { alert("Sorry, your browser does not seem to support localStorage."); return; } var xml = this.owner.toXML(); if (xml.length >= (5*1024*1024)/2) { /* this is a very big db structure... */ alert("Warning: your database structure is above 5 megabytes in size, this is above the localStorage single key limit allowed by some browsers, example Mozilla Firefox 10"); return; } var key = prompt(_("serversaveprompt"), this._name); if (key === null) { return; } key = "wwwsqldesigner_databases_" + (key || "default"); try { localStorage.setItem(key, xml); if (localStorage.getItem(key) != xml) { throw new Error("Content verification failed"); } } catch (e) { alert("Error saving database structure to localStorage! ("+e.message+")"); } } SQL.IO.prototype.clientlocalload = function() { if (!window.localStorage) { alert("Sorry, your browser does not seem to support localStorage."); return; } var key = prompt(_("serverloadprompt"), this._name); if (key === null) { return; } key = "wwwsqldesigner_databases_" + (key || "default"); try { var xml = localStorage.getItem(key); if (!xml) { throw new Error("No data available"); } } catch (e) { alert("Error loading database structure from localStorage! ("+e.message+")"); return; } try { if (window.DOMParser) { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xml, "text/xml"); } else if (window.ActiveXObject) { var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(xml); } else { throw new Error("No XML parser available."); } } catch(e) { alert(_("xmlerror")+': '+e.message); return; } this.fromXML(xmlDoc); } SQL.IO.prototype.clientsql = function() { var bp = this.owner.getOption("staticpath"); var path = bp + "db/"+window.DATATYPES.getAttribute("db")+"/output.xsl"; this.owner.window.showThrobber(); OZ.Request(path, this.bind(this.finish), {xml:true}); } SQL.IO.prototype.finish = function(xslDoc) { this.owner.window.hideThrobber(); var xml = this.owner.toXML(); var sql = ""; try { if (window.XSLTProcessor && window.DOMParser) { var parser = new DOMParser(); var xmlDoc = parser.parseFromString(xml, "text/xml"); var xsl = new XSLTProcessor(); xsl.importStylesheet(xslDoc); var result = xsl.transformToDocument(xmlDoc); sql = result.documentElement.textContent; } else if (window.ActiveXObject) { var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.loadXML(xml); sql = xmlDoc.transformNode(xslDoc); } else { throw new Error("No XSLT processor available"); } } catch(e) { alert(_("xmlerror")+': '+e.message); return; } this.dom.ta.value = sql; } SQL.IO.prototype.serversave = function(e, keyword) { var name = keyword || prompt(_("serversaveprompt"), this._name); if (!name) { return; } this._name = name; var xml = this.owner.toXML(); var bp = this.owner.getOption("xhrpath"); var url = bp + "backend/"+this.dom.backend.value+"/?action=save&keyword="+encodeURIComponent(name); var h = {"Content-type":"application/xml"}; this.owner.window.showThrobber(); this.owner.setTitle(name); OZ.Request(url, this.saveresponse, {xml:true, method:"post", data:xml, headers:h}); } SQL.IO.prototype.quicksave = function(e) { this.serversave(e, this._name); } SQL.IO.prototype.serverload = function(e, keyword) { var name = keyword || prompt(_("serverloadprompt"), this._name); if (!name) { return; } this._name = name; var bp = this.owner.getOption("xhrpath"); var url = bp + "backend/"+this.dom.backend.value+"/?action=load&keyword="+encodeURIComponent(name); this.owner.window.showThrobber(); this.name = name; OZ.Request(url, this.loadresponse, {xml:true}); } SQL.IO.prototype.serverlist = function(e) { var bp = this.owner.getOption("xhrpath"); var url = bp + "backend/"+this.dom.backend.value+"/?action=list"; this.owner.window.showThrobber(); OZ.Request(url, this.listresponse); } SQL.IO.prototype.serverimport = function(e) { var name = prompt(_("serverimportprompt"), ""); if (!name) { return; } var bp = this.owner.getOption("xhrpath"); var url = bp + "backend/"+this.dom.backend.value+"/?action=import&database="+name; this.owner.window.showThrobber(); OZ.Request(url, this.importresponse, {xml:true}); } SQL.IO.prototype.check = function(code) { switch (code) { case 201: case 404: case 500: case 501: case 503: var lang = "http"+code; this.dom.ta.value = _("httpresponse")+": "+_(lang); return false; break; default: return true; } } SQL.IO.prototype.saveresponse = function(data, code) { this.owner.window.hideThrobber(); this.check(code); } SQL.IO.prototype.loadresponse = function(data, code) { this.owner.window.hideThrobber(); if (!this.check(code)) { return; } this.fromXML(data); this.owner.setTitle(this.name); } SQL.IO.prototype.listresponse = function(data, code) { this.owner.window.hideThrobber(); if (!this.check(code)) { return; } this.dom.ta.value = data; } SQL.IO.prototype.importresponse = function(data, code) { this.owner.window.hideThrobber(); if (!this.check(code)) { return; } if (this.fromXML(data)) { this.owner.alignTables(); } } SQL.IO.prototype.press = function(e) { switch (e.keyCode) { case 113: if (OZ.opera) { e.preventDefault(); } this.quicksave(e); break; } } /* --------------------- table manager ------------ */ SQL.TableManager = OZ.Class(); SQL.TableManager.prototype.init = function(owner) { this.owner = owner; this.dom = { container:OZ.$("table"), name:OZ.$("tablename"), comment:OZ.$("tablecomment") }; this.selection = []; this.adding = false; var ids = ["addtable","removetable","aligntables","cleartables","addrow","edittable","tablekeys"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); this.dom[id] = elm; elm.value = _(id); } var ids = ["tablenamelabel","tablecommentlabel"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); elm.innerHTML = _(id); } this.select(false); this.save = this.bind(this.save); OZ.Event.add("area", "click", this.bind(this.click)); OZ.Event.add(this.dom.addtable, "click", this.bind(this.preAdd)); OZ.Event.add(this.dom.removetable, "click", this.bind(this.remove)); OZ.Event.add(this.dom.cleartables, "click", this.bind(this.clear)); OZ.Event.add(this.dom.addrow, "click", this.bind(this.addRow)); OZ.Event.add(this.dom.aligntables, "click", this.owner.bind(this.owner.alignTables)); OZ.Event.add(this.dom.edittable, "click", this.bind(this.edit)); OZ.Event.add(this.dom.tablekeys, "click", this.bind(this.keys)); OZ.Event.add(document, "keydown", this.bind(this.press)); this.dom.container.parentNode.removeChild(this.dom.container); } SQL.TableManager.prototype.addRow = function(e) { var newrow = this.selection[0].addRow(_("newrow")); this.owner.rowManager.select(newrow); newrow.expand(); } SQL.TableManager.prototype.select = function(table, multi) { /* activate table */ if (table) { if (multi) { var i = this.selection.indexOf(table); if (i < 0) { this.selection.push(table); } else { this.selection.splice(i, 1); } } else { if (this.selection[0] === table) { return; } this.selection = [table]; } } else { this.selection = []; } this.processSelection(); } SQL.TableManager.prototype.processSelection = function() { var tables = this.owner.tables; for (var i=0;i<tables.length;i++) { tables[i].deselect(); } if (this.selection.length == 1) { this.dom.addrow.disabled = false; this.dom.edittable.disabled = false; this.dom.tablekeys.disabled = false; this.dom.removetable.value = _("removetable"); } else { this.dom.addrow.disabled = true; this.dom.edittable.disabled = true; this.dom.tablekeys.disabled = true; } if (this.selection.length) { this.dom.removetable.disabled = false; if (this.selection.length > 1) { this.dom.removetable.value = _("removetables"); } } else { this.dom.removetable.disabled = true; this.dom.removetable.value = _("removetable"); } for (var i=0;i<this.selection.length;i++) { var t = this.selection[i]; t.owner.raise(t); t.select(); } } SQL.TableManager.prototype.selectRect = function(x,y,width,height) { /* select all tables intersecting a rectangle */ this.selection = []; var tables = this.owner.tables; var x1 = x+width; var y1 = y+height; for (var i=0;i<tables.length;i++) { var t = tables[i]; var tx = t.x; var tx1 = t.x+t.width; var ty = t.y; var ty1 = t.y+t.height; if (((tx>=x && tx<x1) || (tx1>=x && tx1<x1) || (tx<x && tx1>x1)) && ((ty>=y && ty<y1) || (ty1>=y && ty1<y1) || (ty<y && ty1>y1))) { this.selection.push(t); } } this.processSelection(); } SQL.TableManager.prototype.click = function(e) { /* finish adding new table */ var newtable = false; if (this.adding) { this.adding = false; OZ.DOM.removeClass("area","adding"); this.dom.addtable.value = this.oldvalue; var scroll = OZ.DOM.scroll(); var x = e.clientX + scroll[0]; var y = e.clientY + scroll[1]; newtable = this.owner.addTable(_("newtable"),x,y); var r = newtable.addRow("id",{ai:true}); var k = newtable.addKey("PRIMARY",""); k.addRow(r); } this.select(newtable); this.owner.rowManager.select(false); if (this.selection.length == 1) { this.edit(e); } } SQL.TableManager.prototype.preAdd = function(e) { /* click add new table */ if (this.adding) { this.adding = false; OZ.DOM.removeClass("area","adding"); this.dom.addtable.value = this.oldvalue; } else { this.adding = true; OZ.DOM.addClass("area","adding"); this.oldvalue = this.dom.addtable.value; this.dom.addtable.value = "["+_("addpending")+"]"; } } SQL.TableManager.prototype.clear = function(e) { /* remove all tables */ if (!this.owner.tables.length) { return; } var result = confirm(_("confirmall")+" ?"); if (!result) { return; } this.owner.clearTables(); } SQL.TableManager.prototype.remove = function(e) { var titles = this.selection.slice(0); for (var i=0;i<titles.length;i++) { titles[i] = "'"+titles[i].getTitle()+"'"; } var result = confirm(_("confirmtable")+" "+titles.join(", ")+"?"); if (!result) { return; } var sel = this.selection.slice(0); for (var i=0;i<sel.length;i++) { this.owner.removeTable(sel[i]); } } SQL.TableManager.prototype.edit = function(e) { this.owner.window.open(_("edittable"), this.dom.container, this.save); var title = this.selection[0].getTitle(); this.dom.name.value = title; try { /* throws in ie6 */ this.dom.comment.value = this.selection[0].getComment(); } catch(e) {} /* pre-select table name */ this.dom.name.focus(); if (OZ.ie) { try { /* throws in ie6 */ this.dom.name.select(); } catch(e) {} } else { this.dom.name.setSelectionRange(0, title.length); } } SQL.TableManager.prototype.keys = function(e) { /* open keys dialog */ this.owner.keyManager.open(this.selection[0]); } SQL.TableManager.prototype.save = function() { this.selection[0].setTitle(this.dom.name.value); this.selection[0].setComment(this.dom.comment.value); } SQL.TableManager.prototype.press = function(e) { var target = OZ.Event.target(e).nodeName.toLowerCase(); if (target == "textarea" || target == "input") { return; } /* not when in form field */ if (this.owner.rowManager.selected) { return; } /* do not process keypresses if a row is selected */ if (!this.selection.length) { return; } /* nothing if selection is active */ switch (e.keyCode) { case 46: this.remove(); OZ.Event.prevent(e); break; } } /* --------------------- row manager ------------ */ SQL.RowManager = OZ.Class(); SQL.RowManager.prototype.init = function(owner) { this.owner = owner; this.dom = {}; this.selected = null; this.creating = false; this.connecting = false; var ids = ["editrow","removerow","uprow","downrow","foreigncreate","foreignconnect","foreigndisconnect"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); this.dom[id] = elm; elm.value = _(id); } this.select(false); OZ.Event.add(this.dom.editrow, "click", this.bind(this.edit)); OZ.Event.add(this.dom.uprow, "click", this.bind(this.up)); OZ.Event.add(this.dom.downrow, "click", this.bind(this.down)); OZ.Event.add(this.dom.removerow, "click", this.bind(this.remove)); OZ.Event.add(this.dom.foreigncreate, "click", this.bind(this.foreigncreate)); OZ.Event.add(this.dom.foreignconnect, "click", this.bind(this.foreignconnect)); OZ.Event.add(this.dom.foreigndisconnect, "click", this.bind(this.foreigndisconnect)); OZ.Event.add(false, "tableclick", this.bind(this.tableClick)); OZ.Event.add(false, "rowclick", this.bind(this.rowClick)); OZ.Event.add(document, "keydown", this.bind(this.press)); } SQL.RowManager.prototype.select = function(row) { /* activate a row */ if (this.selected === row) { return; } if (this.selected) { this.selected.deselect(); } this.selected = row; if (this.selected) { this.selected.select(); } this.redraw(); } SQL.RowManager.prototype.tableClick = function(e) { /* create relation after clicking target table */ if (!this.creating) { return; } var r1 = this.selected; var t2 = e.target; var p = this.owner.getOption("pattern"); p = p.replace(/%T/g,r1.owner.getTitle()); p = p.replace(/%t/g,t2.getTitle()); p = p.replace(/%R/g,r1.getTitle()); var r2 = t2.addRow(p, r1.data); r2.update({"type":SQL.Designer.getFKTypeFor(r1.data.type)}); r2.update({"ai":false}); this.owner.addRelation(r1, r2); } SQL.RowManager.prototype.rowClick = function(e) { /* draw relation after clicking target row */ if (!this.connecting) { return; } var r1 = this.selected; var r2 = e.target; if (r1 == r2) { return; } this.owner.addRelation(r1, r2); } SQL.RowManager.prototype.foreigncreate = function(e) { /* start creating fk */ this.endConnect(); if (this.creating) { this.endCreate(); } else { this.creating = true; this.dom.foreigncreate.value = "["+_("foreignpending")+"]"; } } SQL.RowManager.prototype.foreignconnect = function(e) { /* start drawing fk */ this.endCreate(); if (this.connecting) { this.endConnect(); } else { this.connecting = true; this.dom.foreignconnect.value = "["+_("foreignconnectpending")+"]"; } } SQL.RowManager.prototype.foreigndisconnect = function(e) { /* remove connector */ var rels = this.selected.relations; for (var i=rels.length-1;i>=0;i--) { var r = rels[i]; if (r.row2 == this.selected) { this.owner.removeRelation(r); } } this.redraw(); } SQL.RowManager.prototype.endCreate = function() { this.creating = false; this.dom.foreigncreate.value = _("foreigncreate"); } SQL.RowManager.prototype.endConnect = function() { this.connecting = false; this.dom.foreignconnect.value = _("foreignconnect"); } SQL.RowManager.prototype.up = function(e) { this.selected.up(); this.redraw(); } SQL.RowManager.prototype.down = function(e) { this.selected.down(); this.redraw(); } SQL.RowManager.prototype.remove = function(e) { var result = confirm(_("confirmrow")+" '"+this.selected.getTitle()+"' ?"); if (!result) { return; } var t = this.selected.owner; this.selected.owner.removeRow(this.selected); var next = false; if (t.rows) { next = t.rows[t.rows.length-1]; } this.select(next); } SQL.RowManager.prototype.redraw = function() { this.endCreate(); this.endConnect(); if (this.selected) { var table = this.selected.owner; var rows = table.rows; this.dom.uprow.disabled = (rows[0] == this.selected); this.dom.downrow.disabled = (rows[rows.length-1] == this.selected); this.dom.removerow.disabled = false; this.dom.editrow.disabled = false; this.dom.foreigncreate.disabled = !(this.selected.isUnique()); this.dom.foreignconnect.disabled = !(this.selected.isUnique()); this.dom.foreigndisconnect.disabled = true; var rels = this.selected.relations; for (var i=0;i<rels.length;i++) { var r = rels[i]; if (r.row2 == this.selected) { this.dom.foreigndisconnect.disabled = false; } } } else { this.dom.uprow.disabled = true; this.dom.downrow.disabled = true; this.dom.removerow.disabled = true; this.dom.editrow.disabled = true; this.dom.foreigncreate.disabled = true; this.dom.foreignconnect.disabled = true; this.dom.foreigndisconnect.disabled = true; } } SQL.RowManager.prototype.press = function(e) { if (!this.selected) { return; } var target = OZ.Event.target(e).nodeName.toLowerCase(); if (target == "textarea" || target == "input") { return; } /* not when in form field */ switch (e.keyCode) { case 38: this.up(); OZ.Event.prevent(e); break; case 40: this.down(); OZ.Event.prevent(e); break; case 46: this.remove(); OZ.Event.prevent(e); break; case 13: case 27: this.selected.collapse(); break; } } SQL.RowManager.prototype.edit = function(e) { this.selected.expand(); } /* ----------------- key manager ---------- */ SQL.KeyManager = OZ.Class(); SQL.KeyManager.prototype.init = function(owner) { this.owner = owner; this.dom = { container:OZ.$("keys") } this.build(); } SQL.KeyManager.prototype.build = function() { this.dom.list = OZ.$("keyslist"); this.dom.type = OZ.$("keytype"); this.dom.name = OZ.$("keyname"); this.dom.left = OZ.$("keyleft"); this.dom.right = OZ.$("keyright"); this.dom.fields = OZ.$("keyfields"); this.dom.avail = OZ.$("keyavail"); this.dom.listlabel = OZ.$("keyslistlabel"); var ids = ["keyadd","keyremove"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); this.dom[id] = elm; elm.value = _(id); } var ids = ["keyedit","keytypelabel","keynamelabel","keyfieldslabel","keyavaillabel"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); elm.innerHTML = _(id); } var types = ["PRIMARY","INDEX","UNIQUE","FULLTEXT"]; OZ.DOM.clear(this.dom.type); for (var i=0;i<types.length;i++) { var o = OZ.DOM.elm("option"); o.innerHTML = types[i]; o.value = types[i]; this.dom.type.appendChild(o); } this.purge = this.bind(this.purge); OZ.Event.add(this.dom.list, "change", this.bind(this.listchange)); OZ.Event.add(this.dom.type, "change", this.bind(this.typechange)); OZ.Event.add(this.dom.name, "keyup", this.bind(this.namechange)); OZ.Event.add(this.dom.keyadd, "click", this.bind(this.add)); OZ.Event.add(this.dom.keyremove, "click", this.bind(this.remove)); OZ.Event.add(this.dom.left, "click", this.bind(this.left)); OZ.Event.add(this.dom.right, "click", this.bind(this.right)); this.dom.container.parentNode.removeChild(this.dom.container); } SQL.KeyManager.prototype.listchange = function(e) { this.switchTo(this.dom.list.selectedIndex); } SQL.KeyManager.prototype.typechange = function(e) { this.key.setType(this.dom.type.value); this.redrawListItem(); } SQL.KeyManager.prototype.namechange = function(e) { this.key.setName(this.dom.name.value); this.redrawListItem(); } SQL.KeyManager.prototype.add = function(e) { var type = (this.table.keys.length ? "INDEX" : "PRIMARY"); this.table.addKey(type); this.sync(this.table); this.switchTo(this.table.keys.length-1); } SQL.KeyManager.prototype.remove = function(e) { var index = this.dom.list.selectedIndex; if (index == -1) { return; } var r = this.table.keys[index]; this.table.removeKey(r); this.sync(this.table); } SQL.KeyManager.prototype.purge = function() { /* remove empty keys */ for (var i=this.table.keys.length-1;i>=0;i--) { var k = this.table.keys[i]; if (!k.rows.length) { this.table.removeKey(k); } } } SQL.KeyManager.prototype.sync = function(table) { /* sync content with given table */ this.table = table; this.dom.listlabel.innerHTML = _("keyslistlabel").replace(/%s/,table.getTitle()); OZ.DOM.clear(this.dom.list); for (var i=0;i<table.keys.length;i++) { var k = table.keys[i]; var o = OZ.DOM.elm("option"); this.dom.list.appendChild(o); var str = (i+1)+": "+k.getLabel(); o.innerHTML = str; } if (table.keys.length) { this.switchTo(0); } else { this.disable(); } } SQL.KeyManager.prototype.redrawListItem = function() { var index = this.table.keys.indexOf(this.key); this.option.innerHTML = (index+1)+": "+this.key.getLabel(); } SQL.KeyManager.prototype.switchTo = function(index) { /* show Nth key */ this.enable(); var k = this.table.keys[index]; this.key = k; this.option = this.dom.list.getElementsByTagName("option")[index]; this.dom.list.selectedIndex = index; this.dom.name.value = k.getName(); var opts = this.dom.type.getElementsByTagName("option"); for (var i=0;i<opts.length;i++) { if (opts[i].value == k.getType()) { this.dom.type.selectedIndex = i; } } OZ.DOM.clear(this.dom.fields); for (var i=0;i<k.rows.length;i++) { var o = OZ.DOM.elm("option"); o.innerHTML = k.rows[i].getTitle(); o.value = o.innerHTML; this.dom.fields.appendChild(o); } OZ.DOM.clear(this.dom.avail); for (var i=0;i<this.table.rows.length;i++) { var r = this.table.rows[i]; if (k.rows.indexOf(r) != -1) { continue; } var o = OZ.DOM.elm("option"); o.innerHTML = r.getTitle(); o.value = o.innerHTML; this.dom.avail.appendChild(o); } } SQL.KeyManager.prototype.disable = function() { OZ.DOM.clear(this.dom.fields); OZ.DOM.clear(this.dom.avail); this.dom.keyremove.disabled = true; this.dom.left.disabled = true; this.dom.right.disabled = true; this.dom.list.disabled = true; this.dom.name.disabled = true; this.dom.type.disabled = true; this.dom.fields.disabled = true; this.dom.avail.disabled = true; } SQL.KeyManager.prototype.enable = function() { this.dom.keyremove.disabled = false; this.dom.left.disabled = false; this.dom.right.disabled = false; this.dom.list.disabled = false; this.dom.name.disabled = false; this.dom.type.disabled = false; this.dom.fields.disabled = false; this.dom.avail.disabled = false; } SQL.KeyManager.prototype.left = function(e) { /* add field to index */ var opts = this.dom.avail.getElementsByTagName("option"); for (var i=0;i<opts.length;i++) { var o = opts[i]; if (o.selected) { var row = this.table.findNamedRow(o.value); this.key.addRow(row); } } this.switchTo(this.dom.list.selectedIndex); } SQL.KeyManager.prototype.right = function(e) { /* remove field from index */ var opts = this.dom.fields.getElementsByTagName("option"); for (var i=0;i<opts.length;i++) { var o = opts[i]; if (o.selected) { var row = this.table.findNamedRow(o.value); this.key.removeRow(row); } } this.switchTo(this.dom.list.selectedIndex); } SQL.KeyManager.prototype.open = function(table) { this.sync(table); this.owner.window.open(_("tablekeys"),this.dom.container,this.purge); } /* --------------------- window ------------ */ SQL.Window = OZ.Class(); SQL.Window.prototype.init = function(owner) { this.owner = owner; this.dom = { container:OZ.$("window"), background:OZ.$("background"), ok:OZ.$("windowok"), cancel:OZ.$("windowcancel"), title:OZ.$("windowtitle"), content:OZ.$("windowcontent"), throbber:OZ.$("throbber") } this.dom.ok.value = _("windowok"); this.dom.cancel.value = _("windowcancel"); this.dom.throbber.alt = this.dom.throbber.title = _("throbber"); OZ.Event.add(this.dom.ok, "click", this.bind(this.ok)); OZ.Event.add(this.dom.cancel, "click", this.bind(this.close)); OZ.Event.add(document, "keydown", this.bind(this.key)); this.sync = this.bind(this.sync); OZ.Event.add(window, "scroll", this.sync); OZ.Event.add(window, "resize", this.sync); this.state = 0; this.hideThrobber(); this.sync(); } SQL.Window.prototype.showThrobber = function() { this.dom.throbber.style.visibility = ""; } SQL.Window.prototype.hideThrobber = function() { this.dom.throbber.style.visibility = "hidden"; } SQL.Window.prototype.open = function(title, content, callback) { this.state = 1; this.callback = callback; while (this.dom.title.childNodes.length > 1) { this.dom.title.removeChild(this.dom.title.childNodes[1]); } var txt = OZ.DOM.text(title); this.dom.title.appendChild(txt); this.dom.background.style.visibility = "visible"; OZ.DOM.clear(this.dom.content); this.dom.content.appendChild(content); var win = OZ.DOM.win(); var scroll = OZ.DOM.scroll(); this.dom.container.style.left = Math.round(scroll[0] + (win[0] - this.dom.container.offsetWidth)/2)+"px"; this.dom.container.style.top = Math.round(scroll[1] + (win[1] - this.dom.container.offsetHeight)/2)+"px"; this.dom.cancel.style.visibility = (this.callback ? "" : "hidden"); this.dom.container.style.visibility = "visible"; var formElements = ["input","select","textarea"]; var all = this.dom.container.getElementsByTagName("*"); for (var i=0;i<all.length;i++) { if (formElements.indexOf(all[i].tagName.toLowerCase()) != -1) { all[i].focus(); break; } } } SQL.Window.prototype.key = function(e) { if (!this.state) { return; } if (e.keyCode == 13) { this.ok(e); } if (e.keyCode == 27) { this.close(); } } SQL.Window.prototype.ok = function(e) { if (this.callback) { this.callback(); } this.close(); } SQL.Window.prototype.close = function() { if (!this.state) { return; } this.state = 0; this.dom.background.style.visibility = "hidden"; this.dom.container.style.visibility = "hidden"; } SQL.Window.prototype.sync = function() { /* adjust background position */ var dims = OZ.DOM.win(); var scroll = OZ.DOM.scroll(); this.dom.background.style.width = dims[0]+"px"; this.dom.background.style.height = dims[1]+"px"; this.dom.background.style.left = scroll[0]+"px"; this.dom.background.style.top = scroll[1]+"px"; } /* --------------------- options ------------ */ SQL.Options = OZ.Class(); SQL.Options.prototype.init = function(owner) { this.owner = owner; this.dom = { container:OZ.$("opts"), btn:OZ.$("options") } this.dom.btn.value = _("options"); this.save = this.bind(this.save); this.build(); } SQL.Options.prototype.build = function() { this.dom.optionlocale = OZ.$("optionlocale"); this.dom.optiondb = OZ.$("optiondb"); this.dom.optionsnap = OZ.$("optionsnap"); this.dom.optionpattern = OZ.$("optionpattern"); this.dom.optionhide = OZ.$("optionhide"); this.dom.optionvector = OZ.$("optionvector"); this.dom.optionshowsize = OZ.$("optionshowsize"); this.dom.optionshowtype = OZ.$("optionshowtype"); var ids = ["language","db","snap","pattern","hide","vector","showsize","showtype","optionsnapnotice","optionpatternnotice","optionsnotice"]; for (var i=0;i<ids.length;i++) { var id = ids[i]; var elm = OZ.$(id); elm.innerHTML = _(id); } var ls = CONFIG.AVAILABLE_LOCALES; OZ.DOM.clear(this.dom.optionlocale); for (var i=0;i<ls.length;i++) { var o = OZ.DOM.elm("option"); o.value = ls[i]; o.innerHTML = ls[i]; this.dom.optionlocale.appendChild(o); if (this.owner.getOption("locale") == ls[i]) { this.dom.optionlocale.selectedIndex = i; } } var dbs = CONFIG.AVAILABLE_DBS; OZ.DOM.clear(this.dom.optiondb); for (var i=0;i<dbs.length;i++) { var o = OZ.DOM.elm("option"); o.value = dbs[i]; o.innerHTML = dbs[i]; this.dom.optiondb.appendChild(o); if (this.owner.getOption("db") == dbs[i]) { this.dom.optiondb.selectedIndex = i; } } OZ.Event.add(this.dom.btn, "click", this.bind(this.click)); this.dom.container.parentNode.removeChild(this.dom.container); } SQL.Options.prototype.save = function() { this.owner.setOption("locale",this.dom.optionlocale.value); this.owner.setOption("db",this.dom.optiondb.value); this.owner.setOption("snap",this.dom.optionsnap.value); this.owner.setOption("pattern",this.dom.optionpattern.value); this.owner.setOption("hide",this.dom.optionhide.checked ? "1" : ""); this.owner.setOption("vector",this.dom.optionvector.checked ? "1" : ""); this.owner.setOption("showsize",this.dom.optionshowsize.checked ? "1" : ""); this.owner.setOption("showtype",this.dom.optionshowtype.checked ? "1" : ""); } SQL.Options.prototype.click = function() { this.owner.window.open(_("options"),this.dom.container,this.save); this.dom.optionsnap.value = this.owner.getOption("snap"); this.dom.optionpattern.value = this.owner.getOption("pattern"); this.dom.optionhide.checked = this.owner.getOption("hide"); this.dom.optionvector.checked = this.owner.getOption("vector"); this.dom.optionshowsize.checked = this.owner.getOption("showsize"); this.dom.optionshowtype.checked = this.owner.getOption("showtype"); } /* ------------------ minimize/restore bar ----------- */ SQL.Toggle = OZ.Class(); SQL.Toggle.prototype.init = function(elm) { this._state = null; this._elm = elm; OZ.Event.add(elm, "click", this._click.bind(this)); var defaultState = true; if (document.location.href.match(/toolbar=hidden/)) { defaultState = false; } this._switch(defaultState); } SQL.Toggle.prototype._click = function(e) { this._switch(!this._state); } SQL.Toggle.prototype._switch = function(state) { this._state = state; if (this._state) { OZ.$("bar").style.height = ""; } else { OZ.$("bar").style.overflow = "hidden"; OZ.$("bar").style.height = this._elm.offsetHeight + "px"; } this._elm.className = (this._state ? "on" : "off"); } /* --------------------- www sql designer ------------ */ SQL.Designer = OZ.Class().extend(SQL.Visual); SQL.Designer.prototype.init = function() { SQL.Designer = this; this.tables = []; this.relations = []; this.title = document.title; SQL.Visual.prototype.init.apply(this); new SQL.Toggle(OZ.$("toggle")); this.dom.container = OZ.$("area"); this.minSize = [ this.dom.container.offsetWidth, this.dom.container.offsetHeight ]; this.width = this.minSize[0]; this.height = this.minSize[1]; this.typeIndex = false; this.fkTypeFor = false; this.vector = this.getOption("vector") && document.createElementNS; if (this.vector) { this.svgNS = "http://www.w3.org/2000/svg"; this.dom.svg = document.createElementNS(this.svgNS, "svg"); this.dom.container.appendChild(this.dom.svg); } this.flag = 2; this.requestLanguage(); this.requestDB(); } /* update area size */ SQL.Designer.prototype.sync = function() { var w = this.minSize[0]; var h = this.minSize[0]; for (var i=0;i<this.tables.length;i++) { var t = this.tables[i]; w = Math.max(w, t.x + t.width); h = Math.max(h, t.y + t.height); } this.width = w; this.height = h; this.map.sync(); if (this.vector) { this.dom.svg.setAttribute("width", this.width); this.dom.svg.setAttribute("height", this.height); } } SQL.Designer.prototype.requestLanguage = function() { /* get locale file */ var lang = this.getOption("locale") var bp = this.getOption("staticpath"); var url = bp + "locale/"+lang+".xml"; OZ.Request(url, this.bind(this.languageResponse), {method:"get", xml:true}); } SQL.Designer.prototype.languageResponse = function(xmlDoc) { if (xmlDoc) { var strings = xmlDoc.getElementsByTagName("string"); for (var i=0;i<strings.length;i++) { var n = strings[i].getAttribute("name"); var v = strings[i].firstChild.nodeValue; window.LOCALE[n] = v; } } this.flag--; if (!this.flag) { this.init2(); } } SQL.Designer.prototype.requestDB = function() { /* get datatypes file */ var db = this.getOption("db"); var bp = this.getOption("staticpath"); var url = bp + "db/"+db+"/datatypes.xml"; OZ.Request(url, this.bind(this.dbResponse), {method:"get", xml:true}); } SQL.Designer.prototype.dbResponse = function(xmlDoc) { if (xmlDoc) { window.DATATYPES = xmlDoc.documentElement; } this.flag--; if (!this.flag) { this.init2(); } } SQL.Designer.prototype.init2 = function() { /* secondary init, after locale & datatypes were retrieved */ this.map = new SQL.Map(this); this.rubberband = new SQL.Rubberband(this); this.tableManager = new SQL.TableManager(this); this.rowManager = new SQL.RowManager(this); this.keyManager = new SQL.KeyManager(this); this.io = new SQL.IO(this); this.options = new SQL.Options(this); this.window = new SQL.Window(this); this.sync(); OZ.$("docs").value = _("docs"); var url = window.location.href; var r = url.match(/keyword=([^&]+)/); if (r) { var keyword = r[1]; this.io.serverload(false, keyword); } document.body.style.visibility = "visible"; } SQL.Designer.prototype.getMaxZ = function() { /* find max zIndex */ var max = 0; for (var i=0;i<this.tables.length;i++) { var z = this.tables[i].getZ(); if (z > max) { max = z; } } OZ.$("controls").style.zIndex = max+5; return max; } SQL.Designer.prototype.addTable = function(name, x, y) { var max = this.getMaxZ(); var t = new SQL.Table(this, name, x, y, max+1); this.tables.push(t); this.dom.container.appendChild(t.dom.container); return t; } SQL.Designer.prototype.removeTable = function(t) { this.tableManager.select(false); this.rowManager.select(false); var idx = this.tables.indexOf(t); if (idx == -1) { return; } t.destroy(); this.tables.splice(idx,1); } SQL.Designer.prototype.addRelation = function(row1, row2) { var r = new SQL.Relation(this, row1, row2); this.relations.push(r); return r; } SQL.Designer.prototype.removeRelation = function(r) { var idx = this.relations.indexOf(r); if (idx == -1) { return; } r.destroy(); this.relations.splice(idx,1); } SQL.Designer.prototype.getCookie = function() { var c = document.cookie; var obj = {}; var parts = c.split(";"); for (var i=0;i<parts.length;i++) { var part = parts[i]; var r = part.match(/wwwsqldesigner=({.*?})/); if (r) { obj = eval("("+r[1]+")"); } } return obj; } SQL.Designer.prototype.setCookie = function(obj) { var arr = []; for (var p in obj) { arr.push(p+":'"+obj[p]+"'"); } var str = "{"+arr.join(",")+"}"; document.cookie = "wwwsqldesigner="+str+"; path=/"; } SQL.Designer.prototype.getOption = function(name) { var c = this.getCookie(); if (name in c) { return c[name]; } /* defaults */ switch (name) { case "locale": return CONFIG.DEFAULT_LOCALE; case "db": return CONFIG.DEFAULT_DB; case "staticpath": return CONFIG.STATIC_PATH || ""; case "xhrpath": return CONFIG.XHR_PATH || ""; case "snap": return 0; case "showsize": return 0; case "showtype": return 0; case "pattern": return "%R_%T"; case "hide": return false; case "vector": return true; default: return null; } } SQL.Designer.prototype.setOption = function(name, value) { var obj = this.getCookie(); obj[name] = value; this.setCookie(obj); } SQL.Designer.prototype.raise = function(table) { /* raise a table */ var old = table.getZ(); var max = this.getMaxZ(); table.setZ(max); for (var i=0;i<this.tables.length;i++) { var t = this.tables[i]; if (t == table) { continue; } if (t.getZ() > old) { t.setZ(t.getZ()-1); } } var m = table.dom.mini; m.parentNode.appendChild(m); } SQL.Designer.prototype.clearTables = function() { while (this.tables.length) { this.removeTable(this.tables[0]); } this.setTitle(false); } SQL.Designer.prototype.alignTables = function() { var win = OZ.DOM.win(); var avail = win[0] - OZ.$("bar").offsetWidth; var x = 10; var y = 10; var max = 0; this.tables.sort(function(a,b){ return b.getRelations().length - a.getRelations().length; }); for (var i=0;i<this.tables.length;i++) { var t = this.tables[i]; var w = t.dom.container.offsetWidth; var h = t.dom.container.offsetHeight; if (x + w > avail) { x = 10; y += 10 + max; max = 0; } t.moveTo(x,y); x += 10 + w; if (h > max) { max = h; } } this.sync(); } SQL.Designer.prototype.findNamedTable = function(name) { /* find row specified as table(row) */ for (var i=0;i<this.tables.length;i++) { if (this.tables[i].getTitle() == name) { return this.tables[i]; } } } SQL.Designer.prototype.toXML = function() { var xml = '<?xml version="1.0" encoding="utf-8" ?>\n'; xml += '<!-- SQL XML created by WWW SQL Designer, http://code.google.com/p/wwwsqldesigner/ -->\n'; xml += '<!-- Active URL: ' + location.href + ' -->\n'; xml += '<sql>\n'; /* serialize datatypes */ if (window.XMLSerializer) { var s = new XMLSerializer(); xml += s.serializeToString(window.DATATYPES); } else if (window.DATATYPES.xml) { xml += window.DATATYPES.xml; } else { alert(_("errorxml")+': '+e.message); } for (var i=0;i<this.tables.length;i++) { xml += this.tables[i].toXML(); } xml += "</sql>\n"; return xml; } SQL.Designer.prototype.fromXML = function(node) { this.clearTables(); var types = node.getElementsByTagName("datatypes"); if (types.length) { window.DATATYPES = types[0]; } var tables = node.getElementsByTagName("table"); for (var i=0;i<tables.length;i++) { var t = this.addTable("", 0, 0); t.fromXML(tables[i]); } for (var i=0;i<this.tables.length;i++) { /* ff one-pixel shift hack */ this.tables[i].select(); this.tables[i].deselect(); } /* relations */ var rs = node.getElementsByTagName("relation"); for (var i=0;i<rs.length;i++) { var rel = rs[i]; var tname = rel.getAttribute("table"); var rname = rel.getAttribute("row"); var t1 = this.findNamedTable(tname); if (!t1) { continue; } var r1 = t1.findNamedRow(rname); if (!r1) { continue; } tname = rel.parentNode.parentNode.getAttribute("name"); rname = rel.parentNode.getAttribute("name"); var t2 = this.findNamedTable(tname); if (!t2) { continue; } var r2 = t2.findNamedRow(rname); if (!r2) { continue; } this.addRelation(r1, r2); } } SQL.Designer.prototype.setTitle = function(t) { document.title = this.title + (t ? " - "+t : ""); } SQL.Designer.prototype.removeSelection = function() { var sel = (window.getSelection ? window.getSelection() : document.selection); if (!sel) { return; } if (sel.empty) { sel.empty(); } if (sel.removeAllRanges) { sel.removeAllRanges(); } } SQL.Designer.prototype.getTypeIndex = function(label) { if (!this.typeIndex) { this.typeIndex = {}; var types = window.DATATYPES.getElementsByTagName("type"); for (var i=0;i<types.length;i++) { var l = types[i].getAttribute("label"); if (l) { this.typeIndex[l] = i; } } } return this.typeIndex[label]; } SQL.Designer.prototype.getFKTypeFor = function(typeIndex) { if (!this.fkTypeFor) { this.fkTypeFor = {}; var types = window.DATATYPES.getElementsByTagName("type"); for (var i=0;i<types.length;i++) { this.fkTypeFor[i] = i; var fk = types[i].getAttribute("fk"); if (fk) { this.fkTypeFor[i] = this.getTypeIndex(fk); } } } return this.fkTypeFor[typeIndex]; } OZ.Event.add(window, "beforeunload", function(e) { OZ.Event.prevent(e); return ""; });
JavaScript
function bwg_shortcode_load() { jQuery(".spider_int_input").keypress(function (event) { var chCode1 = event.which || event.paramlist_keyCode; if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46)) { return false; } return true; }); jQuery("#display_panel").tooltip({ track: true, content: function () { return jQuery(this).prop('title'); } }); } function bwg_watermark(watermark_type) { jQuery("#" + watermark_type).prop('checked', true); jQuery("#tr_watermark_link").css('display', 'none'); jQuery("#tr_watermark_url").css('display', 'none'); jQuery("#tr_watermark_width_height").css('display', 'none'); jQuery("#tr_watermark_opacity").css('display', 'none'); jQuery("#tr_watermark_text").css('display', 'none'); jQuery("#tr_watermark_font_size").css('display', 'none'); jQuery("#tr_watermark_font").css('display', 'none'); jQuery("#tr_watermark_color").css('display', 'none'); jQuery("#tr_watermark_position").css('display', 'none'); bwg_enable_disable('', '', 'watermark_bottom_right'); switch (watermark_type) { case 'watermark_type_text': { jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_text").css('display', ''); jQuery("#tr_watermark_font_size").css('display', ''); jQuery("#tr_watermark_font").css('display', ''); jQuery("#tr_watermark_color").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); break; } case 'watermark_type_image': { jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_url").css('display', ''); jQuery("#tr_watermark_width_height").css('display', ''); jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); break; } } } function bwg_enable_disable(display, id, current) { jQuery("#" + current).prop('checked', true); jQuery("#" + id).css('display', display); } function bwg_popup_fullscreen() { if (jQuery("#popup_fullscreen_1").is(':checked')) { jQuery("#tr_popup_width_height").css('display', 'none'); } else { jQuery("#tr_popup_width_height").css('display', ''); } } function bwg_thumb_click_action() { if (!jQuery("#thumb_click_action_2").is(':checked')) { jQuery("#tr_thumb_link_target").css('display', 'none'); jQuery("#tbody_popup").css('display', ''); jQuery("#tr_popup_width_height").css('display', ''); jQuery("#tr_popup_effect").css('display', ''); jQuery("#tr_popup_interval").css('display', ''); jQuery("#tr_popup_enable_filmstrip").css('display', ''); if (jQuery("input[name=popup_enable_filmstrip]:checked").val() == 1) { bwg_enable_disable('', 'tr_popup_filmstrip_height', 'popup_filmstrip_yes'); } else { bwg_enable_disable('none', 'tr_popup_filmstrip_height', 'popup_filmstrip_no'); } jQuery("#tr_popup_enable_ctrl_btn").css('display', ''); if (jQuery("input[name=popup_enable_ctrl_btn]:checked").val() == 1) { bwg_enable_disable('', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_yes'); } else { bwg_enable_disable('none', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_no'); } jQuery("#tr_popup_enable_fullscreen").css('display', ''); jQuery("#tr_popup_enable_info").css('display', ''); jQuery("#tr_popup_enable_rate").css('display', ''); jQuery("#tr_popup_enable_comment").css('display', ''); jQuery("#tr_popup_enable_facebook").css('display', ''); jQuery("#tr_popup_enable_twitter").css('display', ''); jQuery("#tr_popup_enable_google").css('display', ''); jQuery("#tr_popup_enable_pinterest").css('display', ''); jQuery("#tr_popup_enable_tumblr").css('display', ''); bwg_popup_fullscreen(); } else { jQuery("#tr_thumb_link_target").css('display', ''); jQuery("#tbody_popup").css('display', 'none'); jQuery("#tbody_popup_ctrl_btn").css('display', 'none'); } } function bwg_show_search_box() { if (jQuery("#show_search_box_1").is(':checked')) { jQuery("#tr_search_box_width").css('display', ''); } else { jQuery("#tr_search_box_width").css('display', 'none'); } } function bwg_change_compuct_album_view_type() { if (jQuery("input[name=compuct_album_view_type]:checked").val() == 'thumbnail') { jQuery("#compuct_album_image_thumb_dimensions").html('Image thumbnail dimensions: '); jQuery("#compuct_album_image_thumb_dimensions_x").css('display', ''); jQuery("#compuct_album_image_thumb_height").css('display', ''); jQuery("#tr_compuct_album_image_title").css('display', ''); } else { jQuery("#compuct_album_image_thumb_dimensions").html('Image thumbnail width: '); jQuery("#compuct_album_image_thumb_dimensions_x").css('display', 'none'); jQuery("#compuct_album_image_thumb_height").css('display', 'none'); jQuery("#tr_compuct_album_image_title").css('display', 'none'); } } function bwg_change_extended_album_view_type() { if (jQuery("input[name=extended_album_view_type]:checked").val() == 'thumbnail') { jQuery("#extended_album_image_thumb_dimensions").html('Image thumbnail dimensions: '); jQuery("#extended_album_image_thumb_dimensions_x").css('display', ''); jQuery("#extended_album_image_thumb_height").css('display', ''); jQuery("#tr_extended_album_image_title").css('display', ''); } else { jQuery("#extended_album_image_thumb_dimensions").html('Image thumbnail width: '); jQuery("#extended_album_image_thumb_dimensions_x").css('display', 'none'); jQuery("#extended_album_image_thumb_height").css('display', 'none'); jQuery("#tr_extended_album_image_title").css('display', 'none'); } } function bwg_change_label(id, text) { jQuery('#' + id).html(text); } function bwg_gallery_type(gallery_type) { jQuery("#" + gallery_type).prop('checked', true); jQuery("#tr_gallery").css('display', 'none'); jQuery("#tr_sort_by").css('display', 'none'); jQuery("#tr_order_by").css('display', 'none'); jQuery("#tr_show_search_box").css('display', 'none'); jQuery("#tr_search_box_width").css('display', 'none'); jQuery("#tr_album").css('display', 'none'); // Thumbnails, Masonry. jQuery("#tr_masonry_hor_ver").css('display', 'none'); bwg_change_label("col_num_label", 'Max. number of image columns'); jQuery("#tr_image_column_number").css('display', 'none'); jQuery("#tr_images_per_page").css('display', 'none'); jQuery("#tr_image_title_hover").css('display', 'none'); jQuery("#tr_image_enable_page").css('display', 'none'); jQuery("#tr_thumb_width_height").css('display', 'none'); // Compact Album. jQuery("#tr_compuct_album_column_number").css('display', 'none'); jQuery("#tr_compuct_albums_per_page").css('display', 'none'); jQuery("#tr_compuct_album_title_hover").css('display', 'none'); jQuery("#tr_compuct_album_view_type").css('display', 'none'); jQuery("#tr_compuct_album_thumb_width_height").css('display', 'none'); jQuery("#tr_compuct_album_image_column_number").css('display', 'none'); jQuery("#tr_compuct_album_images_per_page").css('display', 'none'); jQuery("#tr_compuct_album_image_title").css('display', 'none'); jQuery("#tr_compuct_album_image_title").css('display', 'none'); jQuery("#tr_compuct_album_image_thumb_width_height").css('display', 'none'); jQuery("#tr_compuct_album_enable_page").css('display', 'none'); // Extended Album. jQuery("#tr_extended_albums_per_page").css('display', 'none'); jQuery("#tr_extended_album_height").css('display', 'none'); jQuery("#tr_extended_album_description_enable").css('display', 'none'); jQuery("#tr_extended_album_view_type").css('display', 'none'); jQuery("#tr_extended_album_thumb_width_height").css('display', 'none'); jQuery("#tr_extended_album_image_column_number").css('display', 'none'); jQuery("#tr_extended_album_images_per_page").css('display', 'none'); jQuery("#tr_extended_album_image_title").css('display', 'none'); jQuery("#tr_extended_album_image_thumb_width_height").css('display', 'none'); jQuery("#tr_extended_album_enable_page").css('display', 'none'); // Image Browser. jQuery("#tr_image_browser_width_height").css('display', 'none'); jQuery("#tr_image_browser_title_enable").css('display', 'none'); jQuery("#tr_image_browser_description_enable").css('display', 'none'); // Blog Style. jQuery("#tr_blog_style_width_height").css('display', 'none'); jQuery("#tr_blog_style_title_enable").css('display', 'none'); jQuery("#tr_blog_style_images_per_page").css('display', 'none'); jQuery("#tr_blog_style_enable_page").css('display', 'none'); // Slideshow. jQuery("#tbody_slideshow").css('display', 'none'); jQuery("#tr_slideshow_effect").css('display', 'none'); jQuery("#tr_slideshow_interval").css('display', 'none'); jQuery("#tr_slideshow_width_height").css('display', 'none'); jQuery("#tr_enable_slideshow_autoplay").css('display', 'none'); jQuery("#tr_enable_slideshow_shuffle").css('display', 'none'); jQuery("#tr_enable_slideshow_ctrl").css('display', 'none'); jQuery("#tr_enable_slideshow_filmstrip").css('display', 'none'); jQuery("#tr_slideshow_filmstrip_height").css('display', 'none'); jQuery("#tr_slideshow_enable_title").css('display', 'none'); jQuery("#tr_slideshow_title_position").css('display', 'none'); jQuery("#tr_slideshow_enable_description").css('display', 'none'); jQuery("#tr_slideshow_description_position").css('display', 'none'); jQuery("#tr_enable_slideshow_music").css('display', 'none'); jQuery("#tr_slideshow_music_url").css('display', 'none'); // Popup. jQuery("#tbody_popup_other").css('display', 'none'); jQuery("#tbody_popup").css('display', 'none'); jQuery("#tr_popup_width_height").css('display', 'none'); jQuery("#tr_popup_effect").css('display', 'none'); jQuery("#tr_popup_interval").css('display', 'none'); jQuery("#tr_popup_enable_filmstrip").css('display', 'none'); jQuery("#tr_popup_filmstrip_height").css('display', 'none'); jQuery("#tr_popup_enable_ctrl_btn").css('display', 'none'); jQuery("#tr_popup_enable_fullscreen").css('display', 'none'); jQuery("#tr_popup_enable_info").css('display', 'none'); jQuery("#tr_popup_enable_rate").css('display', 'none'); jQuery("#tr_popup_enable_comment").css('display', 'none'); jQuery("#tr_popup_enable_facebook").css('display', 'none'); jQuery("#tr_popup_enable_twitter").css('display', 'none'); jQuery("#tr_popup_enable_google").css('display', 'none'); jQuery("#tr_popup_enable_pinterest").css('display', 'none'); jQuery("#tr_popup_enable_tumblr").css('display', 'none'); // Watermark. jQuery("#tr_watermark_type").css('display', ''); if (jQuery("input[name=watermark_type]:checked").val() == 'image') { bwg_watermark('watermark_type_image'); } else if (jQuery("input[name=watermark_type]:checked").val() == 'text'){ bwg_watermark('watermark_type_text'); } else { bwg_watermark('watermark_type_none'); } switch (gallery_type) { case 'thumbnails': { jQuery("#tr_gallery").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); bwg_change_label('image_column_number_label', 'Max. number of image columns: '); bwg_change_label('thumb_width_height_label', 'Image thumbnail dimensions: '); jQuery('#thumb_width').show(); jQuery('#thumb_height').show(); jQuery('#thumb_width_height_separator').show(); jQuery("#tr_image_column_number").css('display', ''); jQuery("#tr_images_per_page").css('display', ''); jQuery("#tr_image_title_hover").css('display', ''); jQuery("#tr_image_enable_page").css('display', ''); jQuery("#tr_thumb_width_height").css('display', ''); bwg_show_search_box(); jQuery("#bwg_pro_version").html('Thumbnails'); jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/thumbnails-view-2/"); break; } case 'thumbnails_masonry': { jQuery("#tr_gallery").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); if (jQuery("input[name=masonry_hor_ver]:checked").val() == 'horizontal') { bwg_change_label('image_column_number_label', 'Number of image rows: '); bwg_change_label('thumb_width_height_label', 'Image thumbnail height: '); jQuery('#thumb_width').hide(); jQuery('#thumb_height').show(); } else { bwg_change_label('image_column_number_label', 'Max. number of image columns: '); bwg_change_label('thumb_width_height_label', 'Image thumbnail width: '); jQuery('#thumb_width').show(); jQuery('#thumb_height').hide(); } jQuery("#tr_masonry_hor_ver").css('display', ''); jQuery('#thumb_width_height_separator').hide(); jQuery("#tr_image_column_number").css('display', ''); jQuery("#tr_images_per_page").css('display', ''); jQuery("#tr_image_enable_page").css('display', ''); jQuery("#tr_thumb_width_height").css('display', ''); bwg_show_search_box(); break; } case 'slideshow': { jQuery("#tr_gallery").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_slideshow_effect").css('display', ''); jQuery("#tr_slideshow_interval").css('display', ''); jQuery("#tr_slideshow_width_height").css('display', ''); jQuery("#tbody_slideshow").css('display', ''); jQuery("#tr_enable_slideshow_autoplay").css('display', ''); jQuery("#tr_enable_slideshow_shuffle").css('display', ''); jQuery("#tr_enable_slideshow_ctrl").css('display', ''); jQuery("#tr_enable_slideshow_filmstrip").css('display', ''); if (jQuery("input[name=enable_slideshow_filmstrip]:checked").val() == 1) { bwg_enable_disable('', 'tr_slideshow_filmstrip_height', 'slideshow_filmstrip_yes'); } else { bwg_enable_disable('none', 'tr_slideshow_filmstrip_height', 'slideshow_filmstrip_no'); } jQuery("#tr_slideshow_enable_title").css('display', ''); if (jQuery("input[name=slideshow_enable_title]:checked").val() == 1) { bwg_enable_disable('', 'tr_slideshow_title_position', 'slideshow_title_yes'); } else { bwg_enable_disable('none', 'tr_slideshow_title_position', 'slideshow_title_no'); } jQuery("#tr_slideshow_enable_description").css('display', ''); if (jQuery("input[name=slideshow_enable_description]:checked").val() == 1) { bwg_enable_disable('', 'tr_slideshow_description_position', 'slideshow_description_yes'); } else { bwg_enable_disable('none', 'tr_slideshow_description_position', 'slideshow_description_no'); } jQuery("#tr_enable_slideshow_music").css('display', ''); if (jQuery("input[name=enable_slideshow_music]:checked").val() == 1) { bwg_enable_disable('', 'tr_slideshow_music_url', 'slideshow_music_yes'); } else { bwg_enable_disable('none', 'tr_slideshow_music_url', 'slideshow_music_no'); } jQuery("#bwg_pro_version").html('Slideshow'); jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/slideshow-view/"); break; } case 'image_browser': { jQuery("#tr_gallery").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); jQuery("#tr_image_browser_width_height").css('display', ''); jQuery("#tr_image_browser_title_enable").css('display', ''); jQuery("#tr_image_browser_description_enable").css('display', ''); bwg_show_search_box(); jQuery("#bwg_pro_version").html('Image Browser'); jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/image-browser-view/"); break; } case 'album_compact_preview': { jQuery("#tr_album").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); jQuery("#tr_compuct_album_column_number").css('display', ''); jQuery("#tr_compuct_albums_per_page").css('display', ''); jQuery("#tr_compuct_album_title_hover").css('display', ''); jQuery("#tr_compuct_album_view_type").css('display', ''); jQuery("#tr_compuct_album_thumb_width_height").css('display', ''); jQuery("#tr_compuct_album_image_column_number").css('display', ''); jQuery("#tr_compuct_album_images_per_page").css('display', ''); jQuery("#tr_compuct_album_image_title").css('display', ''); jQuery("#tr_compuct_album_image_title").css('display', ''); jQuery("#tr_compuct_album_image_thumb_width_height").css('display', ''); jQuery("#tr_compuct_album_enable_page").css('display', ''); bwg_change_compuct_album_view_type(); bwg_show_search_box(); jQuery("#bwg_pro_version").html('Compact Album'); jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/compact-album-view/"); break; } case 'album_extended_preview': { jQuery("#tr_album").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); jQuery("#tr_extended_albums_per_page").css('display', ''); jQuery("#tr_extended_album_height").css('display', ''); jQuery("#tr_extended_album_description_enable").css('display', ''); jQuery("#tr_extended_album_view_type").css('display', ''); jQuery("#tr_extended_album_thumb_width_height").css('display', ''); jQuery("#tr_extended_album_image_column_number").css('display', ''); jQuery("#tr_extended_album_images_per_page").css('display', ''); jQuery("#tr_extended_album_image_title").css('display', ''); jQuery("#tr_extended_album_image_thumb_width_height").css('display', ''); jQuery("#tr_extended_album_enable_page").css('display', ''); bwg_change_extended_album_view_type(); bwg_show_search_box(); jQuery("#bwg_pro_version").html('Extended Album'); jQuery("#bwg_pro_version_link").attr("href", "http://wpdemo.web-dorado.com/extended-album-view/"); break; } case 'blog_style': { jQuery("#tr_gallery").css('display', ''); jQuery("#tr_sort_by").css('display', ''); jQuery("#tr_order_by").css('display', ''); jQuery("#tr_show_search_box").css('display', ''); jQuery("#tr_blog_style_width_height").css('display', ''); jQuery("#tr_blog_style_title_enable").css('display', ''); jQuery("#tr_blog_style_images_per_page").css('display', ''); jQuery("#tr_blog_style_enable_page").css('display', ''); bwg_show_search_box(); break; } } if (gallery_type != 'slideshow') { jQuery("#tbody_popup_other").css('display', ''); jQuery("#tbody_popup").css('display', ''); jQuery("#tr_popup_width_height").css('display', ''); jQuery("#tr_popup_effect").css('display', ''); jQuery("#tr_popup_interval").css('display', ''); jQuery("#tr_popup_enable_filmstrip").css('display', ''); if (jQuery("input[name=popup_enable_filmstrip]:checked").val() == 1) { bwg_enable_disable('', 'tr_popup_filmstrip_height', 'popup_filmstrip_yes'); } else { bwg_enable_disable('none', 'tr_popup_filmstrip_height', 'popup_filmstrip_no'); } jQuery("#tr_popup_enable_ctrl_btn").css('display', ''); if (jQuery("input[name=popup_enable_ctrl_btn]:checked").val() == 1) { bwg_enable_disable('', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_yes'); } else { bwg_enable_disable('none', 'tbody_popup_ctrl_btn', 'popup_ctrl_btn_no'); } jQuery("#tr_popup_enable_fullscreen").css('display', ''); jQuery("#tr_popup_enable_info").css('display', ''); jQuery("#tr_popup_enable_rate").css('display', ''); jQuery("#tr_popup_enable_comment").css('display', ''); jQuery("#tr_popup_enable_facebook").css('display', ''); jQuery("#tr_popup_enable_twitter").css('display', ''); jQuery("#tr_popup_enable_google").css('display', ''); jQuery("#tr_popup_enable_pinterest").css('display', ''); jQuery("#tr_popup_enable_tumblr").css('display', ''); bwg_popup_fullscreen(); bwg_thumb_click_action(); } } function bwg_onKeyDown(e) { var e = e || window.event; var chCode1 = e.which || e.paramlist_keyCode; if (chCode1 != 37 && chCode1 != 38 && chCode1 != 39 && chCode1 != 40) { if ((!e.ctrlKey && !e.metaKey) || (chCode1 != 86 && chCode1 != 67 && chCode1 != 65 && chCode1 != 88)) { e.preventDefault(); } } }
JavaScript
function edit_tag(m) { var name, slug, tr; name = jQuery("#name" + m).html(); slug = jQuery("#slug" + m).html(); tr = ' <td id="td_check_'+m+'" ></td> <td id="td_id_'+m+'" ></td> <td id="td_name_'+m+'" class="edit_input"><input id="edit_tagname" name="tagname'+m+'" class="input_th2" type="text" value="'+name+'"></td> <td id="td_slug_'+m+'" class="edit_input"><input id="edit_slug" class="input_th2" name="slug'+m+'" type="text" value="'+slug+'"></td> <td id="td_count_'+m+'" ></td> <td id="td_edit_'+m+'" class="table_big_col"><a class="button-primary button button-small" onclick="save_tag('+m+')" >Lưu Tag</a></td><td id="td_delete_'+m+'" class="table_big_col" ></td> '; jQuery("#tr_" + m).html(tr); jQuery("#td_id_" + m).attr('class', 'table_big_col'); } function save_tag(tag_id) { var tagname=jQuery('input[name=tagname'+tag_id+']').val(); var slug = jQuery('input[name=slug'+tag_id+']').val(); var datas = "tagname="+tagname+"&"+"slug="+slug+"&"+"tag_id="+tag_id; var td_check,td_name,td_slug,td_count,td_edit,td_delete,massege; jQuery.ajax({ type: "POST", url: ajax_url + "=bwg_edit_tag", data: datas, success: function(html) { var tagname_slug=html; var array = tagname_slug.split("."); if (array[0] == "The slug must be unique.") { massege = array[0]; } else { massege = "Item Succesfully Saved."; jQuery("#td_check_" + tag_id).attr('class', 'table_small_col check-column'); td_check='<input id="check_'+tag_id+'" name="check_'+tag_id+'" type="checkbox" />'; jQuery("#td_check_" + tag_id).html(td_check); jQuery("#td_id_" + tag_id).attr('class', 'table_small_col'); jQuery("#td_id_" + tag_id).html(tag_id); jQuery("#td_name_" + tag_id).removeClass(); td_name='<a class="pointer" id="name'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[0]+'</a>'; jQuery("#td_name_" + tag_id).html(td_name); jQuery("#td_slug_" + tag_id).removeClass(); td_slug='<a class="pointer" id="slug'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[1]+'</a>'; jQuery("#td_slug_" + tag_id).html(td_slug); jQuery("#td_count_" + tag_id).attr('class', 'table_big_col'); td_count='<a class="pointer" id="count'+tag_id+'" onclick="edit_tag('+tag_id+')" title="Edit">'+array[2]+'</a>'; jQuery("#td_count_" + tag_id).html(td_count); td_edit='<a class="pointer" onclick="edit_tag('+tag_id+')" >Sửa</a>'; jQuery("#td_edit_" + tag_id).html(td_edit); var func1="spider_set_input_value('task', 'delete');"; var func2="spider_set_input_value('current_id', "+tag_id+");"; var func3="spider_form_submit('event', 'tags_form')"; td_delete='<a class="pointer" onclick="'+func1+func2+func3+'" >Xóa</a>'; jQuery("#td_delete_" + tag_id).html(td_delete); } if ((jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ) || (jQuery( ".error" ) && jQuery( ".error" ).css("display")=="block")) { if (jQuery( ".updated" ) && jQuery( ".updated" ).attr("id")!='wordpress_message_2' ){ jQuery(".updated").html("<strong><p>"+massege+"</p></strong>"); } else { jQuery(".error").html("<strong><p>"+massege+"</p></strong>"); jQuery(".error").attr('class', 'updated'); } } else { jQuery("#wordpress_message_1").css("display", "block"); } } }); } var bwg_save_count = 50; function spider_ajax_save(form_id, tr_group) { var ajax_task = jQuery("#ajax_task").val(); if (!tr_group) { var tr_group = 1; } else if (ajax_task == 'ajax_apply' || ajax_task == 'ajax_save') { ajax_task = ''; } var name = jQuery("#name").val(); var slug = jQuery("#slug").val(); if ((typeof tinyMCE != "undefined") && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden() && tinyMCE.activeEditor.getContent) { var description = tinyMCE.activeEditor.getContent(); } else { var description = jQuery("#description").val(); } var preview_image = jQuery("#preview_image").val(); var published = jQuery("input[name=published]:checked").val(); var search_value = jQuery("#search_value").val(); var current_id = jQuery("#current_id").val(); var page_number = jQuery("#page_number").val(); var search_or_not = jQuery("#search_or_not").val(); var ids_string = jQuery("#ids_string").val(); var image_order_by = jQuery("#image_order_by").val(); var asc_or_desc = jQuery("#asc_or_desc").val(); var image_current_id = jQuery("#image_current_id").val(); ids_array = ids_string.split(","); var tr_count = ids_array.length; if (tr_count > bwg_save_count) { // Remove items form begin and end of array. ids_array.splice(tr_group * bwg_save_count, ids_array.length); ids_array.splice(0, (tr_group - 1) * bwg_save_count); ids_string = ids_array.join(","); } var post_data = {}; post_data["name"] = name; post_data["slug"] = slug; post_data["description"] = description; post_data["preview_image"] = preview_image; post_data["published"] = published; post_data["search_value"] = search_value; post_data["current_id"] = current_id; post_data["page_number"] = page_number; post_data["image_order_by"] = image_order_by; post_data["asc_or_desc"] = asc_or_desc; post_data["ids_string"] = ids_string; post_data["task"] = "ajax_search"; post_data["ajax_task"] = ajax_task; post_data["image_current_id"] = image_current_id; post_data["image_width"] = jQuery("#image_width").val(); post_data["image_height"] = jQuery("#image_height").val(); var flag = false; if (jQuery("#check_all_items").attr('checked') == 'checked') { post_data["check_all_items"] = jQuery("#check_all_items").val(); post_data["added_tags_select_all"] = jQuery("#added_tags_select_all").val(); flag = true; jQuery('#check_all_items').attr('checked', false); } for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') { post_data["check_" + ids_array[i]] = jQuery("#check_" + ids_array[i]).val(); flag = true; } post_data["input_filename_" + ids_array[i]] = jQuery("#input_filename_" + ids_array[i]).val(); post_data["image_url_" + ids_array[i]] = jQuery("#image_url_" + ids_array[i]).val(); post_data["thumb_url_" + ids_array[i]] = jQuery("#thumb_url_" + ids_array[i]).val(); post_data["image_description_" + ids_array[i]] = jQuery("#image_description_" + ids_array[i]).val(); post_data["image_alt_text_" + ids_array[i]] = jQuery("#image_alt_text_" + ids_array[i]).val(); post_data["redirect_url_" + ids_array[i]] = jQuery("#redirect_url_" + ids_array[i]).val(); post_data["input_date_modified_" + ids_array[i]] = jQuery("#input_date_modified_" + ids_array[i]).val(); post_data["input_size_" + ids_array[i]] = jQuery("#input_size_" + ids_array[i]).val(); post_data["input_filetype_" + ids_array[i]] = jQuery("#input_filetype_" + ids_array[i]).val(); post_data["input_resolution_" + ids_array[i]] = jQuery("#input_resolution_" + ids_array[i]).val(); post_data["input_crop_" + ids_array[i]] = jQuery("#input_crop_" + ids_array[i]).val(); post_data["order_input_" + ids_array[i]] = jQuery("#order_input_" + ids_array[i]).val(); post_data["tags_" + ids_array[i]] = jQuery("#tags_" + ids_array[i]).val(); } } // Loading. jQuery('#opacity_div').show(); jQuery('#loading_div').show(); jQuery.post( jQuery('#' + form_id).action, post_data, function (data) { var str = jQuery(data).find("#current_id").val(); jQuery("#current_id").val(str); } ).success(function (data, textStatus, errorThrown) { if (tr_count > bwg_save_count * tr_group) { spider_ajax_save(form_id, ++tr_group); return; } else { var str = jQuery(data).find('#images_table').html(); jQuery('#images_table').html(str); var str = jQuery(data).find('.tablenav').html(); jQuery('.tablenav').html(str); jQuery("#show_hide_weights").val("Ẩn thứ tự cột"); spider_show_hide_weights(); spider_run_checkbox(); if (ajax_task == 'ajax_apply') { jQuery('#message_div').html("<strong><p>Lưu thành công.</p></strong>"); jQuery('#message_div').show(); } else if (ajax_task == 'recover') { jQuery('#draganddrop').html("<strong><p>Phục hồi thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_publish') { jQuery('#draganddrop').html("<strong><p>Hiển thị công cộng thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_unpublish') { jQuery('#draganddrop').html("<strong><p>Hiển thị riêng tư thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_delete') { jQuery('#draganddrop').html("<strong><p>Xóa thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (!flag && ((ajax_task == 'image_publish_all') || (ajax_task == 'image_unpublish_all') || (ajax_task == 'image_delete_all') || (ajax_task == 'image_set_watermark') || (ajax_task == 'image_recover_all') || (ajax_task == 'image_resize'))) { jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một mục.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_publish_all') { jQuery('#draganddrop').html("<strong><p>Hiển thị công cộng thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_unpublish_all') { jQuery('#draganddrop').html("<strong><p>Hiển thị riêng tư thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_delete_all') { jQuery('#draganddrop').html("<strong><p>Xóa thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_set_watermark') { jQuery('#draganddrop').html("<strong><p>Làm mờ thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_resize') { jQuery('#draganddrop').html("<strong><p>Đổi kích cở thành công.</p></strong>"); jQuery('#draganddrop').show(); } else if (ajax_task == 'image_recover_all') { jQuery('#draganddrop').html("<strong><p>Đặt lại thành công.</p></strong>"); jQuery('#draganddrop').show(); } else { jQuery('#draganddrop').html("<strong><p>Lưu thành công.</p></strong>"); jQuery('#draganddrop').show(); } if (ajax_task == "ajax_save") { jQuery('#' + form_id).submit(); } jQuery('#opacity_div').hide(); jQuery('#loading_div').hide(); } }); // if (event.preventDefault) { // event.preventDefault(); // } // else { // event.returnValue = false; // } return false; } function save_location_all(url) { var ids_string = jQuery('#ids_string').val(); var ids_array = ids_string.split(','); var post_ids=[]; for(var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') { post_ids.push(ids_array[i]); } } } if (post_ids.length==0) { jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một ảnh.</p></strong>"); jQuery('#draganddrop').show(); return; } else jQuery('#draganddrop').hide(); var mapForm = document.createElement("form"); mapForm.target = "Map"; mapForm.method = "POST"; // or "post" if appropriate mapForm.action = url; var mapInput = document.createElement("input"); mapInput.type = "hidden"; mapInput.name = "image_ids"; mapInput.value = post_ids; mapForm.appendChild(mapInput); document.body.appendChild(mapForm); map=window.open('','Map','height=1000,width=1000'); if (map) { mapForm.submit(); if (window.focus) {map.focus();} var timer = setInterval( function(){ if(!map.closed) return; clearInterval(timer); var album_id=jQuery("#current_id").val(); spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', album_id); spider_form_submit(event, 'galleries_form'); },1000); } else { alert('Popup cần được cho phép để thực hiện chức năng.'); } ///load lại trang hiện tại } function save_location(url,id) { var mapForm = document.createElement("form"); mapForm.target = "Map"; mapForm.method = "POST"; // or "post" if appropriate mapForm.action = url; var mapInput = document.createElement("input"); mapInput.type = "hidden"; mapInput.name = "image_ids"; mapInput.value = id; mapForm.appendChild(mapInput); document.body.appendChild(mapForm); map=window.open('','Map','height=1000,width=1000'); if (map) { mapForm.submit(); if (window.focus) {map.focus();} var timer = setInterval(function() { if(map.closed) { clearInterval(timer); var album_id=jQuery("#current_id").val(); spider_set_input_value('task', 'edit'); spider_set_input_value('page_number', '1'); spider_set_input_value('search_value', ''); spider_set_input_value('search_or_not', ''); spider_set_input_value('asc_or_desc', 'asc'); spider_set_input_value('order_by', 'order'); spider_set_input_value('current_id', album_id); spider_form_submit(event, 'galleries_form'); } }, 1000); } else { alert('Popup cần được cho phép để thực hiện chức năng.'); } ///load lại trang hiện tại ///var timer = setInterval(function() { } function spider_run_checkbox() { jQuery("tbody").children().children(".check-column").find(":checkbox").click(function (l) { if ("undefined" == l.shiftKey) { return true } if (l.shiftKey) { if (!i) { return true } d = jQuery(i).closest("form").find(":checkbox"); f = d.index(i); j = d.index(this); h = jQuery(this).prop("checked"); if (0 < f && 0 < j && f != j) { d.slice(f, j).prop("checked", function () { if (jQuery(this).closest("tr").is(":visible")) { return h } return false }) } } i = this; var k = jQuery(this).closest("tbody").find(":checkbox").filter(":visible").not(":checked"); jQuery(this).closest("table").children("thead, tfoot").find(":checkbox").prop("checked", function () { return(0 == k.length) }); return true }); jQuery("thead, tfoot").find(".check-column :checkbox").click(function (m) { var n = jQuery(this).prop("checked"), l = "undefined" == typeof toggleWithKeyboard ? false : toggleWithKeyboard, k = m.shiftKey || l; jQuery(this).closest("table").children("tbody").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () { if (jQuery(this).is(":hidden")) { return false } if (k) { return jQuery(this).prop("checked") } else { if (n) { return true } } return false }); jQuery(this).closest("table").children("thead, tfoot").filter(":visible").children().children(".check-column").find(":checkbox").prop("checked", function () { if (k) { return false } else { if (n) { return true } } return false }) }); } // Set value by id. function spider_set_input_value(input_id, input_value) { if (document.getElementById(input_id)) { document.getElementById(input_id).value = input_value; } } // Submit form by id. function spider_form_submit(event, form_id) { if (document.getElementById(form_id)) { document.getElementById(form_id).submit(); } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } // Check if required field is empty. function spider_check_required(id, name) { if (jQuery('#' + id).val() == '') { alert(name + '* field is required.'); jQuery('#' + id).attr('style', 'border-color: #FF0000;'); jQuery('#' + id).focus(); jQuery('html, body').animate({ scrollTop:jQuery('#' + id).offset().top - 200 }, 500); return true; } else { return false; } } // Show/hide order column and drag and drop column. function spider_show_hide_weights() { if (jQuery("#show_hide_weights").val() == 'Hiện thứ tự cột') { jQuery(".connectedSortable").css("cursor", "default"); jQuery("#tbody_arr").find(".handle").hide(0); jQuery("#th_order").show(0); jQuery("#tbody_arr").find(".spider_order").show(0); jQuery("#show_hide_weights").val("Ẩn thứ tự cột"); if (jQuery("#tbody_arr").sortable()) { jQuery("#tbody_arr").sortable("disable"); } } else { jQuery(".connectedSortable").css("cursor", "move"); var page_number; if (jQuery("#page_number") && jQuery("#page_number").val() != '' && jQuery("#page_number").val() != 1) { page_number = (jQuery("#page_number").val() - 1) * 20 + 1; } else { page_number = 1; } jQuery("#tbody_arr").sortable({ handle:".connectedSortable", connectWith:".connectedSortable", update:function (event, tr) { jQuery("#draganddrop").attr("style", ""); jQuery("#draganddrop").html("<strong><p>Thay đổi nên được lưu lại.</p></strong>"); var i = page_number; jQuery('.spider_order').each(function (e) { if (jQuery(this).find('input').val()) { jQuery(this).find('input').val(i++); } }); } });//.disableSelection(); jQuery("#tbody_arr").sortable("enable"); jQuery("#tbody_arr").find(".handle").show(0); jQuery("#tbody_arr").find(".handle").attr('class', 'handle connectedSortable'); jQuery("#th_order").hide(0); jQuery("#tbody_arr").find(".spider_order").hide(0); jQuery("#show_hide_weights").val("Hiện thứ tự cột"); } } // Check all items. function spider_check_all_items() { spider_check_all_items_checkbox(); // if (!jQuery('#check_all').attr('checked')) { jQuery('#check_all').trigger('click'); // } } function spider_check_all_items_checkbox() { if (jQuery('#check_all_items').attr('checked')) { jQuery('#check_all_items').attr('checked', false); jQuery('#draganddrop').hide(); } else { var saved_items = (parseInt(jQuery(".displaying-num").html()) ? parseInt(jQuery(".displaying-num").html()) : 0); var added_items = (jQuery('input[id^="check_pr_"]').length ? parseInt(jQuery('input[id^="check_pr_"]').length) : 0); var items_count = added_items + saved_items; jQuery('#check_all_items').attr('checked', true); if (items_count) { jQuery('#draganddrop').html("<strong><p>Selected " + items_count + " item" + (items_count > 1 ? "s" : "") + ".</p></strong>"); jQuery('#draganddrop').show(); } } } function spider_check_all(current) { if (!jQuery(current).attr('checked')) { jQuery('#check_all_items').attr('checked', false); jQuery('#draganddrop').hide(); } } // Set uploader to button class. function spider_uploader(button_id, input_id, delete_id, img_id) { if (typeof img_id == 'undefined') { img_id = ''; } jQuery(function () { var formfield = null; window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function (html) { if (formfield) { var fileurl = jQuery('img', html).attr('src'); if (!fileurl) { var exploded_html; var exploded_html_askofen; exploded_html = html.split('"'); for (i = 0; i < exploded_html.length; i++) { exploded_html_askofen = exploded_html[i].split("'"); } for (i = 0; i < exploded_html.length; i++) { for (j = 0; j < exploded_html_askofen.length; j++) { if (exploded_html_askofen[j].search("href")) { fileurl = exploded_html_askofen[i + 1]; break; } } } if (img_id != '') { alert('Bạn phải chọn một ảnh.'); tb_remove(); return; } window.parent.document.getElementById(input_id).value = fileurl; window.parent.document.getElementById(button_id).style.display = "none"; window.parent.document.getElementById(input_id).style.display = "inline-block"; window.parent.document.getElementById(delete_id).style.display = "inline-block"; } else { if (img_id == '') { alert('You must select an audio file.'); tb_remove(); return; } window.parent.document.getElementById(input_id).value = fileurl; window.parent.document.getElementById(button_id).style.display = "none"; window.parent.document.getElementById(delete_id).style.display = "inline-block"; if ((img_id != '') && window.parent.document.getElementById(img_id)) { window.parent.document.getElementById(img_id).src = fileurl; window.parent.document.getElementById(img_id).style.display = "inline-block"; } } formfield.val(fileurl); tb_remove(); } else { window.original_send_to_editor(html); } formfield = null; }; formfield = jQuery(this).parent().parent().find(".url_input"); tb_show('', 'media-upload.php?type=image&TB_iframe=true'); jQuery('#TB_overlay,#TB_closeWindowButton').bind("click", function () { formfield = null; }); return false; }); } // Remove uploaded file. function spider_remove_url(button_id, input_id, delete_id, img_id) { if (typeof img_id == 'undefined') { img_id = ''; } if (document.getElementById(button_id)) { document.getElementById(button_id).style.display = ''; } if (document.getElementById(input_id)) { document.getElementById(input_id).value = ''; document.getElementById(input_id).style.display = 'none'; } if (document.getElementById(delete_id)) { document.getElementById(delete_id).style.display = 'none'; } if ((img_id != '') && window.parent.document.getElementById(img_id)) { document.getElementById(img_id).src = ''; document.getElementById(img_id).style.display = 'none'; } } function spider_reorder_items(tbody_id) { jQuery("#" + tbody_id).sortable({ handle:".connectedSortable", connectWith:".connectedSortable", update:function (event, tr) { spider_sortt(tbody_id); } }); } function spider_sortt(tbody_id) { var str = ""; var counter = 0; jQuery("#" + tbody_id).children().each(function () { str += ((jQuery(this).attr("id")).substr(3) + ","); counter++; }); jQuery("#albums_galleries").val(str); if (!counter) { document.getElementById("table_albums_galleries").style.display = "none"; } } function spider_remove_row(tbody_id, event, obj) { var span = obj; var tr = jQuery(span).closest("tr"); jQuery(tr).remove(); spider_sortt(tbody_id); } function spider_jslider(idtaginp) { jQuery(function () { var inpvalue = jQuery("#" + idtaginp).val(); if (inpvalue == "") { inpvalue = 50; } jQuery("#slider-" + idtaginp).slider({ range:"min", value:inpvalue, min:1, max:100, slide:function (event, ui) { jQuery("#" + idtaginp).val("" + ui.value); } }); jQuery("#" + idtaginp).val("" + jQuery("#slider-" + idtaginp).slider("value")); }); } function spider_get_items(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } var trackIds = []; var titles = []; var types = []; var tbody = document.getElementById('tbody_albums_galleries'); var trs = tbody.getElementsByTagName('tr'); for (j = 0; j < trs.length; j++) { i = trs[j].getAttribute('id').substr(3); if (document.getElementById('check_' + i).checked) { trackIds.push(document.getElementById("id_" + i).innerHTML); titles.push(document.getElementById("a_" + i).innerHTML); types.push(document.getElementById("url_" + i).innerHTML == "Album" ? 1 : 0); } } window.parent.bwg_add_items(trackIds, titles, types); } function bwg_check_checkboxes() { var flag = false; var ids_string = jQuery("#ids_string").val(); ids_array = ids_string.split(","); for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked') { flag = true; } } } if(flag) { if(jQuery(".buttons_div_right").find("a").hasClass( "thickbox" )) { return true; } else { jQuery(".buttons_div_right").find("a").addClass( "thickbox thickbox-preview" ); jQuery('#draganddrop').hide(); return true; } } else { jQuery(".buttons_div_right").find("a").removeClass( "thickbox thickbox-preview" ); jQuery('#draganddrop').html("<strong><p>Bạn phải chọn ít nhất một mục.</p></strong>"); jQuery('#draganddrop').show(); return false; } } function bwg_get_tags(image_id, e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } var tagIds = []; var titles = []; var tbody = document.getElementById('tbody_arr'); var trs = tbody.getElementsByTagName('tr'); for (j = 0; j < trs.length; j++) { i = trs[j].getAttribute('id').substr(3); if (document.getElementById('check_' + i).checked) { tagIds.push(i); titles.push(document.getElementById("a_" + i).innerHTML); } } window.parent.bwg_add_tag(image_id, tagIds, titles); } function bwg_add_tag(image_id, tagIds, titles) { if (image_id == '0') { var flag = false; var ids_string = jQuery("#ids_string").val(); ids_array = ids_string.split(","); if (jQuery("#check_all_items").attr("checked")) { var added_tags = ''; for (i = 0; i < tagIds.length; i++) { added_tags = added_tags + tagIds[i] + ','; } jQuery("#added_tags_select_all").val(added_tags); } } else { image_id = image_id + ','; ids_array = image_id.split(","); var flag = true; } for (var i in ids_array) { if (ids_array.hasOwnProperty(i) && ids_array[i]) { if (jQuery("#check_" + ids_array[i]).attr('checked') == 'checked' || flag) { image_id = ids_array[i]; var tag_ids = document.getElementById('tags_' + image_id).value; tags_array = tag_ids.split(','); var div = document.getElementById('tags_div_' + image_id); var counter = 0; for (i = 0; i < tagIds.length; i++) { if (tags_array.indexOf(tagIds[i]) == -1) { tag_ids = tag_ids + tagIds[i] + ','; var tag_div = document.createElement('div'); tag_div.setAttribute('id', image_id + "_tag_" + tagIds[i]); tag_div.setAttribute('class', "tag_div"); div.appendChild(tag_div); var tag_name_span = document.createElement('span'); tag_name_span.setAttribute('class', "tag_name"); tag_name_span.innerHTML = titles[i]; tag_div.appendChild(tag_name_span); var tag_delete_span = document.createElement('span'); tag_delete_span.setAttribute('class', "spider_delete_img_small"); tag_delete_span.setAttribute('onclick', "bwg_remove_tag('" + tagIds[i] + "', '" + image_id + "')"); tag_delete_span.setAttribute('style', "float:right;"); tag_div.appendChild(tag_delete_span); counter++; } } document.getElementById('tags_' + image_id).value = tag_ids; if (counter) { div.style.display = "block"; } } } } tb_remove(); } function bwg_remove_tag(tag_id, image_id) { if (jQuery('#' + image_id + '_tag_' + tag_id)) { jQuery('#' + image_id + '_tag_' + tag_id).remove(); var tag_ids_string = jQuery("#tags_" + image_id).val(); tag_ids_string = tag_ids_string.replace(tag_id + ',', ''); jQuery("#tags_" + image_id).val(tag_ids_string); if (jQuery("#tags_" + image_id).val() == '') { jQuery("#tags_div_" + image_id).hide(); } } } function preview_watermark() { setTimeout(function() { watermark_type = window.parent.document.getElementById('watermark_type_text').checked; if (watermark_type) { watermark_text = document.getElementById('watermark_text').value; watermark_link = document.getElementById('watermark_link').value; watermark_font_size = document.getElementById('watermark_font_size').value; watermark_font = document.getElementById('watermark_font').value; watermark_color = document.getElementById('watermark_color').value; watermark_opacity = document.getElementById('watermark_opacity').value; watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-'); document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_watermark").style.textAlign = watermark_position[1]; stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank" style="text-decoration: none;' : '<span style="cursor:default;') + 'margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + (watermark_link ? '</a>' : '</span>'); document.getElementById("preview_watermark").innerHTML = stringHTML; } watermark_type = window.parent.document.getElementById('watermark_type_image').checked; if (watermark_type) { watermark_url = document.getElementById('watermark_url').value; watermark_link = document.getElementById('watermark_link').value; watermark_width = document.getElementById('watermark_width').value; watermark_height = document.getElementById('watermark_height').value; watermark_opacity = document.getElementById('watermark_opacity').value; watermark_position = jQuery("input[name=watermark_position]:checked").val().split('-'); document.getElementById("preview_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_watermark").style.textAlign = watermark_position[1]; stringHTML = (watermark_link ? '<a href="' + watermark_link + '" target="_blank">' : '') + '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:' + watermark_width + 'px;max-height:' + watermark_height + 'px;opacity:' + (watermark_opacity / 100) + ';" />' + (watermark_link ? '</a>' : ''); document.getElementById("preview_watermark").innerHTML = stringHTML; } }, 50); } function preview_built_in_watermark() { setTimeout(function(){ watermark_type = window.parent.document.getElementById('built_in_watermark_type_text').checked; if (watermark_type) { watermark_text = document.getElementById('built_in_watermark_text').value; watermark_font_size = document.getElementById('built_in_watermark_font_size').value * 400 / 500; watermark_font = 'bwg_' + document.getElementById('built_in_watermark_font').value.replace('.TTF', '').replace('.ttf', ''); watermark_color = document.getElementById('built_in_watermark_color').value; watermark_opacity = document.getElementById('built_in_watermark_opacity').value; watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-'); document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1]; stringHTML = '<span style="cursor:default;margin:4px;font-size:' + watermark_font_size + 'px;font-family:' + watermark_font + ';color:#' + watermark_color + ';opacity:' + (watermark_opacity / 100) + ';" class="non_selectable">' + watermark_text + '</span>'; document.getElementById("preview_built_in_watermark").innerHTML = stringHTML; } watermark_type = window.parent.document.getElementById('built_in_watermark_type_image').checked; if (watermark_type) { watermark_url = document.getElementById('built_in_watermark_url').value; watermark_size = document.getElementById('built_in_watermark_size').value; watermark_position = jQuery("input[name=built_in_watermark_position]:checked").val().split('-'); document.getElementById("preview_built_in_watermark").style.verticalAlign = watermark_position[0]; document.getElementById("preview_built_in_watermark").style.textAlign = watermark_position[1]; stringHTML = '<img class="non_selectable" src="' + watermark_url + '" style="margin:0 4px 0 4px;max-width:95%;width:' + watermark_size + '%;" />'; document.getElementById("preview_built_in_watermark").innerHTML = stringHTML; } }, 50); } function bwg_watermark(watermark_type) { jQuery("#" + watermark_type).attr('checked', 'checked'); jQuery("#tr_watermark_url").css('display', 'none'); jQuery("#tr_watermark_width_height").css('display', 'none'); jQuery("#tr_watermark_opacity").css('display', 'none'); jQuery("#tr_watermark_text").css('display', 'none'); jQuery("#tr_watermark_link").css('display', 'none'); jQuery("#tr_watermark_font_size").css('display', 'none'); jQuery("#tr_watermark_font").css('display', 'none'); jQuery("#tr_watermark_color").css('display', 'none'); jQuery("#tr_watermark_position").css('display', 'none'); jQuery("#tr_watermark_preview").css('display', 'none'); jQuery("#preview_watermark").css('display', 'none'); switch (watermark_type) { case 'watermark_type_text': { jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_text").css('display', ''); jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_font_size").css('display', ''); jQuery("#tr_watermark_font").css('display', ''); jQuery("#tr_watermark_color").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); jQuery("#tr_watermark_preview").css('display', ''); jQuery("#preview_watermark").css('display', 'table-cell'); break; } case 'watermark_type_image': { jQuery("#tr_watermark_url").css('display', ''); jQuery("#tr_watermark_link").css('display', ''); jQuery("#tr_watermark_width_height").css('display', ''); jQuery("#tr_watermark_opacity").css('display', ''); jQuery("#tr_watermark_position").css('display', ''); jQuery("#tr_watermark_preview").css('display', ''); jQuery("#preview_watermark").css('display', 'table-cell'); break; } } } function bwg_built_in_watermark(watermark_type) { jQuery("#built_in_" + watermark_type).attr('checked', 'checked'); jQuery("#tr_built_in_watermark_url").css('display', 'none'); jQuery("#tr_built_in_watermark_size").css('display', 'none'); jQuery("#tr_built_in_watermark_opacity").css('display', 'none'); jQuery("#tr_built_in_watermark_text").css('display', 'none'); jQuery("#tr_built_in_watermark_font_size").css('display', 'none'); jQuery("#tr_built_in_watermark_font").css('display', 'none'); jQuery("#tr_built_in_watermark_color").css('display', 'none'); jQuery("#tr_built_in_watermark_position").css('display', 'none'); jQuery("#tr_built_in_watermark_preview").css('display', 'none'); jQuery("#preview_built_in_watermark").css('display', 'none'); switch (watermark_type) { case 'watermark_type_text': { jQuery("#tr_built_in_watermark_opacity").css('display', ''); jQuery("#tr_built_in_watermark_text").css('display', ''); jQuery("#tr_built_in_watermark_font_size").css('display', ''); jQuery("#tr_built_in_watermark_font").css('display', ''); jQuery("#tr_built_in_watermark_color").css('display', ''); jQuery("#tr_built_in_watermark_position").css('display', ''); jQuery("#tr_built_in_watermark_preview").css('display', ''); jQuery("#preview_built_in_watermark").css('display', 'table-cell'); break; } case 'watermark_type_image': { jQuery("#tr_built_in_watermark_url").css('display', ''); jQuery("#tr_built_in_watermark_size").css('display', ''); jQuery("#tr_built_in_watermark_position").css('display', ''); jQuery("#tr_built_in_watermark_preview").css('display', ''); jQuery("#preview_built_in_watermark").css('display', 'table-cell'); break; } } } function bwg_change_option_type(type) { type = (type == '' ? 1 : type); document.getElementById('type').value = type; for (var i = 1; i <= 8; i++) { if (i == type) { document.getElementById('div_content_' + i).style.display = 'block'; document.getElementById('div_' + i).style.background = '#C5C5C5'; } else { document.getElementById('div_content_' + i).style.display = 'none'; document.getElementById('div_' + i).style.background = '#F4F4F4'; } } document.getElementById('display_panel').style.display = 'inline-block'; } function bwg_inputs() { jQuery(".spider_int_input").keypress(function (event) { var chCode1 = event.which || event.paramlist_keyCode; if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) { return false; } return true; }); } function bwg_enable_disable(display, id, current) { jQuery("#" + current).attr('checked', 'checked'); jQuery("#" + id).css('display', display); } function bwg_popup_fullscreen(num) { if (num) { jQuery("#tr_popup_dimensions").css('display', 'none'); } else { jQuery("#tr_popup_dimensions").css('display', ''); } } function bwg_change_album_view_type(type) { if (type == 'thumbnail') { jQuery("#album_thumb_dimensions").html('Kích thước ảnh đại diện album: '); jQuery("#album_thumb_dimensions_x").css('display', ''); jQuery("#album_thumb_height").css('display', ''); } else { jQuery("#album_thumb_dimensions").html('Chiều rộng ảnh đại diện album: '); jQuery("#album_thumb_dimensions_x").css('display', 'none'); jQuery("#album_thumb_height").css('display', 'none'); } } function spider_check_isnum(e) { var chCode1 = e.which || e.paramlist_keyCode; if (chCode1 > 31 && (chCode1 < 48 || chCode1 > 57) && (chCode1 != 46) && (chCode1 != 45)) { return false; } return true; } function bwg_change_theme_type(type) { var button_name = jQuery("#button_name").val(); jQuery("#Thumbnail").hide(); jQuery("#Masonry").hide(); jQuery("#Slideshow").hide(); jQuery("#Compact_album").hide(); jQuery("#Extended_album").hide(); jQuery("#Image_browser").hide(); jQuery("#Blog_style").hide(); jQuery("#Lightbox").hide(); jQuery("#Navigation").hide(); jQuery("#" + type).show(); jQuery("#type_menu").show(); jQuery(".spider_fieldset").show(); jQuery("#current_type").val(type); jQuery("#type_Thumbnail").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Masonry").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Slideshow").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Compact_album").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Extended_album").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Image_browser").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Blog_style").attr("style", "background-color: #F4F4F4; opacity: 0.4; filter: Alpha(opacity=40);"); jQuery("#type_Lightbox").attr("style", "background-color: #F4F4F4;"); jQuery("#type_Navigation").attr("style", "background-color: #F4F4F4;"); jQuery("#type_" + type).attr("style", "background-color: #CFCBCB;"); } function bwg_get_video_host(url) { if ((/youtu\.be/i).test(url) || (/youtube\.com\/watch/i).test(url) || (/youtube\.com\/.*/i).test(url)) { return 'YOUTUBE'; } if ((/vimeo\.com/i).test(url)) { return 'VIMEO'; } alert('Enter only YouTube or Vimeo url.'); return ''; } function bwg_get_youtube_video_id(url) { // pattern = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; // var matches = url.match(pattern); // if (matches && (matches[7]).length == 11) { // return matches[7]; // } // return ''; var video_id; var url_parts = url.split('v='); if (url_parts.length <= 1) { url_parts = url.split('/v/'); if (url_parts.length <= 1) { url_parts = url_parts[url_parts.length - 1].split('/'); if (url_parts.length <= 1) { url_parts = url_parts[0].split('?'); } } url_parts = url_parts[url_parts.length - 1].split('&'); if (url_parts.length <= 1) { url_parts = url_parts[url_parts.length - 1].split('?'); } } else { url_parts = url_parts[url_parts.length - 1].split('&'); if (url_parts.length <= 1) { url_parts = url_parts[url_parts.length - 1].split('#'); } } video_id = url_parts[0].split('?')[0]; return video_id ? video_id : false; } function bwg_get_vimeo_video_id(url) { // pattern = /\/\/(www\.)?vimeo.com\/(\d+)($|\/)/; // var matches = url.match(pattern); // if (matches) { // return matches[2]; // } // return ''; var url_parts var video_id; url_parts = url.split('/'); url_parts = url_parts[url_parts.length - 1].split('?'); video_id = url_parts[0]; return video_id ? video_id : false; } function bwg_get_video_info(input_id) { var url = jQuery("#" + input_id).val(); if (!url) { alert('Please enter video url to add.'); return ''; } var host = bwg_get_video_host(url); var filesValid = []; var fileData = []; switch (host) { case 'YOUTUBE': var video_id = bwg_get_youtube_video_id(url); if (video_id) { jQuery.getJSON('http://gdata.youtube.com/feeds/api/videos/'+video_id+'?v=2&alt=jsonc',function(data,status,xhr){ fileData['name'] = data.data.title; fileData['description'] = data.data.description; fileData['filename'] = video_id; fileData['url'] = url; fileData['reliative_url'] = url; fileData['thumb_url'] = data.data.thumbnail.hqDefault; fileData['thumb'] = data.data.thumbnail.hqDefault; fileData['size'] = bwg_convert_seconds(data.data.duration); fileData['filetype'] = 'YOUTUBE'; fileData['date_modified'] = bwg_convert_date(data.data.uploaded, 'T'); fileData['resolution'] = ''; fileData['redirect_url'] = ''; filesValid.push(fileData); bwg_add_image(filesValid); document.getElementById(input_id).value = ''; }); return 'ok'; } else { alert('Please enter a valid YouTube link.'); return ''; } case 'VIMEO': var video_id = bwg_get_vimeo_video_id(url); if (video_id) { jQuery.getJSON('http://vimeo.com/api/v2/video/'+video_id+'.json',function(data,status,xhr){ fileData['name'] = data[0].title; fileData['description'] = data[0].description; fileData['filename'] = video_id; fileData['url'] = url; fileData['reliative_url'] = url; fileData['thumb_url'] = data[0].thumbnail_large; fileData['thumb'] = data[0].thumbnail_large; fileData['size'] = bwg_convert_seconds(data[0].duration); fileData['filetype'] = 'VIMEO'; fileData['date_modified'] = bwg_convert_date(data[0].upload_date, ' '); fileData['resolution'] = ''; fileData['redirect_url'] = ''; filesValid.push(fileData); bwg_add_image(filesValid); document.getElementById(input_id).value = ''; }); return 'ok'; } else { alert('Please enter a valid Vimeo link.'); return ''; } default: return ''; } } function bwg_convert_seconds(seconds) { var sec_num = parseInt(seconds, 10); var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); if (minutes < 10 && hours != 0) {minutes = "0" + minutes;} if (seconds < 10) {seconds = "0" + seconds;} var time = (hours != 0 ? hours + ':' : '') + minutes + ':' + seconds; return time; } function bwg_convert_date(date, separator) { var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); date = date.split(separator); var dateArray = date[0].split("-"); return dateArray[2] + " " + m_names[dateArray[1] - 1] + " " + dateArray[0] + ", " + date[1].substring(0, 5); } jQuery(window).ready(function() { jQuery('#wpcontent').css('margin','0'); jQuery('.update-nag').css('display','none'); if(jQuery('.update-nag').next().is("div")) jQuery('.update-nag').next().css('display','none'); jQuery('#wpfooter').css('display','none'); jQuery('body').css('visibility','visible'); var h=jQuery(document).height();//lấy chiều cao bằng chiều cao của nôi dung window.parent.jQuery('iframe').css('min-height',h+50); var w=jQuery("#images_table").width()+100; window.parent.jQuery('iframe').css({'min-width':w, "overflow":'visible'}); if (w>1200) window.parent.jQuery("#primary").css({"margin-left":"50px"}); });
JavaScript
(function () { tinymce.create('tinymce.plugins.bwg_mce', { init:function (ed, url) { var c = this; c.url = url; c.editor = ed; ed.addCommand('mcebwg_mce', function () { ed.windowManager.open({ file:bwg_admin_ajax, width:1100 + ed.getLang('bwg_mce.delta_width', 0), height:550 + ed.getLang('bwg_mce.delta_height', 0), inline:1 }, { plugin_url:url }); var e = ed.selection.getNode(), d = wp.media.gallery, f; if (typeof wp === "undefined" || !wp.media || !wp.media.gallery) { return } if (e.nodeName != "IMG" || ed.dom.getAttrib(e, "class").indexOf("bwg_shortcode") == -1) { return } f = d.edit("[" + ed.dom.getAttrib(e, "title") + "]"); }); ed.addButton('bwg_mce', { title:'Insert Photo Gallery', cmd:'mcebwg_mce', image: url + '/images/bwg_edit_but.png' }); ed.onMouseDown.add(function (d, f) { if (f.target.nodeName == "IMG" && d.dom.hasClass(f.target, "bwg_shortcode")) { var g = tinymce.activeEditor; g.wpGalleryBookmark = g.selection.getBookmark("simple"); g.execCommand("mcebwg_mce"); } }); ed.onBeforeSetContent.add(function (d, e) { e.content = c._do_bwg(e.content) }); ed.onPostProcess.add(function (d, e) { if (e.get) { e.content = c._get_bwg(e.content) } }) }, _do_bwg:function (ed) { return ed.replace(/\[Best_Wordpress_Gallery([^\]]*)\]/g, function (d, c) { return '<img src="' + bwg_plugin_url + '/images/bwg_shortcode.png" class="bwg_shortcode mceItem" title="Best_Wordpress_Gallery' + tinymce.DOM.encode(c) + '" />'; }) }, _get_bwg:function (b) { function ed(c, d) { d = new RegExp(d + '="([^"]+)"', "g").exec(c); return d ? tinymce.DOM.decode(d[1]) : ""; } return b.replace(/(?:<p[^>]*>)*(<img[^>]+>)(?:<\/p>)*/g, function (e, d) { var c = ed(d, "class"); if (c.indexOf("bwg_shortcode") != -1) { return "<p>[" + tinymce.trim(ed(d, "title")) + "]</p>" } return e }) } }); tinymce.PluginManager.add('bwg_mce', tinymce.plugins.bwg_mce); })();
JavaScript
var isPopUpOpened = false; function spider_createpopup(url, current_view, width, height, duration, description, lifetime) { if (isPopUpOpened) { return }; isPopUpOpened = true; if (spider_hasalreadyreceivedpopup(description) || spider_isunsupporteduseragent()) { return; } jQuery("html").attr("style", "overflow:hidden !important;"); jQuery("#spider_popup_loading_" + current_view).css({display: "block"}); jQuery("#spider_popup_overlay_" + current_view).css({display: "block"}); jQuery.get(url, function(data) { var popup = jQuery( '<div id="spider_popup_wrap" class="spider_popup_wrap" style="' + ' width:' + width + 'px;' + ' height:' + height + 'px;' + ' margin-top:-' + height / 2 + 'px;' + ' margin-left: -' + width / 2 + 'px; ">' + data + '</div>') .hide() .appendTo("body"); spider_showpopup(description, lifetime, popup, duration); }).success(function(jqXHR, textStatus, errorThrown) { jQuery("#spider_popup_loading_" + current_view).css({display: "none !important;"}); }); } function spider_showpopup(description, lifetime, popup, duration) { isPopUpOpened = true; popup.show(); spider_receivedpopup(description, lifetime); } function spider_hasalreadyreceivedpopup(description) { if (document.cookie.indexOf(description) > -1) { delete document.cookie[document.cookie.indexOf(description)]; } return false; } function spider_receivedpopup(description, lifetime) { var date = new Date(); date.setDate(date.getDate() + lifetime); document.cookie = description + "=true;expires=" + date.toUTCString() + ";path=/"; } function spider_isunsupporteduseragent() { return (!window.XMLHttpRequest); } function spider_destroypopup(duration) { if (document.getElementById("spider_popup_wrap") != null) { jQuery(".spider_popup_wrap").remove(); jQuery(".spider_popup_loading").css({display: "none"}); jQuery(".spider_popup_overlay").css({display: "none"}); jQuery(document).off("keydown"); jQuery("html").attr("style", "overflow:auto !important"); } isPopUpOpened = false; var isMobile = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase())); var viewportmeta = document.querySelector('meta[name="viewport"]'); if (isMobile && viewportmeta) { viewportmeta.content = 'width=device-width, initial-scale=1'; } clearInterval(bwg_playInterval); } // Submit popup. function spider_ajax_save(form_id) { var post_data = {}; post_data["bwg_name"] = jQuery("#bwg_name").val(); post_data["bwg_comment"] = jQuery("#bwg_comment").val(); post_data["bwg_email"] = jQuery("#bwg_email").val(); post_data["bwg_captcha_input"] = jQuery("#bwg_captcha_input").val(); post_data["ajax_task"] = jQuery("#ajax_task").val(); post_data["image_id"] = jQuery("#image_id").val(); post_data["comment_id"] = jQuery("#comment_id").val(); // Loading. jQuery("#ajax_loading").css('height', jQuery(".bwg_comments").css('height')); jQuery("#opacity_div").css('width', jQuery(".bwg_comments").css('width')); jQuery("#opacity_div").css('height', jQuery(".bwg_comments").css('height')); jQuery("#loading_div").css('width', jQuery(".bwg_comments").css('width')); jQuery("#loading_div").css('height', jQuery(".bwg_comments").css('height')); document.getElementById("opacity_div").style.display = ''; document.getElementById("loading_div").style.display = 'table-cell'; jQuery.post( jQuery('#' + form_id).attr('action'), post_data, function (data) { var str = jQuery(data).find('.bwg_comments').html(); jQuery('.bwg_comments').html(str); } ).success(function(jqXHR, textStatus, errorThrown) { document.getElementById("opacity_div").style.display = 'none'; document.getElementById("loading_div").style.display = 'none'; // Update scrollbar. jQuery(".bwg_comments").mCustomScrollbar({scrollInertia: 150}); // Bind comment container close function to close button. jQuery(".bwg_comments_close_btn").click(bwg_comment); }); // if (event.preventDefault) { // event.preventDefault(); // } // else { // event.returnValue = false; // } return false; } // Submit rating. function spider_rate_ajax_save(form_id) { var post_data = {}; post_data["image_id"] = jQuery("#" + form_id + " input[name='image_id']").val(); post_data["rate"] = jQuery("#" + form_id + " input[name='score']").val(); post_data["ajax_task"] = jQuery("#rate_ajax_task").val(); jQuery.post( jQuery('#' + form_id).attr('action'), post_data, function (data) { var str = jQuery(data).find('#' + form_id).html(); jQuery('#' + form_id).html(str); } ).success(function(jqXHR, textStatus, errorThrown) { }); // if (event.preventDefault) { // event.preventDefault(); // } // else { // event.returnValue = false; // } return false; } // Set value by ID. function spider_set_input_value(input_id, input_value) { if (document.getElementById(input_id)) { document.getElementById(input_id).value = input_value; } } // Submit form by ID. function spider_form_submit(event, form_id) { if (document.getElementById(form_id)) { document.getElementById(form_id).submit(); } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } } // Check if required field is empty. function spider_check_required(id, name) { if (jQuery('#' + id).val() == '') { jQuery('#' + id).attr('style', 'border-color: #FF0000;'); jQuery('#' + id).focus(); return true; } else { return false; } } // Check Email. function spider_check_email(id) { if (jQuery('#' + id).val() != '') { var email = jQuery('#' + id).val().replace(/^\s+|\s+$/g, ''); if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) { alert(bwg_objectL10n.bwg_mail_validation); return true; } return false; } } // Refresh captcha. function bwg_captcha_refresh(id) { if (document.getElementById(id + "_img") && document.getElementById(id + "_input")) { srcArr = document.getElementById(id + "_img").src.split("&r="); document.getElementById(id + "_img").src = srcArr[0] + '&r=' + Math.floor(Math.random() * 100); document.getElementById(id + "_img").style.display = "inline-block"; document.getElementById(id + "_input").value = ""; } }
JavaScript
function spider_frontend_ajax(form_id, current_view, id, album_gallery_id, cur_album_id, type, srch_btn, title) { var page_number = jQuery("#page_number_" + current_view).val(); var bwg_previous_album_ids = jQuery('#bwg_previous_album_id_' + current_view).val(); var bwg_previous_album_page_numbers = jQuery('#bwg_previous_album_page_number_' + current_view).val(); var post_data = {}; if (album_gallery_id == 'back') { // Back from album. var bwg_previous_album_id = bwg_previous_album_ids.split(","); album_gallery_id = bwg_previous_album_id[0]; jQuery('#bwg_previous_album_id_' + current_view).val(bwg_previous_album_ids.replace(bwg_previous_album_id[0] + ',', '')); var bwg_previous_album_page_number = bwg_previous_album_page_numbers.split(","); page_number = bwg_previous_album_page_number[0]; jQuery('#bwg_previous_album_page_number_' + current_view).val(bwg_previous_album_page_numbers.replace(bwg_previous_album_page_number[0] + ',', '')); } else if (cur_album_id != '') { // Enter album (not change the page). jQuery('#bwg_previous_album_id_' + current_view).val(cur_album_id + ',' + bwg_previous_album_ids); if (page_number) { jQuery('#bwg_previous_album_page_number_' + current_view).val(page_number + ',' + bwg_previous_album_page_numbers); } page_number = 1; } if (srch_btn) { // Start search. page_number = 1; } if (typeof title == "undefined") { var title = ""; } post_data["page_number_" + current_view] = page_number; post_data["album_gallery_id_" + current_view] = album_gallery_id; post_data["bwg_previous_album_id_" + current_view] = jQuery('#bwg_previous_album_id_' + current_view).val(); post_data["bwg_previous_album_page_number_" + current_view] = jQuery('#bwg_previous_album_page_number_' + current_view).val(); post_data["type_" + current_view] = type; post_data["title_" + current_view] = title; if (jQuery("#bwg_search_input_" + current_view).length > 0) { // Search box exists. post_data["bwg_search_" + current_view] = jQuery("#bwg_search_input_" + current_view).val(); } // Loading. jQuery("#ajax_loading_" + current_view).css('display', ''); jQuery.post( window.location, post_data, function (data) { var str = jQuery(data).find('#' + form_id).html(); jQuery('#' + form_id).html(str); // There are no images. if (jQuery("#bwg_search_input_" + current_view).length > 0 && album_gallery_id == 0) { // Search box exists and not album view. var bwg_images_count = jQuery('#bwg_images_count_' + current_view).val(); if (bwg_images_count == 0) { var cont = jQuery("#" + id).parent().html(); var error_msg = '<div style="width:95%"><div class="error"><p><strong>' + bwg_objectL10n.bwg_search_result + '</strong></p></div></div>'; jQuery("#" + id).parent().html(error_msg + cont) } } } ).success(function(jqXHR, textStatus, errorThrown) { jQuery("#ajax_loading_" + current_view).css('display', 'none'); // window.scroll(0, spider_get_pos(document.getElementById(form_id))); jQuery("html, body").animate({scrollTop: jQuery('#' + form_id).offset().top - 150}, 500); // For masonry view. var cccount = 0; var obshicccount = jQuery(".bwg_masonry_thumb_spun_" + current_view + " a").length; jQuery(".bwg_masonry_thumb_spun_" + current_view + " a img").on("load", function() { if (++cccount == obshicccount) { window["bwg_masonry_" + current_view](); } }); }); // if (event.preventDefault) { // event.preventDefault(); // } // else { // event.returnValue = false; // } return false; }
JavaScript
/** * jscolor, JavaScript Color Picker * @version 1.3.9 * @license GNU Lesser General Public License, * http://www.gnu.org/copyleft/lesser.html * @author Jan Odvarko, http://odvarko.cz * @created 2008-06-15 * @updated 2011-07-28 * @link http://jscolor.com */ var jscolor = { // location of jscolor directory (leave empty to autodetect) dir : '', //class name bindClass : 'color', //automatic binding via <input class="..."> binding : true, //use image preloading? preloading : true, install : function() { jscolor.addEvent(window, 'load', jscolor.init); }, init : function() { if (jscolor.binding) { jscolor.bind(); } if (jscolor.preloading) { jscolor.preload(); } }, getDir : function() { if (!jscolor.dir) { var detected = jscolor.detectDir(); jscolor.dir = detected !== false ? detected : 'jscolor/'; } return jscolor.dir; }, detectDir : function() { var base = location.href; var e = document.getElementsByTagName('base'); for (var i = 0; i < e.length; i += 1) { if (e[i].href) { base = e[i].href; } } var e = document.getElementsByTagName('script'); for (var i = 0; i < e.length; i += 1) { if (e[i].src && /(^|\/)jscolor\.js([?#].*)?$/i.test(e[i].src)) { var src = new jscolor.URI(e[i].src); var srcAbs = src.toAbsolute(base); srcAbs.path = srcAbs.path.replace(/[^\/]+$/, ''); srcAbs.query = null; srcAbs.fragment = null; return srcAbs.toString(); } } return false; }, bind : function() { var matchClass = new RegExp('(^|\\s)(' + jscolor.bindClass + ')\\s*(\\{[^}]*\\})?', 'i'); var e = document.getElementsByTagName('input'); for (var i = 0; i < e.length; i += 1) { var m; if (!e[i].color && e[i].className && (m = e[i].className.match(matchClass))) { var prop = {}; if (m[3]) { try { eval('prop=' + m[3]); } catch (eInvalidProp) { } } e[i].color = new jscolor.color(e[i], prop); } } }, preload : function() { for (var fn in jscolor.imgRequire) { if (jscolor.imgRequire.hasOwnProperty(fn)) { jscolor.loadImage(fn); } } }, images : { pad : [ 181, 101 ], sld : [ 16, 101 ], cross : [ 15, 15 ], arrow : [ 7, 11 ] }, imgRequire : {}, imgLoaded : {}, requireImage : function(filename) { jscolor.imgRequire[filename] = true; }, loadImage : function(filename) { if (!jscolor.imgLoaded[filename]) { jscolor.imgLoaded[filename] = new Image(); jscolor.imgLoaded[filename].src = jscolor.getDir() + filename; } }, fetchElement : function(mixed) { return typeof mixed === 'string' ? document.getElementById(mixed) : mixed; }, addEvent : function(el, evnt, func) { if (el.addEventListener) { el.addEventListener(evnt, func, false); } else if (el.attachEvent) { el.attachEvent('on' + evnt, func); } }, fireEvent : function(el, evnt) { if (!el) { return; } if (document.createEvent) { var ev = document.createEvent('HTMLEvents'); ev.initEvent(evnt, true, true); el.dispatchEvent(ev); } else if (document.createEventObject) { var ev = document.createEventObject(); el.fireEvent('on' + evnt, ev); } else if (el['on' + evnt]) { // model (IE5) el['on' + evnt](); } }, getElementPos : function(e) { var e1 = e, e2 = e; var x = 0, y = 0; if (e1.offsetParent) { do { x += e1.offsetLeft; y += e1.offsetTop; } while (e1 = e1.offsetParent); } while ((e2 = e2.parentNode) && e2.nodeName.toUpperCase() !== 'BODY') { x -= e2.scrollLeft; y -= e2.scrollTop; } return [ x, y ]; }, getElementSize : function(e) { return [ e.offsetWidth, e.offsetHeight ]; }, getRelMousePos : function(e) { var x = 0, y = 0; if (!e) { e = window.event; } if (typeof e.offsetX === 'number') { x = e.offsetX; y = e.offsetY; } else if (typeof e.layerX === 'number') { x = e.layerX; y = e.layerY; } return { x : x, y : y }; }, getViewPos : function() { if (typeof window.pageYOffset === 'number') { return [ window.pageXOffset, window.pageYOffset ]; } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { return [ document.body.scrollLeft, document.body.scrollTop ]; } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { return [ document.documentElement.scrollLeft, document.documentElement.scrollTop ]; } else { return [ 0, 0 ]; } }, getViewSize : function() { if (typeof window.innerWidth === 'number') { return [ window.innerWidth, window.innerHeight ]; } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { return [ document.body.clientWidth, document.body.clientHeight ]; } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { return [ document.documentElement.clientWidth, document.documentElement.clientHeight ]; } else { return [ 0, 0 ]; } }, URI : function(uri) { this.scheme = null; this.authority = null; this.path = ''; this.query = null; this.fragment = null; this.parse = function(uri) { var m = uri .match(/^(([A-Za-z][0-9A-Za-z+.-]*)(:))?((\/\/)([^\/?#]*))?([^?#]*)((\?)([^#]*))?((#)(.*))?/); this.scheme = m[3] ? m[2] : null; this.authority = m[5] ? m[6] : null; this.path = m[7]; this.query = m[9] ? m[10] : null; this.fragment = m[12] ? m[13] : null; return this; }; this.toString = function() { var result = ''; if (this.scheme !== null) { result = result + this.scheme + ':'; } if (this.authority !== null) { result = result + '//' + this.authority; } if (this.path !== null) { result = result + this.path; } if (this.query !== null) { result = result + '?' + this.query; } if (this.fragment !== null) { result = result + '#' + this.fragment; } return result; }; this.toAbsolute = function(base) { var base = new jscolor.URI(base); var r = this; var t = new jscolor.URI; if (base.scheme === null) { return false; } if (r.scheme !== null && r.scheme.toLowerCase() === base.scheme.toLowerCase()) { r.scheme = null; } if (r.scheme !== null) { t.scheme = r.scheme; t.authority = r.authority; t.path = removeDotSegments(r.path); t.query = r.query; } else { if (r.authority !== null) { t.authority = r.authority; t.path = removeDotSegments(r.path); t.query = r.query; } else { if (r.path === '') { t.path = base.path; if (r.query !== null) { t.query = r.query; } else { t.query = base.query; } } else { if (r.path.substr(0, 1) === '/') { t.path = removeDotSegments(r.path); } else { if (base.authority !== null && base.path === '') { // === ? t.path = '/' + r.path; } else { t.path = base.path.replace(/[^\/]+$/, '') + r.path; } t.path = removeDotSegments(t.path); } t.query = r.query; } t.authority = base.authority; } t.scheme = base.scheme; } t.fragment = r.fragment; return t; }; function removeDotSegments(path) { var out = ''; while (path) { if (path.substr(0, 3) === '../' || path.substr(0, 2) === './') { path = path.replace(/^\.+/, '').substr(1); } else if (path.substr(0, 3) === '/./' || path === '/.') { path = '/' + path.substr(3); } else if (path.substr(0, 4) === '/../' || path === '/..') { path = '/' + path.substr(4); out = out.replace(/\/?[^\/]*$/, ''); } else if (path === '.' || path === '..') { path = ''; } else { var rm = path.match(/^\/?[^\/]*/)[0]; path = path.substr(rm.length); out = out + rm; } } return out; } if (uri) { this.parse(uri); } }, /* * Usage example: var myColor = new jscolor.color(myInputElement) */ color : function(target, prop) { this.required = true; this.adjust = true; this.hash = false; this.caps = true; this.slider = true; this.valueElement = target; this.styleElement = target; this.hsv = [ 0, 0, 1 ]; this.rgb = [ 1, 1, 1 ]; this.pickerOnfocus = true; this.pickerMode = 'HSV'; this.pickerPosition = 'bottom'; this.pickerButtonHeight = 20; this.pickerClosable = false; this.pickerCloseText = 'Close'; this.pickerButtonColor = 'ButtonText'; this.pickerFace = 10; this.pickerFaceColor = 'ThreeDFace'; this.pickerBorder = 1; this.pickerBorderColor = 'ThreeDHighlight ThreeDShadow ThreeDShadow ThreeDHighlight'; // color this.pickerInset = 1; this.pickerInsetColor = 'ThreeDShadow ThreeDHighlight ThreeDHighlight ThreeDShadow'; // color this.pickerZIndex = 10000; for (var p in prop) { if (prop.hasOwnProperty(p)) { this[p] = prop[p]; } } this.hidePicker = function() { if (isPickerOwner()) { removePicker(); } }; this.showPicker = function() { if (!isPickerOwner()) { var tp = jscolor.getElementPos(target); var ts = jscolor.getElementSize(target); var vp = jscolor.getViewPos(); var vs = jscolor.getViewSize(); var ps = getPickerDims(this); var a, b, c; switch (this.pickerPosition.toLowerCase()) { case 'left': a = 1; b = 0; c = -1; break; case 'right': a = 1; b = 0; c = 1; break; case 'top': a = 0; b = 1; c = -1; break; default: a = 0; b = 1; c = 1; break; } var l = (ts[b] + ps[b]) / 2; var pp = [ -vp[a] + tp[a] + ps[a] > vs[a] ? (-vp[a] + tp[a] + ts[a] / 2 > vs[a] / 2 && tp[a] + ts[a] - ps[a] >= 0 ? tp[a] + ts[a] - ps[a] : tp[a]) : tp[a], -vp[b] + tp[b] + ts[b] + ps[b] - l + l * c > vs[b] ? (-vp[b] + tp[b] + ts[b] / 2 > vs[b] / 2 && tp[b] + ts[b] - l - l * c >= 0 ? tp[b] + ts[b] - l - l * c : tp[b] + ts[b] - l + l * c) : (tp[b] + ts[b] - l + l * c >= 0 ? tp[b] + ts[b] - l + l * c : tp[b] + ts[b] - l - l * c) ]; drawPicker(pp[a], pp[b]); } }; this.importColor = function() { if (!valueElement) { this.exportColor(); } else { if (!this.adjust) { if (!this.fromString(valueElement.value, leaveValue)) { styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor; styleElement.style.color = styleElement.jscStyle.color; this.exportColor(leaveValue | leaveStyle); } } else if (!this.required && /^\s*$/.test(valueElement.value)) { valueElement.value = ''; styleElement.style.backgroundColor = styleElement.jscStyle.backgroundColor; styleElement.style.color = styleElement.jscStyle.color; this.exportColor(leaveValue | leaveStyle); } else if (this.fromString(valueElement.value)) { // OK } else { this.exportColor(); } } }; this.exportColor = function(flags) { if (!(flags & leaveValue) && valueElement) { var value = this.toString(); if (this.caps) { value = value.toUpperCase(); } if (this.hash) { value = '#' + value; } valueElement.value = value; } if (!(flags & leaveStyle) && styleElement) { styleElement.style.backgroundColor = '#' + this.toString(); styleElement.style.color = 0.213 * this.rgb[0] + 0.715 * this.rgb[1] + 0.072 * this.rgb[2] < 0.5 ? '#FFF' : '#000'; } if (!(flags & leavePad) && isPickerOwner()) { redrawPad(); } if (!(flags & leaveSld) && isPickerOwner()) { redrawSld(); } }; this.fromHSV = function(h, s, v, flags) { h < 0 && (h = 0) || h > 6 && (h = 6); s < 0 && (s = 0) || s > 1 && (s = 1); v < 0 && (v = 0) || v > 1 && (v = 1); this.rgb = HSV_RGB(h === null ? this.hsv[0] : (this.hsv[0] = h), s === null ? this.hsv[1] : (this.hsv[1] = s), v === null ? this.hsv[2] : (this.hsv[2] = v)); this.exportColor(flags); }; this.fromRGB = function(r, g, b, flags) { r < 0 && (r = 0) || r > 1 && (r = 1); g < 0 && (g = 0) || g > 1 && (g = 1); b < 0 && (b = 0) || b > 1 && (b = 1); var hsv = RGB_HSV(r === null ? this.rgb[0] : (this.rgb[0] = r), g === null ? this.rgb[1] : (this.rgb[1] = g), b === null ? this.rgb[2] : (this.rgb[2] = b)); if (hsv[0] !== null) { this.hsv[0] = hsv[0]; } if (hsv[2] !== 0) { this.hsv[1] = hsv[1]; } this.hsv[2] = hsv[2]; this.exportColor(flags); }; this.fromString = function(hex, flags) { var m = hex.match(/^\W*([0-9A-F]{3}([0-9A-F]{3})?)\W*$/i); if (!m) { return false; } else { if (m[1].length === 6) { this.fromRGB(parseInt(m[1].substr(0, 2), 16) / 255, parseInt(m[1] .substr(2, 2), 16) / 255, parseInt(m[1].substr(4, 2), 16) / 255, flags); } else { this.fromRGB(parseInt(m[1].charAt(0) + m[1].charAt(0), 16) / 255, parseInt(m[1].charAt(1) + m[1].charAt(1), 16) / 255, parseInt( m[1].charAt(2) + m[1].charAt(2), 16) / 255, flags); } return true; } }; this.toString = function() { return ((0x100 | Math.round(255 * this.rgb[0])).toString(16).substr(1) + (0x100 | Math.round(255 * this.rgb[1])).toString(16).substr(1) + (0x100 | Math .round(255 * this.rgb[2])).toString(16).substr(1)); }; function RGB_HSV(r, g, b) { var n = Math.min(Math.min(r, g), b); var v = Math.max(Math.max(r, g), b); var m = v - n; if (m === 0) { return [ null, 0, v ]; } var h = r === n ? 3 + (b - g) / m : (g === n ? 5 + (r - b) / m : 1 + (g - r) / m); return [ h === 6 ? 0 : h, m / v, v ]; } function HSV_RGB(h, s, v) { if (h === null) { return [ v, v, v ]; } var i = Math.floor(h); var f = i % 2 ? h - i : 1 - (h - i); var m = v * (1 - s); var n = v * (1 - s * f); switch (i) { case 6: case 0: return [ v, n, m ]; case 1: return [ n, v, m ]; case 2: return [ m, v, n ]; case 3: return [ m, n, v ]; case 4: return [ n, m, v ]; case 5: return [ v, m, n ]; } } function removePicker() { delete jscolor.picker.owner; document.getElementsByTagName('body')[0].removeChild(jscolor.picker.boxB); } function drawPicker(x, y) { if (!jscolor.picker) { jscolor.picker = { box : document.createElement('div'), boxB : document.createElement('div'), pad : document.createElement('div'), padB : document.createElement('div'), padM : document.createElement('div'), sld : document.createElement('div'), sldB : document.createElement('div'), sldM : document.createElement('div'), btn : document.createElement('div'), btnS : document.createElement('span'), btnT : document.createTextNode(THIS.pickerCloseText) }; for (var i = 0, segSize = 4; i < jscolor.images.sld[1]; i += segSize) { var seg = document.createElement('div'); seg.style.height = segSize + 'px'; seg.style.fontSize = '1px'; seg.style.lineHeight = '0'; jscolor.picker.sld.appendChild(seg); } jscolor.picker.sldB.appendChild(jscolor.picker.sld); jscolor.picker.box.appendChild(jscolor.picker.sldB); jscolor.picker.box.appendChild(jscolor.picker.sldM); jscolor.picker.padB.appendChild(jscolor.picker.pad); jscolor.picker.box.appendChild(jscolor.picker.padB); jscolor.picker.box.appendChild(jscolor.picker.padM); jscolor.picker.btnS.appendChild(jscolor.picker.btnT); jscolor.picker.btn.appendChild(jscolor.picker.btnS); jscolor.picker.box.appendChild(jscolor.picker.btn); jscolor.picker.boxB.appendChild(jscolor.picker.box); } var p = jscolor.picker; // controls interaction p.box.onmouseup = p.box.onmouseout = function() { target.focus(); }; p.box.onmousedown = function() { abortBlur = true; }; p.box.onmousemove = function(e) { if (holdPad || holdSld) { holdPad && setPad(e); holdSld && setSld(e); if (document.selection) { document.selection.empty(); } else if (window.getSelection) { window.getSelection().removeAllRanges(); } } }; p.padM.onmouseup = p.padM.onmouseout = function() { if (holdPad) { holdPad = false; jscolor.fireEvent(valueElement, 'change'); } }; p.padM.onmousedown = function(e) { holdPad = true; setPad(e); }; p.sldM.onmouseup = p.sldM.onmouseout = function() { if (holdSld) { holdSld = false; jscolor.fireEvent(valueElement, 'change'); } }; p.sldM.onmousedown = function(e) { holdSld = true; setSld(e); }; // picker var dims = getPickerDims(THIS); p.box.style.width = dims[0] + 'px'; p.box.style.height = dims[1] + 'px'; // picker border p.boxB.style.position = 'absolute'; p.boxB.style.clear = 'both'; p.boxB.style.left = x + 'px'; p.boxB.style.top = y + 'px'; p.boxB.style.zIndex = THIS.pickerZIndex; p.boxB.style.border = THIS.pickerBorder + 'px solid'; p.boxB.style.borderColor = THIS.pickerBorderColor; p.boxB.style.background = THIS.pickerFaceColor; // pad image p.pad.style.width = jscolor.images.pad[0] + 'px'; p.pad.style.height = jscolor.images.pad[1] + 'px'; // pad border p.padB.style.position = 'absolute'; p.padB.style.left = THIS.pickerFace + 'px'; p.padB.style.top = THIS.pickerFace + 'px'; p.padB.style.border = THIS.pickerInset + 'px solid'; p.padB.style.borderColor = THIS.pickerInsetColor; // pad mouse area p.padM.style.position = 'absolute'; p.padM.style.left = '0'; p.padM.style.top = '0'; p.padM.style.width = THIS.pickerFace + 2 * THIS.pickerInset + jscolor.images.pad[0] + jscolor.images.arrow[0] + 'px'; p.padM.style.height = p.box.style.height; p.padM.style.cursor = 'crosshair'; // slider image p.sld.style.overflow = 'hidden'; p.sld.style.width = jscolor.images.sld[0] + 'px'; p.sld.style.height = jscolor.images.sld[1] + 'px'; // slider border p.sldB.style.display = THIS.slider ? 'block' : 'none'; p.sldB.style.position = 'absolute'; p.sldB.style.right = THIS.pickerFace + 'px'; p.sldB.style.top = THIS.pickerFace + 'px'; p.sldB.style.border = THIS.pickerInset + 'px solid'; p.sldB.style.borderColor = THIS.pickerInsetColor; // slider mouse area p.sldM.style.display = THIS.slider ? 'block' : 'none'; p.sldM.style.position = 'absolute'; p.sldM.style.right = '0'; p.sldM.style.top = '0'; p.sldM.style.width = jscolor.images.sld[0] + jscolor.images.arrow[0] + THIS.pickerFace + 2 * THIS.pickerInset + 'px'; p.sldM.style.height = p.box.style.height; try { p.sldM.style.cursor = 'pointer'; } catch (eOldIE) { p.sldM.style.cursor = 'hand'; } // "close" button function setBtnBorder() { var insetColors = THIS.pickerInsetColor.split(/\s+/); var pickerOutsetColor = insetColors.length < 2 ? insetColors[0] : insetColors[1] + ' ' + insetColors[0] + ' ' + insetColors[0] + ' ' + insetColors[1]; p.btn.style.borderColor = pickerOutsetColor; } p.btn.style.display = THIS.pickerClosable ? 'block' : 'none'; p.btn.style.position = 'absolute'; p.btn.style.left = THIS.pickerFace + 'px'; p.btn.style.bottom = THIS.pickerFace + 'px'; p.btn.style.padding = '0 15px'; p.btn.style.height = '18px'; p.btn.style.border = THIS.pickerInset + 'px solid'; setBtnBorder(); p.btn.style.color = THIS.pickerButtonColor; p.btn.style.font = '12px sans-serif'; p.btn.style.textAlign = 'center'; try { p.btn.style.cursor = 'pointer'; } catch (eOldIE) { p.btn.style.cursor = 'hand'; } p.btn.onmousedown = function() { THIS.hidePicker(); }; p.btnS.style.lineHeight = p.btn.style.height; // load images in optimal order switch (modeID) { case 0: var padImg = 'hs.png'; break; case 1: var padImg = 'hv.png'; break; } p.padM.style.backgroundImage = "url('" + jscolor.getDir() + "cross.gif')"; p.padM.style.backgroundRepeat = "no-repeat"; p.sldM.style.backgroundImage = "url('" + jscolor.getDir() + "arrow.gif')"; p.sldM.style.backgroundRepeat = "no-repeat"; p.pad.style.backgroundImage = "url('" + jscolor.getDir() + padImg + "')"; p.pad.style.backgroundRepeat = "no-repeat"; p.pad.style.backgroundPosition = "0 0"; // place pointers redrawPad(); redrawSld(); jscolor.picker.owner = THIS; document.getElementsByTagName('body')[0].appendChild(p.boxB); } function getPickerDims(o) { var dims = [ 2 * o.pickerInset + 2 * o.pickerFace + jscolor.images.pad[0] + (o.slider ? 2 * o.pickerInset + 2 * jscolor.images.arrow[0] + jscolor.images.sld[0] : 0), o.pickerClosable ? 4 * o.pickerInset + 3 * o.pickerFace + jscolor.images.pad[1] + o.pickerButtonHeight : 2 * o.pickerInset + 2 * o.pickerFace + jscolor.images.pad[1] ]; return dims; } function redrawPad() { // redraw the pad pointer switch (modeID) { case 0: var yComponent = 1; break; case 1: var yComponent = 2; break; } var x = Math.round((THIS.hsv[0] / 6) * (jscolor.images.pad[0] - 1)); var y = Math.round((1 - THIS.hsv[yComponent]) * (jscolor.images.pad[1] - 1)); jscolor.picker.padM.style.backgroundPosition = (THIS.pickerFace + THIS.pickerInset + x - Math.floor(jscolor.images.cross[0] / 2)) + 'px ' + (THIS.pickerFace + THIS.pickerInset + y - Math .floor(jscolor.images.cross[1] / 2)) + 'px'; // redraw the slider image var seg = jscolor.picker.sld.childNodes; switch (modeID) { case 0: var rgb = HSV_RGB(THIS.hsv[0], THIS.hsv[1], 1); for (var i = 0; i < seg.length; i += 1) { seg[i].style.backgroundColor = 'rgb(' + (rgb[0] * (1 - i / seg.length) * 100) + '%,' + (rgb[1] * (1 - i / seg.length) * 100) + '%,' + (rgb[2] * (1 - i / seg.length) * 100) + '%)'; } break; case 1: var rgb, s, c = [ THIS.hsv[2], 0, 0 ]; var i = Math.floor(THIS.hsv[0]); var f = i % 2 ? THIS.hsv[0] - i : 1 - (THIS.hsv[0] - i); switch (i) { case 6: case 0: rgb = [ 0, 1, 2 ]; break; case 1: rgb = [ 1, 0, 2 ]; break; case 2: rgb = [ 2, 0, 1 ]; break; case 3: rgb = [ 2, 1, 0 ]; break; case 4: rgb = [ 1, 2, 0 ]; break; case 5: rgb = [ 0, 2, 1 ]; break; } for (var i = 0; i < seg.length; i += 1) { s = 1 - 1 / (seg.length - 1) * i; c[1] = c[0] * (1 - s * f); c[2] = c[0] * (1 - s); seg[i].style.backgroundColor = 'rgb(' + (c[rgb[0]] * 100) + '%,' + (c[rgb[1]] * 100) + '%,' + (c[rgb[2]] * 100) + '%)'; } break; } } function redrawSld() { // redraw the slider pointer switch (modeID) { case 0: var yComponent = 2; break; case 1: var yComponent = 1; break; } var y = Math.round((1 - THIS.hsv[yComponent]) * (jscolor.images.sld[1] - 1)); jscolor.picker.sldM.style.backgroundPosition = '0 ' + (THIS.pickerFace + THIS.pickerInset + y - Math .floor(jscolor.images.arrow[1] / 2)) + 'px'; } function isPickerOwner() { return jscolor.picker && jscolor.picker.owner === THIS; } function blurTarget() { if (valueElement === target) { THIS.importColor(); } if (THIS.pickerOnfocus) { THIS.hidePicker(); } } function blurValue() { if (valueElement !== target) { THIS.importColor(); } } function setPad(e) { var mpos = jscolor.getRelMousePos(e); var x = mpos.x - THIS.pickerFace - THIS.pickerInset; var y = mpos.y - THIS.pickerFace - THIS.pickerInset; switch (modeID) { case 0: THIS.fromHSV(x * (6 / (jscolor.images.pad[0] - 1)), 1 - y / (jscolor.images.pad[1] - 1), null, leaveSld); break; case 1: THIS.fromHSV(x * (6 / (jscolor.images.pad[0] - 1)), null, 1 - y / (jscolor.images.pad[1] - 1), leaveSld); break; } } function setSld(e) { var mpos = jscolor.getRelMousePos(e); var y = mpos.y - THIS.pickerFace - THIS.pickerInset; switch (modeID) { case 0: THIS.fromHSV(null, null, 1 - y / (jscolor.images.sld[1] - 1), leavePad); break; case 1: THIS.fromHSV(null, 1 - y / (jscolor.images.sld[1] - 1), null, leavePad); break; } } var THIS = this; var modeID = this.pickerMode.toLowerCase() === 'hvs' ? 1 : 0; var abortBlur = false; var valueElement = jscolor.fetchElement(this.valueElement), styleElement = jscolor .fetchElement(this.styleElement); var holdPad = false, holdSld = false; //var leaveValue = 1 << 0, leaveStyle = 1 << 1, leavePad = 1 << 2, leaveSld = 1 << 3; var leaveValue = 1, leaveStyle = 2, leavePad = 4, leaveSld = 8; // target jscolor.addEvent(target, 'focus', function() { if (THIS.pickerOnfocus) { THIS.showPicker(); } }); jscolor.addEvent(target, 'blur', function() { if (!abortBlur) { window.setTimeout(function() { abortBlur || blurTarget(); abortBlur = false; }, 0); } else { abortBlur = false; } }); // valueElement if (valueElement) { var updateField = function() { THIS.fromString(valueElement.value, leaveValue); }; jscolor.addEvent(valueElement, 'keyup', updateField); jscolor.addEvent(valueElement, 'input', updateField); jscolor.addEvent(valueElement, 'blur', blurValue); valueElement.setAttribute('autocomplete', 'off'); } // styleElement if (styleElement) { styleElement.jscStyle = { backgroundColor : styleElement.style.backgroundColor, color : styleElement.style.color }; } // require images switch (modeID) { case 0: jscolor.requireImage('hs.png'); break; case 1: jscolor.requireImage('hv.png'); break; } jscolor.requireImage('cross.gif'); jscolor.requireImage('arrow.gif'); this.importColor(); } }; jscolor.install();
JavaScript
/* * DisplayObject3D ---------------------------------------------- */ var DisplayObject3D = function(){ return this; }; DisplayObject3D.prototype._x = 0; DisplayObject3D.prototype._y = 0; //Create 3d Points DisplayObject3D.prototype.make3DPoint = function(x,y,z) { var point = {}; point.x = x; point.y = y; point.z = z; return point; }; //Create 2d Points DisplayObject3D.prototype.make2DPoint = function(x, y, depth, scaleFactor){ var point = {}; point.x = x; point.y = y; point.depth = depth; point.scaleFactor = scaleFactor; return point; }; DisplayObject3D.prototype.container = undefined; DisplayObject3D.prototype.pointsArray = []; DisplayObject3D.prototype.init = function (container){ this.container = container; this.containerId = this.container.attr("id"); //if there isn't a ul than it creates a list of +'s if (container.has("ul").length === 0){ for (i=0; i < this.pointsArray.length; i++){ this.container.append('<b id="tags_cloud_item'+i+'">+</b>'); } } }; /* * DisplayObject3D End ---------------------------------------------- */ /* * Camera3D ---------------------------------------------- */ var Camera3D = function (){}; Camera3D.prototype.x = 0; Camera3D.prototype.y = 0; Camera3D.prototype.z = 500; Camera3D.prototype.focalLength = 1000; Camera3D.prototype.scaleRatio = function(item){ return this.focalLength / (this.focalLength + item.z - this.z); }; Camera3D.prototype.init = function (x, y, z, focalLength){ this.x = x; this.y = y; this.z = z; this.focalLength = focalLength; }; /* * Camera3D End ---------------------------------------------- */ /* * Object3D ---------------------------------------------- */ var Object3D = function (container){ this.container = container; }; Object3D.prototype.objects = []; Object3D.prototype.addChild = function (object3D){ this.objects.push(object3D); object3D.init(this.container); return object3D; }; /* * Object3D End ---------------------------------------------- */ /* * Scene3D ---------------------------------------------- */ var Scene3D = function (){}; Scene3D.prototype.sceneItems = []; Scene3D.prototype.addToScene = function (object){ this.sceneItems.push(object); }; Scene3D.prototype.Transform3DPointsTo2DPoints = function(points, axisRotations, camera){ var TransformedPointsArray = []; var sx = Math.sin(axisRotations.x); var cx = Math.cos(axisRotations.x); var sy = Math.sin(axisRotations.y); var cy = Math.cos(axisRotations.y); var sz = Math.sin(axisRotations.z); var cz = Math.cos(axisRotations.z); var x,y,z, xy,xz, yx,yz, zx,zy, scaleFactor; var i = points.length; while (i--){ x = points[i].x; y = points[i].y; z = points[i].z; // rotation around x xy = cx * y - sx * z; xz = sx * y + cx * z; // rotation around y yz = cy * xz - sy * x; yx = sy * xz + cy * x; // rotation around z zx = cz * yx - sz * xy; zy = sz * yx + cz * xy; scaleFactor = camera.focalLength / (camera.focalLength + yz); x = zx * scaleFactor; y = zy * scaleFactor; z = yz; var displayObject = new DisplayObject3D(); TransformedPointsArray[i] = displayObject.make2DPoint(x, y, -z, scaleFactor); } return TransformedPointsArray; }; Scene3D.prototype.renderCamera = function (camera){ for(var i = 0 ; i < this.sceneItems.length; i++){ var obj = this.sceneItems[i].objects[0]; var screenPoints = this.Transform3DPointsTo2DPoints(obj.pointsArray, axisRotation, camera); var hasList = (document.getElementById(obj.containerId).getElementsByTagName("ul").length > 0); for (k=0; k < obj.pointsArray.length; k++){ var currItem = null; if (hasList){ currItem = document.getElementById(obj.containerId).getElementsByTagName("ul")[0].getElementsByTagName("li")[k]; }else{ currItem = document.getElementById(obj.containerId).getElementsByTagName("*")[k]; } if(currItem){ currItem._x = screenPoints[k].x; currItem._y = screenPoints[k].y; currItem.scale = screenPoints[k].scaleFactor; currItem.style.position = "absolute"; currItem.style.top = (currItem._y + jQuery("#" + obj.containerId).height() * 0.4)+'px'; currItem.style.left = (currItem._x + jQuery("#" + obj.containerId).width() * 0.4)+'px'; currItem.style.fontSize = 100 * currItem.scale + '%'; jQuery(currItem).css({opacity:(currItem.scale-.5)}); curChild = jQuery(currItem).find("#imgg"); if (curChild) { jQuery(currItem).css("zIndex", Math.round(currItem.scale * 100)); curChild.css({maxWidth:(currItem.scale*50)}); curChild.css({maxHeight:(currItem.scale*50)}); } } } } }; /* * Scene3D End ---------------------------------------------- */ //Center for rotation var axisRotation = new DisplayObject3D().make3DPoint(0,0,0);
JavaScript
var Sphere = function (radius, sides, numOfItems){ for (var j = sides ; j > 0; j--){ for (var i = numOfItems / sides ; i > 0; i--) { var angle = i * Math.PI / (numOfItems / sides + 1); var angleB = j * Math.PI * 2 / (sides); var x = Math.sin(angleB) * Math.sin(angle) * radius; var y = Math.cos(angleB) * Math.sin(angle) * radius; var z = Math.cos(angle) * radius; this.pointsArray.push(this.make3DPoint(x,y,z)); } }; }; Sphere.prototype = new DisplayObject3D();
JavaScript
/* * jQuery.fullscreen library v0.4.0 * Copyright (c) 2013 Vladimir Zhuravlev * * @license https://github.com/private-face/jquery.fullscreen/blob/master/LICENSE * * Date: Wed Dec 11 22:45:17 ICT 2013 **/ ;(function($) { function defined(a) { return typeof a !== 'undefined'; } function extend(child, parent, prototype) { var F = function() {}; F.prototype = parent.prototype; child.prototype = new F(); child.prototype.constructor = child; parent.prototype.constructor = parent; child._super = parent.prototype; if (prototype) { $.extend(child.prototype, prototype); } } var SUBST = [ ['', ''], // spec ['exit', 'cancel'], // firefox & old webkits expect cancelFullScreen instead of exitFullscreen ['screen', 'Screen'] // firefox expects FullScreen instead of Fullscreen ]; var VENDOR_PREFIXES = ['', 'o', 'ms', 'moz', 'webkit', 'webkitCurrent']; function native(obj, name) { var prefixed; if (typeof obj === 'string') { name = obj; obj = document; } for (var i = 0; i < SUBST.length; ++i) { name = name.replace(SUBST[i][0], SUBST[i][1]); for (var j = 0; j < VENDOR_PREFIXES.length; ++j) { prefixed = VENDOR_PREFIXES[j]; prefixed += j === 0 ? name : name.charAt(0).toUpperCase() + name.substr(1); if (defined(obj[prefixed])) { return obj[prefixed]; } } } return void 0; }var ua = navigator.userAgent; var fsEnabled = native('fullscreenEnabled'); var IS_ANDROID_CHROME = ua.indexOf('Android') !== -1 && ua.indexOf('Chrome') !== -1; var IS_NATIVELY_SUPPORTED = !IS_ANDROID_CHROME && defined(native('fullscreenElement')) && (!defined(fsEnabled) || fsEnabled === true); var version = $.fn.jquery.split('.'); var JQ_LT_17 = (parseInt(version[0]) < 2 && parseInt(version[1]) < 7); var FullScreenAbstract = function() { this.__options = null; this._fullScreenElement = null; this.__savedStyles = {}; }; FullScreenAbstract.prototype = { _DEFAULT_OPTIONS: { styles: { 'boxSizing': 'border-box', 'MozBoxSizing': 'border-box', 'WebkitBoxSizing': 'border-box' }, toggleClass: null }, __documentOverflow: '', __htmlOverflow: '', _preventDocumentScroll: function() { this.__documentOverflow = $('body')[0].style.overflow; this.__htmlOverflow = $('html')[0].style.overflow; // $('body, html').css('overflow', 'hidden'); }, _allowDocumentScroll: function() { // $('body')[0].style.overflow = this.__documentOverflow; // $('html')[0].style.overflow = this.__htmlOverflow; }, _fullScreenChange: function() { if (!this.isFullScreen()) { this._allowDocumentScroll(); this._revertStyles(); this._triggerEvents(); this._fullScreenElement = null; } else { this._preventDocumentScroll(); this._triggerEvents(); } }, _fullScreenError: function(e) { this._revertStyles(); this._fullScreenElement = null; if (e) { $(document).trigger('fscreenerror', [e]); } }, _triggerEvents: function() { $(this._fullScreenElement).trigger(this.isFullScreen() ? 'fscreenopen' : 'fscreenclose'); $(document).trigger('fscreenchange', [this.isFullScreen(), this._fullScreenElement]); }, _saveAndApplyStyles: function() { var $elem = $(this._fullScreenElement); this.__savedStyles = {}; for (var property in this.__options.styles) { // save this.__savedStyles[property] = this._fullScreenElement.style[property]; // apply this._fullScreenElement.style[property] = this.__options.styles[property]; } if (this.__options.toggleClass) { $elem.addClass(this.__options.toggleClass); } }, _revertStyles: function() { var $elem = $(this._fullScreenElement); for (var property in this.__options.styles) { this._fullScreenElement.style[property] = this.__savedStyles[property]; } if (this.__options.toggleClass) { $elem.removeClass(this.__options.toggleClass); } }, open: function(elem, options) { // do nothing if request is for already fullscreened element if (elem === this._fullScreenElement) { return; } // exit active fullscreen before opening another one if (this.isFullScreen()) { this.exit(); } // save fullscreened element this._fullScreenElement = elem; // apply options, if any this.__options = $.extend(true, {}, this._DEFAULT_OPTIONS, options); // save current element styles and apply new this._saveAndApplyStyles(); }, exit: null, isFullScreen: null, isNativelySupported: function() { return IS_NATIVELY_SUPPORTED; } }; var FullScreenNative = function() { FullScreenNative._super.constructor.apply(this, arguments); this.exit = $.proxy(native('exitFullscreen'), document); this._DEFAULT_OPTIONS = $.extend(true, {}, this._DEFAULT_OPTIONS, { 'styles': { 'width': '100%', 'height': '100%' } }); $(document) .bind(this._prefixedString('fullscreenchange') + ' MSFullscreenChange', $.proxy(this._fullScreenChange, this)) .bind(this._prefixedString('fullscreenerror') + ' MSFullscreenError', $.proxy(this._fullScreenError, this)); }; extend(FullScreenNative, FullScreenAbstract, { VENDOR_PREFIXES: ['', 'o', 'moz', 'webkit'], _prefixedString: function(str) { return $.map(this.VENDOR_PREFIXES, function(s) { return s + str; }).join(' '); }, open: function(elem, options) { FullScreenNative._super.open.apply(this, arguments); var requestFS = native(elem, 'requestFullscreen'); requestFS.call(elem); }, exit: $.noop, isFullScreen: function() { return native('fullscreenElement') !== null; }, element: function() { return native('fullscreenElement'); } }); var FullScreenFallback = function() { FullScreenFallback._super.constructor.apply(this, arguments); this._DEFAULT_OPTIONS = $.extend({}, this._DEFAULT_OPTIONS, { 'styles': { 'position': 'fixed', 'zIndex': '2147483647', 'left': 0, 'top': 0, 'bottom': 0, 'right': 0 } }); this.__delegateKeydownHandler(); }; extend(FullScreenFallback, FullScreenAbstract, { __isFullScreen: false, __delegateKeydownHandler: function() { var $doc = $(document); $doc.delegate('*', 'keydown.fullscreen', $.proxy(this.__keydownHandler, this)); var data = JQ_LT_17 ? $doc.data('events') : $._data(document).events; var events = data['keydown']; if (!JQ_LT_17) { events.splice(0, 0, events.splice(events.delegateCount - 1, 1)[0]); } else { data.live.unshift(data.live.pop()); } }, __keydownHandler: function(e) { if (this.isFullScreen() && e.which === 27) { this.exit(); return false; } return true; }, _revertStyles: function() { FullScreenFallback._super._revertStyles.apply(this, arguments); // force redraw (fixes bug in IE7 with content dissapearing) this._fullScreenElement.offsetHeight; }, open: function(elem) { FullScreenFallback._super.open.apply(this, arguments); this.__isFullScreen = true; this._fullScreenChange(); }, exit: function() { this.__isFullScreen = false; this._fullScreenChange(); }, isFullScreen: function() { return this.__isFullScreen; }, element: function() { return this.__isFullScreen ? this._fullScreenElement : null; } });$.fullscreen = IS_NATIVELY_SUPPORTED ? new FullScreenNative() : new FullScreenFallback(); $.fn.fullscreen = function(options) { var elem = this[0]; options = $.extend({ toggleClass: null, // overflow: 'hidden' }, options); options.styles = { // overflow: options.overflow }; // delete options.overflow; if (elem) { $.fullscreen.open(elem, options); } return this; }; })(jQuery);
JavaScript
/* * jQuery.upload v1.0.2 * * Copyright (c) 2010 lagos * Dual licensed under the MIT and GPL licenses. * * http://lagoscript.org */ (function($) { var uuid = 0; $.fn.upload = function(url, data, callback, type) { var self = this, inputs, checkbox, checked, iframeName = 'jquery_upload' + ++uuid, iframe = $('<iframe name="' + iframeName + '" style="position:absolute;top:-9999px" />').appendTo('body'), form = '<form target="' + iframeName + '" method="post" enctype="multipart/form-data" />'; if ($.isFunction(data)) { type = callback; callback = data; data = {}; } checkbox = $('input:checkbox', this); checked = $('input:checked', this); form = self.wrapAll(form).parent('form').attr('action', url); // Make sure radios and checkboxes keep original values // (IE resets checkd attributes when appending) checkbox.removeAttr('checked'); checked.attr('checked', true); inputs = createInputs(data); inputs = inputs ? $(inputs).appendTo(form) : null; form.submit(function() { iframe.load(function() { var data = handleData(this, type), checked = $('input:checked', self); form.after(self).remove(); checkbox.removeAttr('checked'); checked.attr('checked', true); if (inputs) { inputs.remove(); } setTimeout(function() { iframe.remove(); if (type === 'script') { $.globalEval(data); } if (callback) { callback.call(self, data); } }, 0); }); }).submit(); return this; }; function createInputs(data) { return $.map(param(data), function(param) { return '<input type="hidden" name="' + param.name + '" value="' + param.value + '"/>'; }).join(''); } function param(data) { if ($.isArray(data)) { return data; } var params = []; function add(name, value) { params.push({name:name, value:value}); } if (typeof data === 'object') { $.each(data, function(name) { if ($.isArray(this)) { $.each(this, function() { add(name, this); }); } else { add(name, $.isFunction(this) ? this() : this); } }); } else if (typeof data === 'string') { $.each(data.split('&'), function() { var param = $.map(this.split('='), function(v) { return decodeURIComponent(v.replace(/\+/g, ' ')); }); add(param[0], param[1]); }); } return params; } function handleData(iframe, type) { var data, contents = $(iframe).contents().get(0); if ($.isXMLDoc(contents) || contents.XMLDocument) { return contents.XMLDocument || contents; } data = $(contents).find('body').html(); switch (type) { case 'xml': data = parseXml(data); break; case 'json': data = window.eval('(' + data + ')'); break; } return data; } function parseXml(text) { if (window.DOMParser) { return new DOMParser().parseFromString(text, 'application/xml'); } else { var xml = new ActiveXObject('Microsoft.XMLDOM'); xml.async = false; xml.loadXML(text); return xml; } } })(jQuery);
JavaScript
/* * jQuery Iframe Transport Plugin 1.6.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts three additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] $.ajaxTransport('iframe', function (options) { if (options.async) { var form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('<form style="display:none;"></form>'); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: iframe = $( '<iframe src="javascript:false;" name="iframe-transport-' + (counter += 1) + '"></iframe>' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="javascript:false;"></iframe>') .appendTo(form); form.remove(); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, and script: $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); }));
JavaScript
/** * Author: Rob * Date: 4/18/13 * Time: 3:56 PM */ //////////////////////////////////////////////////////////////////////////////////////// // Events // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Constants // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Variables // //////////////////////////////////////////////////////////////////////////////////////// var keyFileSelected; var keyFileSelectedML; var filesSelected; var filesSelectedML; var dragFiles; var isUploading; //////////////////////////////////////////////////////////////////////////////////////// // Constructor // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Public Methods // //////////////////////////////////////////////////////////////////////////////////////// jQuery(document).ready(function () { filesSelected = []; filesSelectedML = []; dragFiles = []; //file manager under system messages jQuery("#wrapper").css("top", jQuery("#file_manager_message").css("height")); jQuery(window).resize(function () { jQuery("#container").css("top", jQuery("#file_manager_message").css("height")); }); isUploading = false; jQuery("#uploader").css("display", "none"); jQuery("#uploader_progress_bar").css("display", "none"); jQuery("#importer").css("display", "none"); //decrease explorer header width by scroller width jQuery(".scrollbar_filler").css("width", getScrollBarWidth() + "px"); jQuery(document).keydown(function(e) { onKeyDown(e); }); }); //////////////////////////////////////////////////////////////////////////////////////// // Getters & Setters // //////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////// // Private Methods // //////////////////////////////////////////////////////////////////////////////////////// function getClipboardFiles() { return jQuery("form[name=adminForm]").find("input[name=clipboard_file]").val(); } function submit(task, sortBy, sortOrder, itemsView, destDir, fileNewName, newDirName, clipboardTask, clipboardFiles, clipboardSrc, clipboardDest) { fileNames = filesSelected.join("**#**"); fileNamesML = filesSelectedML.join("**@**"); switch (task) { case "rename_item": destDir = dir; newDirName = ""; clipboardTask = "" clipboardDest = ""; break; case "remove_items": destDir = dir; fileNewName = ""; newDirName = ""; clipboardTask = "" clipboardDest = ""; break; case "make_dir": destDir = dir; fileNewName = ""; clipboardTask = "" clipboardDest = ""; break; case "paste_items": destDir = dir; fileNewName = ""; newDirName = ""; break; case "import_items": destDir = dir; fileNewName = ""; newDirName = ""; break; default: task = ""; break; } jQuery("form[name=adminForm]").find("input[name=task]").val(task); if (sortBy != null) { jQuery("form[name=adminForm]").find("input[name=sort_by]").val(sortBy); } if (sortOrder != null) { jQuery("form[name=adminForm]").find("input[name=sort_order]").val(sortOrder); } if (itemsView != null) { jQuery("form[name=adminForm]").find("input[name=items_view]").val(itemsView); } if (destDir != null) { jQuery("form[name=adminForm]").find("input[name=dir]").val(destDir); } if (fileNames != null) { jQuery("form[name=adminForm]").find("input[name=file_names]").val(fileNames); } if (fileNamesML != null) { jQuery("form[name=adminForm]").find("input[name=file_namesML]").val(fileNamesML); } if (fileNewName != null) { jQuery("form[name=adminForm]").find("input[name=file_new_name]").val(fileNewName); } if (newDirName != null) { jQuery("form[name=adminForm]").find("input[name=new_dir_name]").val(newDirName); } if (clipboardTask != null) { jQuery("form[name=adminForm]").find("input[name=clipboard_task]").val(clipboardTask); } if (clipboardFiles != null) { jQuery("form[name=adminForm]").find("input[name=clipboard_files]").val(clipboardFiles); } if (clipboardSrc != null) { jQuery("form[name=adminForm]").find("input[name=clipboard_src]").val(clipboardSrc); } if (clipboardDest != null) { jQuery("form[name=adminForm]").find("input[name=clipboard_dest]").val(clipboardDest); } jQuery("form[name=adminForm]").submit(); } function updateFileNames() { var result = ""; if (filesSelected.length > 0) { var fileNames = []; for (var i = 0; i < filesSelected.length; i++) { fileNames[i] = "'" + filesSelected[i] + "'"; } result = fileNames.join(" "); } jQuery("#file_names_span span").html(result); } // submit file function submitFiles() { if (filesSelected.length == 0) { return; } var filesValid = []; for (var i = 0; i < filesSelected.length; i++) { var file_object = jQuery(".explorer_item[name='" + filesSelected[i] + "']"); if (jQuery(file_object).attr("isDir") == "false") { var fileData = []; fileData['name'] = filesSelected[i]; fileData['filename'] = jQuery(file_object).attr("filename"); fileData['url'] = dir + "/" + filesSelected[i]; fileData['reliative_url'] = dirUrl + "/" + filesSelected[i]; fileData['thumb_url'] = dir + "/thumb/" + filesSelected[i]; fileData['thumb'] = jQuery(file_object).attr("filethumb"); fileData['size'] = jQuery(file_object).attr("filesize"); fileData['filetype'] = jQuery(file_object).attr("filetype"); fileData['date_modified'] = jQuery(file_object).attr("date_modified"); fileData['resolution'] = jQuery(file_object).attr("fileresolution"); filesValid.push(fileData); } } window.parent[callback](filesValid); window.parent.tb_remove(); } function importFiles() { if (filesSelectedML.length == 0) { alert("Select at least one file to import."); return; } else { submit("import_items", null, null, null, null, null, null, null, null, null, dir); } } function getScrollBarWidth() { var inner = document.createElement("p"); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement("div"); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = "scroll"; var w2 = inner.offsetWidth; if (w1 == w2) { w2 = outer.clientWidth; } document.body.removeChild(outer); return (w1 - w2); } function getFileName(file) { var dotIndex = file.lastIndexOf('.'); return file.substring(0, dotIndex < 0 ? file.length : dotIndex); } function getFileExtension(file) { return file.substring(file.lastIndexOf('.') + 1); } //////////////////////////////////////////////////////////////////////////////////////// // Listeners // //////////////////////////////////////////////////////////////////////////////////////// //ctrls bar handlers function onBtnUpClick(event, obj) { var destDir = dir.substring(0, dir.lastIndexOf(DS)); submit("", null, null, null, destDir, null, null, null, null, null, null); } function onBtnMakeDirClick(event, obj) { var newDirName = prompt(messageEnterDirName); if ((newDirName) && (newDirName != "")) { submit("make_dir", null, null, null, null, null, newDirName, null, null, null, null); } } function onBtnRenameItemClick(event, obj) { if (filesSelected.length != 0) { var newName = prompt(messageEnterNewName, getFileName(filesSelected[0])); if ((newName != null) && (newName != "")) { submit("rename_item", null, null, null, null, newName, null, null, null, null, null); } } } function onBtnCopyClick(event, obj) { if (filesSelected.length != 0) { submit("", null, null, null, null, null, null, "copy", filesSelected.join("**#**"), dir, null); } } function onBtnCutClick(event, obj) { if (filesSelected.length != 0) { submit("", null, null, null, null, null, null, "cut", filesSelected.join("**#**"), dir, null); } } function onBtnPasteClick(event, obj) { if (getClipboardFiles() != "") { submit("paste_items", null, null, null, null, null, null, null, null, null, dir); } } function onBtnRemoveItemsClick(event, obj) { if ((filesSelected.length != 0) && (confirm(warningRemoveItems) == true)) { submit("remove_items", null, null, null, null, null, null, null, null, null, null); } } function onBtnShowUploaderClick(event, obj) { jQuery("#uploader").fadeIn(); } function onBtnViewThumbsClick(event, obj) { submit("", null, null, "thumbs", null, null, null, null, null, null, null); } function onBtnViewListClick(event, obj) { submit("", null, null, "list", null, null, null, null, null, null, null); } function onBtnBackClick(event, obj) { if ((isUploading == false) || (confirm(warningCancelUploads) == true)) { // jQuery("#uploader").fadeOut(function () { submit("", null, null, null, null, null, null, null, null, null, null); // }); } } function onPathComponentClick(event, obj, path) { submit("", null, null, null, path, null, null, null, null, null, null); } function onBtnShowImportClick(event, obj) { jQuery("#importer").fadeIn(); } function onNameHeaderClick(event, obj) { var newSortOrder = ((sortBy == "name") && (sortOrder == "asc")) ? "desc" : "asc"; submit("", "name", newSortOrder, null, null, null, null, null, null, null, null); } function onSizeHeaderClick(event, obj) { var newSortOrder = ((sortBy == "size") && (sortOrder == "asc")) ? "desc" : "asc"; submit("", "size", newSortOrder, null, null, null, null, null, null, null, null); } function onDateModifiedHeaderClick(event, obj) { var newSortOrder = ((sortBy == "date_modified") && (sortOrder == "asc")) ? "desc" : "asc"; submit("", "date_modified", newSortOrder, null, null, null, null, null, null, null, null); } //file handlers function onKeyDown(e) { var e = e || window.event; var chCode1 = e.which || e.paramlist_keyCode; if ((e.ctrlKey || e.metaKey) && chCode1 == 65) { jQuery(".explorer_item").addClass("explorer_item_select"); jQuery(".importer_item").addClass("importer_item_select"); filesSelected = []; filesSelectedML = []; jQuery(".explorer_item").each(function() { var objName = jQuery(this).attr("name"); if (filesSelected.indexOf(objName) == -1) { filesSelected.push(objName); keyFileSelected = this; } }); jQuery(".importer_item").each(function() { var objName = jQuery(this).attr("path"); if (filesSelectedML.indexOf(objName) == -1) { filesSelectedML.push(objName); keyFileSelectedML = this; } }); e.preventDefault(); } } function onFileMOver(event, obj) { jQuery(obj).addClass("explorer_item_hover"); } function onFileMOverML(event, obj) { jQuery(obj).addClass("importer_item_hover"); } function onFileMOut(event, obj) { jQuery(obj).removeClass("explorer_item_hover"); } function onFileMOutML(event, obj) { jQuery(obj).removeClass("importer_item_hover"); } function onFileClick(event, obj) { jQuery(".explorer_item").removeClass("explorer_item_select"); var objName = jQuery(obj).attr("name"); if (event.ctrlKey == true || event.metaKey == true) { if (filesSelected.indexOf(objName) == -1) { filesSelected.push(objName); keyFileSelected = obj; } else { filesSelected.splice(filesSelected.indexOf(objName), 1); jQuery(obj).removeClass("explorer_item_select"); } } else if (event.shiftKey == true) { filesSelected = []; var explorerItems = jQuery(".explorer_item"); var curFileIndex = explorerItems.index(jQuery(obj)); var keyFileIndex = explorerItems.index(keyFileSelected); var startIndex = Math.min(keyFileIndex, curFileIndex); var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex); for (var i = startIndex; i < endIndex + 1; i++) { filesSelected.push(jQuery(explorerItems[i]).attr("name")); } } else { filesSelected = [jQuery(obj).attr("name")]; keyFileSelected = obj; } for (var i = 0; i < filesSelected.length; i++) { jQuery(".explorer_item[name='" + filesSelected[i] + "']").addClass("explorer_item_select"); } updateFileNames(); } function onFileClickML(event, obj) { jQuery(".importer_item").removeClass("importer_item_select"); var objName = jQuery(obj).attr("path"); if (event.ctrlKey == true || event.metaKey == true) { if (filesSelectedML.indexOf(objName) == -1) { filesSelectedML.push(objName); keyFileSelectedML = obj; } else { filesSelectedML.splice(filesSelectedML.indexOf(objName), 1); jQuery(obj).removeClass("importer_item_select"); } } else if (event.shiftKey == true) { filesSelectedML = []; var explorerItems = jQuery(".importer_item"); var curFileIndex = explorerItems.index(jQuery(obj)); var keyFileIndex = explorerItems.index(keyFileSelectedML); var startIndex = Math.min(keyFileIndex, curFileIndex); var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex); for (var i = startIndex; i < endIndex + 1; i++) { filesSelectedML.push(jQuery(explorerItems[i]).attr("path")); } } else { filesSelectedML = [jQuery(obj).attr("path")]; keyFileSelectedML = obj; } for (var i = 0; i < filesSelectedML.length; i++) { jQuery(".importer_item[path='" + filesSelectedML[i] + "']").addClass("importer_item_select"); } updateFileNames(); } function onFileDblClick(event, obj) { if (jQuery(obj).attr("isDir") == "true") { submit("", null, null, null, dir + DS + jQuery(obj).attr("name"), null, null, null, null, null, null); } else { filesSelected = []; filesSelected.push(jQuery(obj).attr("name")); submitFiles(); } } function onFileDblClickML(event, obj) { filesSelectedML = []; filesSelectedML.push(jQuery(obj).attr("path")); importFiles(); } function onFileDragStart(event, obj) { var objName = jQuery(obj).attr("name"); if (filesSelected.indexOf(objName) < 0) { jQuery(".explorer_item").removeClass("explorer_item_select"); if (event.ctrlKey == true || event.metaKey == true) { if (filesSelected.indexOf(objName) == -1) { filesSelected.push(objName); keyFileSelected = obj; } } else if (event.shiftKey == true) { filesSelected = []; var explorerItems = jQuery(".explorer_item"); var curFileIndex = explorerItems.index(jQuery(obj)); var keyFileIndex = explorerItems.index(keyFileSelected); var startIndex = Math.min(keyFileIndex, curFileIndex); var endIndex = startIndex + Math.abs(curFileIndex - keyFileIndex); for (var i = startIndex; i < endIndex + 1; i++) { filesSelected.push(jQuery(explorerItems[i]).attr("name")); } } else { filesSelected = [jQuery(obj).attr("name")]; keyFileSelected = obj; } for (var i = 0; i < filesSelected.length; i++) { jQuery(".explorer_item[name='" + filesSelected[i] + "']").addClass("explorer_item_select"); } updateFileNames(); } dragFiles = filesSelected; } function onFileDragOver(event, obj) { event.preventDefault(); } function onFileDrop(event, obj) { var destDirName = jQuery(obj).attr("name"); if ((dragFiles.length == 0) || (dragFiles.indexOf(destDirName) >= 0)) { return false; } var clipboardTask = (event.ctrlKey == true || event.metaKey == true) ? "copy" : "cut"; var clipboardDest = dir + DS + destDirName; submit("paste_items", null, null, null, null, null, null, clipboardTask, dragFiles.join("**#**"), dir, clipboardDest); event.preventDefault(); } function onBtnOpenClick(event, obj) { if (jQuery(".explorer_item[name='" + filesSelected[0] + "']").attr("isDir") == true) { filesSelected.length = 1; submit("", null, null, null, dir + DS + filesSelected[0], null, null, null, null, null, null); } else { submitFiles(); } } function onBtnImportClick(event, obj) { importFiles(); } function onBtnCancelClick(event, obj) { window.parent.tb_remove(); } function onBtnSelectAllClick() { jQuery(".explorer_item").addClass("explorer_item_select"); filesSelected = []; jQuery(".explorer_item").each(function() { var objName = jQuery(this).attr("name"); if (filesSelected.indexOf(objName) == -1) { filesSelected.push(objName); keyFileSelected = this; } }); } function onBtnSelectAllMediLibraryClick() { jQuery(".importer_item").addClass("importer_item_select"); filesSelectedML = []; jQuery(".importer_item").each(function() { var objName = jQuery(this).attr("path"); if (filesSelectedML.indexOf(objName) == -1) { filesSelectedML.push(objName); keyFileSelectedML = this; } }); }
JavaScript
jQuery(document).ready(function() { jQuery(".follow-button").click(function() { var author_id=jQuery(this).attr('data-author-id'); jQuery.ajax({ type:'POST', url:ajax_object.ajaxurl, data: { action:'follow', author_id:author_id }, success:function(data) { jQuery('#follow_status_'+author_id).html(data); } }); }); });
JavaScript