1 /**
  2  * save and restore focus when overlay shows or hides
  3  * @author yiminghe@gmail.com
  4  */
  5 KISSY.add("editor/plugin/focusFix/index", function (S, Editor) {
  6     var UA = S.UA,
  7         focusManager = Editor.focusManager;
  8 
  9     function _show4FocusExt() {
 10         var self = this;
 11         // 保存当前焦点editor
 12 
 13         self._focusEditor = focusManager.currentInstance();
 14         var editor = self._focusEditor;
 15         /*
 16          * IE BUG: If the initial focus went into a non-text element (e.g. button,image),
 17          * then IE would still leave the caret inside the editing area.
 18          */
 19         // ie9 图片resize框,仍然会突出
 20         if (UA['ie'] && editor) {
 21             // 聚焦到当前窗口
 22             // 使得编辑器失去焦点,促使ie保存当前选择区域(位置)
 23             // chrome 需要下面两句
 24             window['focus']();
 25             document.body.focus();
 26 
 27             var $selection = editor.get("document")[0].selection,
 28                 $range = $selection.createRange();
 29             if ($range) {
 30                 if (
 31                 // 如果单纯选择文字就不用管了
 32                 // $range.parentElement &&
 33                 // $range.parentElement().ownerDocument == editor.document
 34                 // ||
 35                 // 缩放图片那个框在ie下会突出浮动层来
 36                     $range.item
 37                         && $range.item(0).ownerDocument == editor.get("document")[0]) {
 38                     var $myRange = document.body.createTextRange();
 39                     $myRange.moveToElementText(self.get("el").first()[0]);
 40                     $myRange.collapse(true);
 41                     $myRange.select();
 42                 }
 43             }
 44         }
 45     }
 46 
 47     function _hide4FocusExt() {
 48         var editor = this._focusEditor;
 49         editor && editor.focus();
 50     }
 51 
 52     return {
 53         init:function (self) {
 54             self.on("beforeVisibleChange", function (e) {
 55                 if (e.newVal) {
 56                     _show4FocusExt.call(self);
 57                 }
 58             });
 59             self.on("hide", function () {
 60                 _hide4FocusExt.call(self);
 61             });
 62         }
 63     };
 64 
 65 }, {
 66     requires:['editor']
 67 });