1 /**
  2  * Add justify command identifier for Editor.
  3  * @author yiminghe@gmail.com
  4  */
  5 KISSY.add("editor/plugin/justifyUtils/cmd", function (S, Editor) {
  6     var alignRemoveRegex = /(-moz-|-webkit-|start|auto)/gi,
  7         default_align = "left";
  8 
  9     function exec(editor, textAlign) {
 10         editor.focus();
 11         editor.execCommand("save");
 12         var selection = editor.getSelection(),
 13             bookmarks = selection.createBookmarks(),
 14             ranges = selection.getRanges(),
 15             iterator,
 16             block;
 17         for (var i = ranges.length - 1; i >= 0; i--) {
 18             iterator = ranges[ i ].createIterator();
 19             iterator.enlargeBr = true;
 20             while (( block = iterator.getNextParagraph() )) {
 21                 block.removeAttr('align');
 22                 if (isAlign(block, textAlign)) {
 23                     block.css('text-align', '');
 24                 } else {
 25                     block.css('text-align', textAlign);
 26                 }
 27             }
 28         }
 29         selection.selectBookmarks(bookmarks);
 30         editor.execCommand("save");
 31         editor.notifySelectionChange();
 32     }
 33 
 34     function isAlign(block, textAlign) {
 35         var align = block.css("text-align")
 36             .replace(alignRemoveRegex, "")
 37             //默认值,没有设置
 38             || default_align;
 39         return align == textAlign;
 40     }
 41 
 42     return {
 43         addCommand:function (editor, command, textAlign) {
 44             if (!editor.hasCommand(command)) {
 45 
 46                 editor.addCommand(command, {
 47                     exec:function (editor) {
 48                         exec(editor, textAlign);
 49                     }
 50                 });
 51 
 52                 editor.addCommand(Editor.Utils.getQueryCmd(command), {
 53                     exec:function (editor) {
 54                         var selection = editor.getSelection();
 55                         if (selection && !selection.isInvalid) {
 56                             var startElement = selection.getStartElement();
 57                             var path = new Editor.ElementPath(startElement);
 58                             var block = path.block || path.blockLimit;
 59                             if (!block || block.nodeName() === "body") {
 60                                 return false;
 61                             }
 62                             return isAlign(block, textAlign);
 63                         }
 64                     }
 65                 });
 66 
 67             }
 68         }
 69     };
 70 }, {
 71     requires:['editor']
 72 });