Debian Codegraph @

dojox/editor/plugins/BidiSupport.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare",
3 "dojo/_base/array",
4 "dojo/aspect",
5 "dojo/_base/lang",
6 "dojo/dom-attr",
7 "dojo/dom-class",
8 "dojo/dom-construct",
9 "dojo/i18n",
10 "dojo/NodeList-dom",
11 "dojo/NodeList-traverse",
12 "dojo/dom-style",
13 "dojo/sniff",
14 "dojo/query",
15 "dijit",
16 "dojox",
17 "dijit/_editor/_Plugin",
18 "dijit/_editor/range",
19 "dijit/_editor/plugins/EnterKeyHandling",
20 "dijit/_editor/plugins/FontChoice",
21 "./NormalizeIndentOutdent",
22 "dijit/form/ToggleButton",
23 "dojo/i18n!./nls/BidiSupport"
24 ], function(declare,array,aspect,lang,domAttr,domClass,domConstruct,i18n,listDom,listTraverse,domStyle,has,query,dijit,dojox,_Plugin,rangeapi,EnterKeyHandling,FontChoice,NormIndentOutdent,ToggleButton){
25
26 // module:
27 // rtebidi/BidiSupport
28
29 var BidiSupport = declare("dojox.editor.plugins.BidiSupport", _Plugin, {
30 // summary:
31 // This plugin provides some advanced BiDi support for
32 // rich text editing widget. It adds several bidi-specific commands,
33 // which are not released in native RTE's ('set text direction to left-to-right',
34 // 'set text direction to right-to-left', 'change text direction to opposite')
35 // and overrides some existing native commands.
36
37 // Override _Plugin.useDefaultCommand.
38 useDefaultCommand: false,
39
40 // Override _Plugin.buttonClass. Plugin uses two buttons, defined below.
41 buttonClass: null,
42
43 // iconClassPrefix: [const] String
44 // The CSS class name for the button node icon.
45 iconClassPrefix: "dijitAdditionalEditorIcon",
46
47 command: "bidiSupport",
48
49 // blockMode: [const] String
50 // This property decides the behavior of Enter key, actually released by EnterKeyHandling
51 // plugin. Possible values are 'P' and 'DIV'. Used when EnterKeyHandling isn't included
52 // into the list of the base plugins, loaded with the current Editor, as well as in case,
53 // if blockNodeForEnter property of EnterKeyHandling plugin isn't set to 'P' or 'DIV'.
54 // The default value is "DIV".
55 blockMode: "DIV",
56
57 // shortcutonly: [const] Boolean
58 // If this property is set to 'false', plugin handles all text direction commands
59 // and its behavior is controlled both by buttons and by shortcut (Ctrl+Shift+X).
60 // In opposite case only command 'change text direction to opposite', controlled by shortcut,
61 // is supported, and buttons don't appear in the toolbar.
62 // Defaults to false.
63 shortcutonly: false,
64
65 // bogusHtmlContent: [private] String
66 // HTML to stick into a new empty block
67 bogusHtmlContent: ' ',
68
69 // buttonLtr: [private] dijit/form/ToggleButton
70 // Used to set direction of the selected text to left-to-right.
71 buttonLtr: null,
72
73 // buttonRtl: [private] dijit/form/ToggleButton
74 // Used to set direction of the selected text to right-to-left.
75 buttonRtl: null,
76
77 _indentBy: 40,
78 _lineTextArray: ["DIV","P","LI","H1","H2","H3","H4","H5","H6","ADDRESS","PRE","DT","DE","TD"],
79 _lineStyledTextArray: ["H1","H2","H3","H4","H5","H6","ADDRESS","PRE","P"],
80 _tableContainers: ["TABLE","THEAD","TBODY","TR"],
81 _blockContainers: ["TABLE","OL","UL","BLOCKQUOTE"],
82
83 _initButton: function(){
84 // summary:
85 // Override _Plugin._initButton(). Creates two buttons, used for
86 // setting text direction to left-to-right and right-to-left.
87 if(this.shortcutonly){
88 return;
89 }
90 if(!this.buttonLtr){
91 this.buttonLtr = this._createButton("ltr");
92 }
93 if(!this.buttonRtl){
94 this.buttonRtl = this._createButton("rtl");
95 }
96 },
97
98 _createButton: function(direction){
99 // summary:
100 // Initialize specific button.
101 return ToggleButton(lang.mixin({
102 label: i18n.getLocalization("dojox.editor.plugins", "BidiSupport")[direction],
103 dir: this.editor.dir,
104 lang: this.editor.lang,
105 showLabel: false,
106 iconClass: this.iconClassPrefix+" "+this.iconClassPrefix + (direction == "ltr"? "ParaLeftToRight" : "ParaRightToLeft"),
107 onClick: lang.hitch(this, "_changeState", [direction])
108 }, this.params || {}));
109 },
110
111 setToolbar: function(/*dijit.Toolbar*/ toolbar){
112 // summary:
113 // Override _Plugin.setToolbar(). Adds buttons so, that 'ltr' button
114 // will appear from the left of 'rtl' button regardless of the editor's
115 // orientation.
116 if(this.shortcutonly){
117 return;
118 }
119 if(this.editor.isLeftToRight()){
120 toolbar.addChild(this.buttonLtr);
121 toolbar.addChild(this.buttonRtl);
122 }else{
123 toolbar.addChild(this.buttonRtl);
124 toolbar.addChild(this.buttonLtr);
125 }
126 },
127
128 updateState: function(){
129 // summary:
130 // Override _Plugin.updateState(). Determines direction of the text in the
131 // start point of the current selection. Changes state of the buttons
132 // correspondingly.
133 if(!this.editor || !this.editor.isLoaded || this.shortcutonly){
134 return;
135 }
136 this.buttonLtr.set("disabled", !!this.disabled);
137 this.buttonRtl.set("disabled", !!this.disabled);
138 if(this.disabled){
139 return;
140 }
141 var sel = rangeapi.getSelection(this.editor.window);
142 if(!sel || sel.rangeCount == 0){
143 return;
144 }
145 var range = sel.getRangeAt(0), node;
146 if(range.startContainer === this.editor.editNode && !range.startContainer.hasChildNodes()){
147 node = range.startContainer;
148 }else{
149 var startNode = range.startContainer,
150 startOffset = range.startOffset;
151 if(this._isBlockElement(startNode)){
152 while(startNode.hasChildNodes()){
153 if(startOffset == startNode.childNodes.length){
154 startOffset--;
155 }
156 startNode = startNode.childNodes[startOffset];
157 startOffset = 0;
158 }
159 }
160 node = this._getBlockAncestor(startNode);
161 }
162 var cDir = domStyle.get(node,"direction");
163 this.buttonLtr.set("checked", "ltr" == cDir);
164 this.buttonRtl.set("checked", "rtl" == cDir);
165 },
166
167 setEditor: function(/*dijit.Editor*/ editor){
168 // summary:
169 // Override _Plugin.setEditor().
170 // description:
171 // Sets editor's flag 'advancedBidi' to true, which may be used by other plugins
172 // as a switch to bidi-specific behaviour. Adds bidi-specific filters, including
173 // postDom filter, which provides explicit direction settings for the blocks
174 // of the text, direction of which isn't defined. Overrides some native commands,
175 // which should be changed or expanded in accordance with bidi-specific needs.
176 // Loads EnterKeyHandling plugin, if it was not loaded, and changes its
177 // blockNodeForEnter property, if it is needed. Defines shortcut, which will cause
178 // execution of 'change text direction to opposite' ('mirror') command.
179 this.editor = editor;
180 if(this.blockMode != "P" && this.blockMode != "DIV"){
181 this.blockMode = "DIV";
182 }
183 this._initButton();
184 var isLtr = this.editor.dir == "ltr";
185 // FF: RTL-oriented DIV's, containing new lines and/or tabs, can't be converted to lists (exception in native execCommand)
186 // Delete new lines and tabs from everywhere excluding contents of PRE elements.
187 this.editor.contentPreFilters.push(this._preFilterNewLines);
188 // Explicit direction setting
189 var postDomFilterSetDirExplicitly = lang.hitch(this, function(node){
190 if(this.disabled || !node.hasChildNodes()){
191 return node;
192 }
193 this._changeStateOfBlocks(this.editor.editNode, this.editor.editNode, this.editor.editNode, "explicitdir", null);
194 return this.editor.editNode;
195 });
196 this.editor.contentDomPostFilters.push(postDomFilterSetDirExplicitly);
197 // FF: Native change alignment command for more then one DIV doesn't change actually alignment, but damages
198 // markup so, that selected DIV's are converted into sequence of text elements, separated by <br>'s.
199 // Override native command
200 this.editor._justifyleftImpl = lang.hitch(this, function(){
201 this._changeState("left");
202 return true;
203 });
204 this.editor._justifyrightImpl = lang.hitch(this, function(){
205 this._changeState("right");
206 return true;
207 });
208 this.editor._justifycenterImpl = lang.hitch(this, function(){
209 this._changeState("center");
210 return true;
211 });
212 // FF: When blocks are converted into list items, their attributes are lost.
213 // IE: 1)Instead of converting regular block into list item, IE includes block into the newly created item,
214 // so attributes and styles don't appear in the item.
215 // 2)IE always converts list item into <P>.
216 // Expand native command
217 this.editor._insertorderedlistImpl = lang.hitch(this, "_insertLists", "insertorderedlist");
218 this.editor._insertunorderedlistImpl = lang.hitch(this, "_insertLists", "insertunorderedlist");
219
220 // IE: Direction of newly created blockquotes is set explicitly,
221 // which creates problems for further editing of the text.
222 // Expand native command
223 this.editor._indentImpl = lang.hitch(this, "_indentAndOutdent", "indent");
224
225 // FF: Outdent for the list items from the first level's list converts them into sequence of
226 // text elements, separated by <BR>s. Attributes of list items are lost.
227 // Expand native command
228 this.editor._outdentImpl = lang.hitch(this, "_indentAndOutdent", "outdent");
229
230 // FF: 1)Instead of converting <div> to some other block, FF includes newly created block into
231 // old <div>. Excessive nesting blocks creates problems for further working with the text.
232 // 2)Formatting contents of more then one list item (but less then all items in the list)
233 // caused unexpected merge of their contents.
234 // Expand native command
235 this.editor._formatblockImpl = lang.hitch(this, "_formatBlocks");
236
237 this.editor.onLoadDeferred.addCallback(lang.hitch(this, function(){
238 var edPlugins = this.editor._plugins,
239 i, p, ind = edPlugins.length, f = false,
240 h = lang.hitch(this, "_changeState", "mirror"),
241 hl = lang.hitch(this, "_changeState", "ltr"),
242 hr = lang.hitch(this, "_changeState", "rtl");
243
244 this.editor.addKeyHandler('9', 1, 0, h); //Ctrl-9
245 this.editor.addKeyHandler('8', 1, 0, hl); //Ctrl-8
246 this.editor.addKeyHandler('0', 1, 0, hr); //Ctrl-0
247 for(i = 0; i < edPlugins.length; i++){
248 p = edPlugins[i];
249 if (!p){
250 continue;
251 }
252 if(p.constructor === EnterKeyHandling){
253 p.destroy();
254 p = null;
255 ind = i;
256 }else if(p.constructor === NormIndentOutdent){
257 this.editor._normalizeIndentOutdent = true;
258 this.editor._indentImpl = lang.hitch(this, "_indentAndOutdent", "indent");
259 this.editor._outdentImpl = lang.hitch(this, "_indentAndOutdent", "outdent");
260 }else if(p.constructor === FontChoice && p.command === "formatBlock"){
261 this.own(aspect.before(p.button, "_execCommand", lang.hitch(this, "_handleNoFormat")));
262 }
263 }
264 this.editor.addPlugin({ctor: EnterKeyHandling, blockNodeForEnter: this.blockMode, blockNodes: /^(?:P|H1|H2|H3|H4|H5|H6|LI|DIV)$/}, ind);
265 p = this.editor._plugins[ind];
266 this.own(aspect.after(p, "handleEnterKey", lang.hitch(this, "_checkNewLine"), true));
267 }));
268 this.own(aspect.after(this.editor, "onNormalizedDisplayChanged", lang.hitch(this, "updateState"), true));
269 },
270
271 _checkNewLine: function(){
272 var range = rangeapi.getSelection(this.editor.window).getRangeAt(0);
273 var curBlock = rangeapi.getBlockAncestor(range.startContainer, null, this.editor.editNode).blockNode;
274 if (curBlock.innerHTML === this.bogusHtmlContent && curBlock.previousSibling){
275 curBlock.style.cssText = curBlock.previousSibling.style.cssText;
276 }else if(curBlock.innerHTML !== this.bogusHtmlContent && curBlock.previousSibling && curBlock.previousSibling.innerHTML === this.bogusHtmlContent){
277 curBlock.previousSibling.style.cssText = curBlock.style.cssText;
278 }
279 },
280
281 _handleNoFormat: function(editor, command, choice){
282 if (choice === "noFormat"){
283 return [editor, command, "DIV"];
284 }
285 return arguments;
286 },
287
288 _execNativeCmd: function(cmd, arg, info){
289 // summary:
290 // Call native command for nodes inside selection
291 // cmd:
292 // Name of the command (like "insertorderedlist" or "indent")
293 // arg:
294 // Arguments of the command
295 // info:
296 // Object containing
297 // nodes: array of all block nodes, which should be handled by this command
298 // groups: array containing groups of nodes. Nodes from each group should be handled by separate
299 // execution of current command
300 // cells: array of cells, contents of which should be handled by current command
301 // description:
302 // Sometimes native commands "insertorderedlist", "insertunorderedlist", "indent",
303 // "outdent" and "formatblocks" are the cause of various problems. These problems have
304 // different levels of severity - from crashing of their executing or damage of the editor's
305 // content to creating visually correct results, which however can cause the future problems,
306 // not always bidi-specific. For example, Webkit fails with insertlist commands, if selection
307 // contains some block element (like <H1> or <DIV>), followed by the table, and few cells of
308 // this table.IE fails,when try to handle insertlist command for list items, containing <PRE>.
309 // Mozilla and IE produce wrong results for selection,containing more then one cell. Mozilla
310 // merges contents of some listitems with "formatblock" command. Safari places DIV's in the
311 // same list with newly created list items. Webkit creates multilevel blocks to format the text.
312 // IE adds to the list lines of the text,which are outside the selection. Webkit put whole table
313 // into list item. All browsers lose direction and alignment styles with outdent command,
314 // executed for items from one-level list. Etc.
315 // We try to avoid these problems and produce correct (and more or less similar) results for
316 // all supported browsers. This is achieved by separating the each above-mentioned command into
317 // three parts.
318 // The first ("preparelist","prepareindent","prepareoutdent" and "prepareformat") is performed
319 // before corresponding native call. It prepares selected region of the editor's content by
320 // rebuilding it with strong block structure and keeps info about each group of selected
321 // elements. Separate groups are created for contents of each table cell, as well as for lines of
322 // text that are before, after and between tables. In case of webkit and insertlist or formatblocks
323 // commands, each selected block element is placed into separate "group".
324 // The second part of the command is native call itself. Native calls are executed separately
325 // for each group of nodes. This requires to reset a selection, each time limiting it to only
326 // the elements of the current group.
327 // The third part is perfomed after native call. Its role is to restore missing styles,
328 // to delete bogus elements, created in the previous steps, to merge sibling lists etc.
329 // Corresponding commands have the same names, as native (e.g., "insertorderedlist',
330 // "insertunorderedlist", "indent", "outdent" and "formatblocks"), because just they produce
331 // the final result. For IE and Mozilla we call one "post" command per native call. For webkit
332 // we call one "post" command per group of elements.
333
334 // If info contains only one group of elements, we, as usually, perform one native call per selection
335 if(this._isSimpleInfo(info)){
336 var result = this.editor.document.execCommand(cmd, false, arg);
337 // After some operations (like insert lists into cells of tables) webkit inserts BR before table
338 if(has("webkit")){
339 query("table",this.editor.editNode).prev().forEach(function(x,ind,arr){
340 if(this._hasTag(x,"BR")){
341 x.parentNode.removeChild(x);
342 }
343 },this);
344 }
345 return result;
346 }
347 var sel = rangeapi.getSelection(this.editor.window);
348 if(!sel || sel.rangeCount == 0){
349 return false;
350 }
351 var range = sel.getRangeAt(0), tempRange = range.cloneRange();
352 var startContainer = range.startContainer, startOffset = range.startOffset,
353 endContainer = range.endContainer, endOffset = range.endOffset;
354 for(var i = 0; i < info.groups.length; i++){
355 var group = info.groups[i];
356 // Set selection for currrent group of elements
357 var eOffs = group[group.length-1].childNodes.length;
358 tempRange.setStart(group[0],0);
359 tempRange.setEnd(group[group.length-1],eOffs);
360 sel.removeAllRanges();
361 sel.addRange(tempRange);
362 var table = this.editor.selection.getParentOfType(group[0],["TABLE"]);
363 // Execute native command for current group
364 var returnValue = this.editor.document.execCommand(cmd, false, arg);
365 if(has("webkit")){
366 if(table && this._hasTag(table.previousSibling, "BR")){
367 table.parentNode.removeChild(table.previousSibling);
368 }
369 this.editor.focus();
370 // Keep info about entire selection
371 sel = rangeapi.getSelection(this.editor.window);
372 var internalRange = sel.getRangeAt(0);
373 if(i == 0){
374 startContainer = internalRange.endContainer;
375 startOffset = internalRange.endOffset;
376 }else if(i == info.groups.length-1){
377 endContainer = internalRange.endContainer;
378 endOffset = internalRange.endOffset;
379 }
380 }
381 if(!returnValue){
382 break;
383 }
384 // For webkit we execute "post" command for each group of elements.
385 if(has("webkit")){
386 this._changeState(cmd);
387 }
388 }
389 // Restore selection
390 sel.removeAllRanges();
391 try{
392 tempRange.setStart(startContainer, startOffset);
393 tempRange.setEnd(endContainer, endOffset);
394 sel.addRange(tempRange);
395 }catch(e){
396 }
397 return true;
398 },
399
400 _insertLists: function(cmd){
401 // summary:
402 // Overrides native insertorderlist and insertunorderlist commands.
403 // cmd:
404 // Name of the command, one of "insertorderedlist" or "insertunorderedlist"
405 // description:
406 // Overrides native insertorderlist and insertunorderlist commands with the goal
407 // to avoid some bidi-specific problems that arise when these commands are executed.
408 // Performed in three steps:
409 // 1) prepares selected fragment of the document to execution of native command.
410 // 2) executes corresponding native command
411 // 3) updates contents of selected fragment of the document after execution of
412 // native comand.
413 var info = this._changeState("preparelists",cmd);
414 var returnValue = this._execNativeCmd(cmd, null, info);
415 if(!returnValue){
416 return false;
417 }
418 // For webkit "post" command executed separately for each group of elements.
419 if(!has("webkit") || this._isSimpleInfo(info)){
420 this._changeState(cmd);
421 }
422 this._cleanLists();
423 this._mergeLists();
424 return true;
425 },
426
427 _indentAndOutdent: function(cmd){
428 // summary:
429 // Overrides native indent and outdent commands.
430 // cmd:
431 // Name of the command, of of "indent" or "outdent"
432 // description:
433 // Overrides native indent and outdent commands with the goal to avoid some
434 // bidi-specific problems that arise when these commands are executed.
435 // Performed in three steps:
436 // 1) prepares selected fragment of the document to execution of native command
437 // (outdent only).
438 // 2) executes corresponding native command
439 // 3) updates contents of selected fragment of the document after execution of
440 // native comand.
441 if(this.editor._normalizeIndentOutdent){
442 // To emulate NormalizeIndentOutdent
443 this._changeState("normalize" + cmd);
444 return true;
445 }
446 var info = this._changeState("prepare" + cmd);
447
448 // If useCSS and styleWithCSS both set to false, mozilla creates blockquotes
449 if(has("mozilla")){
450 var oldValue;
451 try{
452 oldValue = this.editor.document.queryCommandValue("styleWithCSS");
453 }catch(e){
454 oldValue = false;
455 }
456 this.editor.document.execCommand("styleWithCSS", false, true);
457 }
458
459 var returnValue = this._execNativeCmd(cmd, null, info);
460 if(has("mozilla")){
461 this.editor.document.execCommand("styleWithCSS", false, oldValue);
462 }
463 if(!returnValue){
464 return false;
465 }
466 this._changeState(cmd);
467 this._mergeLists();
468 return true;
469 },
470
471 _formatBlocks: function(arg){
472 // summary:
473 // Overrides native formatblock command.
474 // arg:
475 // Tag name of block type, like H1, DIV or P.
476 // description:
477 // Overrides native formatblock command with the goal to avoid some
478 // bidi-specific problems that arise when this command is executed.
479 // Performed in three steps:
480 // 1) prepares selected fragment of the document to execution of native command
481 // (Mozilla only).
482 // 2) executes native command
483 // 3) updates contents of selected fragment of the document after execution of
484 // native comand.
485 var info;
486 if(has("mozilla") || has("webkit")){
487 info = this._changeState("prepareformat", arg);
488 }
489 if(has("ie") && arg && arg.charAt(0) != "<"){
490 arg = "<" + arg + ">";
491 }
492 var returnValue = this._execNativeCmd("formatblock", arg, info);
493 if(!returnValue){
494 return false;
495 }
496 if(!has("webkit") || this._isSimpleInfo(info)){
497 this._changeState("formatblock", arg);
498 }
499 this._mergeLists();
500 return true;
501 },
502
503 _changeState: function(cmd,arg){
504 // summary:
505 // Determines and refines current selection and calls method
506 // _changeStateOfBlocks(), where given action is actually done
507 // description:
508 // The main goal of this method is correctly identify the block elements,
509 // that are at the beginning and end of the current selection.
510 // return: nodesInfo
511 // Object containing
512 // nodes: array of all block nodes, which should be handled by this command
513 // groups: array containing groups of nodes. Nodes from each group should be handled by separate
514 // execution of current command
515 // cells: array of cells, contents of which should be handled by current command
516 if(!this.editor.window){
517 return;
518 }
519 this.editor.focus();
520 var sel = rangeapi.getSelection(this.editor.window);
521 if(!sel || sel.rangeCount == 0){
522 return;
523 }
524 var range = sel.getRangeAt(0), tempRange = range.cloneRange(),
525 startNode, endNode, startOffset, endOffset;
526 startNode = range.startContainer;
527 startOffset = range.startOffset;
528 endNode = range.endContainer;
529 endOffset = range.endOffset;
530 var isCollapsed = startNode === endNode && startOffset == endOffset;
531 if(this._isBlockElement(startNode) || this._hasTagFrom(startNode,this._tableContainers)){
532 while(startNode.hasChildNodes()){
533 if(startOffset == startNode.childNodes.length){
534 startOffset--;
535 }
536 startNode = startNode.childNodes[startOffset];
537 startOffset = 0;
538 }
539 }
540 tempRange.setStart(startNode, startOffset);
541 startNode = this._getClosestBlock(startNode,"start",tempRange);
542 var supList = rangeapi.getBlockAncestor(startNode, /li/i, this.editor.editNode).blockNode;
543 if(supList && supList !== startNode){
544 startNode = supList;
545 }
546 endNode = tempRange.endContainer;
547 endOffset = tempRange.endOffset;
548 if(this._isBlockElement(endNode) || this._hasTagFrom(endNode,this._tableContainers)){
549 while(endNode.hasChildNodes()){
550 if(endOffset == endNode.childNodes.length){
551 endOffset--;
552 }
553 endNode = endNode.childNodes[endOffset];
554 if(endNode.hasChildNodes()){
555 endOffset = endNode.childNodes.length;
556 }else if(endNode.nodeType == 3 && endNode.nodeValue){
557 endOffset = endNode.nodeValue.length;
558 }else{
559 endOffset = 0;
560 }
561 }
562 }
563 tempRange.setEnd(endNode, endOffset);
564 endNode = this._getClosestBlock(endNode,"end",tempRange);
565 supList = rangeapi.getBlockAncestor(endNode, /li/i, this.editor.editNode).blockNode;
566 if(supList && supList !== endNode){
567 endNode = supList;
568 }
569 sel = rangeapi.getSelection(this.editor.window, true);
570 sel.removeAllRanges();
571 sel.addRange(tempRange);
572 var commonAncestor = rangeapi.getCommonAncestor(startNode, endNode);
573 var nodesInfo = this._changeStateOfBlocks(startNode, endNode, commonAncestor, cmd, arg, tempRange);
574 if(isCollapsed){
575 endNode = tempRange.startContainer;
576 endOffset = tempRange.startOffset;
577 tempRange.setEnd(endNode, endOffset);
578 sel = rangeapi.getSelection(this.editor.window, true);
579 sel.removeAllRanges();
580 sel.addRange(tempRange);
581 }
582 return nodesInfo;
583 },
584
585 _isBlockElement: function(node){
586 if(!node || node.nodeType != 1){
587 return false;
588 }
589 var display = domStyle.get(node,"display");
590 return (display == 'block' || display == "list-item" || display == "table-cell");
591 },
592
593 _isInlineOrTextElement: function(node){
594 return !this._isBlockElement(node) && (node.nodeType == 1 || node.nodeType == 3 || node.nodeType == 8);
595 },
596
597 _isElement: function(node){
598 return node && (node.nodeType == 1 || node.nodeType == 3);
599 },
600
601 _isBlockWithText: function(node){
602 return node !== this.editor.editNode && this._hasTagFrom(node,this._lineTextArray);
603 },
604
605 _getBlockAncestor: function(node){
606 while(node.parentNode && !this._isBlockElement(node)){
607 node = node.parentNode;
608 }
609 return node;
610 },
611
612 _getClosestBlock: function(node, point, tempRange){
613 // summary:
614 // Searches for a closest block element containing the text which
615 // is at a given point of current selection. Refines current
616 // selection, if text element from start or end point was merged
617 // with its neighbors.
618 if(this._isBlockElement(node)){
619 return node;
620 }
621 var parent = node.parentNode,
622 firstSibling, lastSibling,
623 createOwnBlock = false,
624 multiText = false;
625 removeOffset = false;
626 while(true){
627 var sibling = node;
628 createOwnBlock = false;
629 while(true){
630 if(this._isInlineOrTextElement(sibling)){
631 firstSibling = sibling;
632 if(!lastSibling){
633 lastSibling = sibling;
634 }
635 }
636 sibling = sibling.previousSibling;
637 if(!sibling){
638 break;
639 }else if(this._isBlockElement(sibling) || this._hasTagFrom(sibling,this._blockContainers) || this._hasTag(sibling,"BR")){
640 createOwnBlock = true;
641 break;
642 }else if(sibling.nodeType == 3 && sibling.nextSibling.nodeType == 3){
643 // Merge neighboring text elements
644 sibling.nextSibling.nodeValue = sibling.nodeValue + sibling.nextSibling.nodeValue;
645 multiText = true;
646 if(point == "start" && sibling === tempRange.startContainer){
647 tempRange.setStart(sibling.nextSibling, 0);
648 }else if(point == "end" && (sibling === tempRange.endContainer || sibling.nextSibling === tempRange.endContainer)){
649 tempRange.setEnd(sibling.nextSibling, sibling.nextSibling.nodeValue.length);
650 }
651 sibling = sibling.nextSibling;
652 sibling.parentNode.removeChild(sibling.previousSibling);
653 if(!sibling.previousSibling){
654 break;
655 }
656 }
657 }
658 sibling = node;
659 while(true){
660 if(this._isInlineOrTextElement(sibling)){
661 if(!firstSibling){
662 firstSibling = sibling;
663 }
664 lastSibling = sibling;
665 }
666 sibling = sibling.nextSibling;
667 if(!sibling){
668 break;
669 }else if(this._isBlockElement(sibling) || this._hasTagFrom(sibling,this._blockContainers)){
670 createOwnBlock = true;
671 break;
672 }else if(this._hasTag(sibling,"BR") && sibling.nextSibling && !(this._isBlockElement(sibling.nextSibling) ||
673 this._hasTagFrom(sibling.nextSibling,this._blockContainers))){
674 lastSibling = sibling;
675 createOwnBlock = true;
676 break;
677 }else if(sibling.nodeType == 3 && sibling.previousSibling.nodeType == 3){
678 // Merge neighboring text elements
679 sibling.previousSibling.nodeValue += sibling.nodeValue;
680 multiText = true;
681 if(point == "start" && sibling === tempRange.startContainer){
682 tempRange.setStart(sibling.previousSibling, 0);
683 }else if(point == "end" && (sibling === tempRange.endContainer || sibling.previousSibling === tempRange.endContainer)){
684 tempRange.setEnd(sibling.previousSibling, sibling.previousSibling.nodeValue.length);
685 }
686 sibling = sibling.previousSibling;
687 sibling.parentNode.removeChild(sibling.nextSibling);
688 if(!sibling.nextSibling){
689 break;
690 }
691 }
692 }
693 // If text in the start or end point of the current selection doesn't placed in some block element
694 // or if it has block siblings, new block, containing this text element (and its inline siblings) is created.
695 if(createOwnBlock || (this._isBlockElement(parent) &&
696 !this._isBlockWithText(parent) && firstSibling)){
697 var origStartOffset = tempRange? tempRange.startOffset : 0,
698 origEndOffset = tempRange? tempRange.endOffset : 0,
699 origStartContainer = tempRange? tempRange.startContainer : null,
700 origEndContainer = tempRange? tempRange.endContainer : null,
701 divs = this._repackInlineElements(firstSibling, lastSibling, parent),
702 div = divs[point == "start"? 0 : divs.length-1];
703 if(tempRange && div && firstSibling === origStartContainer && this._hasTag(firstSibling,"BR")){
704 origStartContainer = div;
705 origStartOffset = 0;
706 if(lastSibling === firstSibling){
707 origEndContainer = origStartContainer;
708 origEndOffset = 0;
709 }
710 }
711 if(tempRange){
712 tempRange.setStart(origStartContainer, origStartOffset);
713 tempRange.setEnd(origEndContainer, origEndOffset);
714 }
715 return div;
716 }
717 if(this._isBlockElement(parent)){
718 return parent;
719 }
720 node = parent;
721 removeOffset = true;
722 parent = parent.parentNode;
723 firstSibling = lastSibling = null;
724 }
725 },
726
727 _changeStateOfBlocks: function(startNode, endNode, commonAncestor, cmd, arg, tempRange){
728 // summary:
729 // Collects all block elements, containing text, which are inside of current selection,
730 // and performs for each of them given action.
731 // Possible commands and corresponding actions:
732 // - "ltr": change direction to left-to-right
733 // - "rtl": change direction to right-to-left
734 // - "mirror": change direction to opposite
735 // - "explicitdir": explicit direction setting
736 // - "left": change alignment to left
737 // - "right": change alignment to right
738 // - "center": change alignment to center
739 // - "preparelists": action should be done before executing native insert[un]orderedlist
740 // - "prepareoutdent": action should be done before executing native outdent
741 // - "prepareindent": action should be done before executing native indent
742 // - "prepareformat": action should be done before executing native formatblock
743 // - "insertunorderedlist": action should be done after executing native insertunorderedlist
744 // - "insertorderedlist": action should be done after executing native insertorderedlist
745 // - "indent": action should be done after executing native indent
746 // - "outdent": action should be done after executing native outdent
747 // - "normalizeindent": emulate indent done by NormalizeIndentOutdent plugin
748 // - "normalizeoutdent": emulate outdent done by NormalizeIndentOutdent plugin
749 // - "formatblock": action should be done after executing native formatblock
750 var nodes = [];
751 // Refine selection, needed for 'explicitdir' command (full selection)
752 if(startNode === this.editor.editNode){
753 if(!startNode.hasChildNodes()){
754 return;
755 }
756 if(this._isInlineOrTextElement(startNode.firstChild)){
757 this._rebuildBlock(startNode);
758 }
759 startNode = this._getClosestBlock(startNode.firstChild, "start", null);
760 }
761 if(endNode === this.editor.editNode){
762 if(!endNode.hasChildNodes()){
763 return;
764 }
765 if(this._isInlineOrTextElement(endNode.lastChild)){
766 this._rebuildBlock(endNode);
767 }
768 endNode = this._getClosestBlock(endNode.lastChild, "end", null);
769 }
770
771 // Collect all selected block elements, which contain or can contain text.
772 // Walk through DOM tree between start and end points of current selection.
773 var origStartOffset = tempRange? tempRange.startOffset : 0,
774 origEndOffset = tempRange? tempRange.endOffset : 0,
775 origStartContainer = tempRange? tempRange.startContainer : null,
776 origEndContainer = tempRange? tempRange.endContainer : null;
777 var info = this._collectNodes(startNode, endNode, commonAncestor, tempRange, nodes,
778 origStartContainer, origStartOffset, origEndContainer, origEndOffset, cmd);
779 var nodesInfo = {nodes: nodes, groups: info.groups, cells: info.cells};
780 cmd = cmd.toString();
781 // Execution of specific action for each element from collection
782 switch(cmd){
783 //change direction
784 case "mirror":
785 case "ltr":
786 case "rtl":
787 //change alignment
788 case "left":
789 case "right":
790 case "center":
791 //explicit direction setting
792 case "explicitdir":
793 this._execDirAndAlignment(nodesInfo, cmd, arg);
794 break;
795 //before executing 'insert list' native command
796 case "preparelists":
797 this._prepareLists(nodesInfo, arg);
798 break;
799 //after executing 'insert list' native command
800 case "insertorderedlist":
801 case "insertunorderedlist":
802 this._execInsertLists(nodesInfo);
803 break;
804 //before executing 'outdent' native command
805 case "prepareoutdent":
806 this._prepareOutdent(nodesInfo);
807 break;
808 //before executing 'indent' native command
809 case "prepareindent":
810 this._prepareIndent(nodesInfo);
811 break;
812 //after executing 'indent' native command
813 case "indent":
814 this._execIndent(nodesInfo);
815 break;
816 //after executing 'outdent' native command
817 case "outdent":
818 this._execOutdent(nodesInfo);
819 break;
820 //replace native 'indent' and 'outdent' commands
821 case "normalizeindent":
822 this._execNormalizedIndent(nodesInfo);
823 break;
824 case "normalizeoutdent":
825 this._execNormalizedOutdent(nodesInfo);
826 break;
827 //before 'formatblock' native command
828 case "prepareformat":
829 this._prepareFormat(nodesInfo, arg);
830 break;
831 //after executing 'formatblock' native command
832 case "formatblock":
833 this._execFormatBlocks(nodesInfo, arg);
834 break;
835 default: console.error("Command " + cmd + " isn't handled");
836 }
837 // Refine selection after changes
838 if(tempRange){
839 tempRange.setStart(origStartContainer, origStartOffset);
840 tempRange.setEnd(origEndContainer, origEndOffset);
841 sel = rangeapi.getSelection(this.editor.window, true);
842 sel.removeAllRanges();
843 sel.addRange(tempRange);
844 this.editor.onDisplayChanged();
845 }
846 return nodesInfo;
847 },
848
849 _collectNodes: function(startNode, endNode, commonAncestor, tempRange, nodes, origStartContainer, origStartOffset, origEndContainer, origEndOffset, cmd){
850 // summary:
851 // Collect all selected block elements, which contain or can contain text.
852 // Walk through DOM tree between start and end points of current selection.
853 var node = startNode, sibling, child, parent = node.parentNode, divs = [],
854 firstSibling, lastSibling, groups = [], group = [], cells = [], curTD = this.editor.editNode;
855 var saveNodesAndGroups = lang.hitch(this, function(x){
856 nodes.push(x);
857 var cell = this.editor.selection.getParentOfType(x,["TD"]);
858 if(curTD !== cell || has("webkit") && (cmd === "prepareformat" || cmd === "preparelists")){
859 if(group.length){
860 groups.push(group);
861 }
862 group = [];
863 if(curTD != cell){
864 curTD = cell;
865 if(curTD){
866 cells.push(curTD);
867 }
868 }
869 }
870 group.push(x);
871 });
872 this._rebuildBlock(parent);
873 while(true){
874 if(this._hasTagFrom(node,this._tableContainers)){
875 if(node.firstChild){
876 parent = node;
877 node = node.firstChild;
878 continue;
879 }
880 }else if(this._isBlockElement(node)){
881 var supLI = rangeapi.getBlockAncestor(node, /li/i, this.editor.editNode).blockNode;
882 if(supLI && supLI !== node){
883 node = supLI;
884 parent = node.parentNode;
885 continue;
886 }
887 if(!this._hasTag(node,"LI")){
888 if(node.firstChild){
889 this._rebuildBlock(node);
890 if(this._isBlockElement(node.firstChild) || this._hasTagFrom(node.firstChild,this._tableContainers)){
891 parent = node;
892 node = node.firstChild;
893 continue;
894 }
895 }
896 }
897 if(this._hasTagFrom(node,this._lineTextArray)){
898 saveNodesAndGroups(node);
899 }
900 }else if(this._isInlineOrTextElement(node) && !this._hasTagFrom(node.parentNode,this._tableContainers)){
901 firstSibling = node;
902 while(node){
903 var nextSibling = node.nextSibling;
904 if(this._isInlineOrTextElement(node)){
905 lastSibling = node;
906 if(this._hasTag(node,"BR")){
907 if(!(this._isBlockElement(parent) && node === parent.lastChild)){
908 divs = this._repackInlineElements(firstSibling, lastSibling, parent);
909 node = divs[divs.length-1];
910 for(var nd = 0; nd < divs.length; nd++){
911 saveNodesAndGroups(divs[nd]);
912 }
913 firstSibling = lastSibling = null;
914 if(nextSibling && this._isInlineOrTextElement(nextSibling)){
915 firstSibling = nextSibling;
916 }
917 }
918 }
919 }else if(this._isBlockElement(node)){
920 break;
921 }
922 node = nextSibling;
923 }
924 if(!firstSibling){
925 continue;
926 }
927 divs = this._repackInlineElements(firstSibling, lastSibling, parent);
928 node = divs[divs.length-1];
929 for(var nd = 0; nd < divs.length; nd++){
930 saveNodesAndGroups(divs[nd]);
931 }
932 }
933
934 if(node === endNode){
935 break;
936 }
937 if(node.nextSibling){
938 node = node.nextSibling;
939 }else if(parent !== commonAncestor){
940 while(!parent.nextSibling){
941 node = parent;
942 parent = node.parentNode;
943 if(parent === commonAncestor){
944 break;
945 }
946 }
947 if(parent !== commonAncestor && parent.nextSibling){
948 node = parent.nextSibling;
949 parent = parent.parentNode;
950 }else{
951 break;
952 }
953 }else{
954 break;
955 }
956 }
957 if(group.length){
958 if(has("webkit") || curTD){
959 groups.push(group);
960 }else{
961 groups.unshift(group);
962 }
963 }
964 return {groups: groups, cells: cells};
965 },
966
967 _execDirAndAlignment: function(nodesInfo, cmd,arg){
968 // summary:
969 // Change direction and/or alignment of each node from the given array.
970 switch(cmd){
971 //change direction
972 case "mirror":
973 case "ltr":
974 case "rtl":
975 array.forEach(nodesInfo.nodes, function(x){
976 var style = domStyle.getComputedStyle(x),
977 curDir = style.direction,
978 oppositeDir = curDir == "ltr"? "rtl" : "ltr",
979 realDir = (cmd != "mirror"? cmd : oppositeDir),
980 curAlign = style.textAlign,
981 marginLeft = isNaN(parseInt(style.marginLeft))? 0 : parseInt(style.marginLeft),
982 marginRight = isNaN(parseInt(style.marginRight))? 0 : parseInt(style.marginRight);
983 domAttr.remove(x,"dir");
984 domAttr.remove(x,"align");
985 domStyle.set(x, {direction: realDir, textAlign: ""});
986 if(this._hasTag(x,"CENTER")){
987 return;
988 }
989 if(curAlign.indexOf("center") >= 0){
990 domStyle.set(x,"textAlign","center");
991 }
992 if(this._hasTag(x,"LI")){
993 this._refineLIMargins(x);
994 var margin = curDir === "rtl"? marginRight : marginLeft;
995 var level = 0, tNode = x.parentNode, name;
996 if(curDir != domStyle.get(tNode,"direction")){
997 while(tNode !== this.editor.editNode){
998 if(this._hasTagFrom(tNode,["OL","UL"])){
999 level++;
1000 }
1001 tNode = tNode.parentNode;
1002 }
1003 margin -= this._getMargins(level);
1004 }
1005 var styleMargin = realDir == "rtl"? "marginRight" : "marginLeft";
1006 var cMargin = domStyle.get(x,styleMargin);
1007 var cIndent = isNaN(cMargin)? 0 : parseInt(cMargin);
1008 domStyle.set(x,styleMargin,"" + (cIndent + margin) + "px");
1009 if(has("webkit")){
1010 if(curAlign.indexOf("center") < 0){
1011 domStyle.set(x, "textAlign", (realDir == "rtl"? "right" : "left"));
1012 }
1013 }else if(x.firstChild && x.firstChild.tagName){
1014 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1015 var style = domStyle.getComputedStyle(x),
1016 align = this._refineAlignment(style.direction, style.textAlign);
1017 if(has("mozilla")){
1018 domStyle.set(x.firstChild, {textAlign: align});
1019 }else{
1020 domStyle.set(x.firstChild, {direction : realDir, textAlign: align});
1021 }
1022 }
1023 }
1024 }else{
1025 if(realDir == "rtl" && marginLeft != 0){
1026 domStyle.set(x, {marginLeft: "", marginRight: "" + marginLeft + "px"});
1027 }else if(realDir == "ltr" && marginRight != 0){
1028 domStyle.set(x, {marginRight: "", marginLeft: "" + marginRight + "px"});
1029 }
1030 }
1031 },this);
1032 query("table",this.editor.editNode).forEach(function(table,idx,array){
1033 var dir = cmd;
1034 if(cmd === "mirror"){
1035 dir = domStyle.get(table,"direction") === "ltr"? "rtl" : "ltr";
1036 }
1037 var listTD = query("td",table), first = false, last = false;
1038 for(var i = 0; i < nodesInfo.cells.length; i++){
1039 if(!first && listTD[0] === nodesInfo.cells[i]){
1040 first = true;
1041 }else if(listTD[listTD.length-1] === nodesInfo.cells[i]){
1042 last = true;
1043 break;
1044 }
1045 }
1046 if(first && last){
1047 domStyle.set(table,"direction",dir);
1048 for(i = 0; i < listTD.length; i++){
1049 domStyle.set(listTD[i],"direction",dir);
1050 }
1051 }
1052 },this);
1053 break;
1054 //change alignment
1055 case "left":
1056 case "right":
1057 case "center":
1058 array.forEach(nodesInfo.nodes, function(x){
1059 if(this._hasTag(x,"CENTER")){
1060 return;
1061 }
1062 domAttr.remove(x,"align");
1063 domStyle.set(x,"textAlign",cmd);
1064 if(this._hasTag(x,"LI")){
1065 if(x.firstChild && x.firstChild.tagName){
1066 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1067 var style = domStyle.getComputedStyle(x),
1068 align = this._refineAlignment(style.direction, style.textAlign);
1069 domStyle.set(x.firstChild, "textAlign", align);
1070 }
1071 }
1072 }
1073 },this);
1074 break;
1075 //explicit direction setting
1076 case "explicitdir":
1077 array.forEach(nodesInfo.nodes, function(x){
1078 var style = domStyle.getComputedStyle(x),
1079 curDir = style.direction;
1080 domAttr.remove(x,"dir");
1081 domStyle.set(x, {direction: curDir});
1082 },this);
1083 break;
1084 }
1085 },
1086
1087 _prepareLists: function(nodesInfo, arg){
1088 // summary:
1089 // Perform changes before native insertorderedlist and
1090 // insertunorderedlist commands for each node from the given array.
1091 array.forEach(nodesInfo.nodes, function(x,index,arr){
1092 if(has("mozilla") || has("webkit")){
1093 //Mozilla not always handles the only block inside cell
1094 if(has("mozilla")){
1095 var cell = this._getParentFrom(x,["TD"]);
1096 if(cell && query("div[tempRole]",cell).length == 0){
1097 domConstruct.create("div",{innerHTML: "<span tempRole='true'>" + this.bogusHtmlContent + "</span", tempRole: "true"},cell);
1098 }
1099 }
1100 var name = this._tag(x);
1101 var styledSpan;
1102 if(has("webkit") && this._hasTagFrom(x,this._lineStyledTextArray) ||
1103 (this._hasTag(x,"LI") && this._hasStyledTextLineTag(x.firstChild))){
1104 var savedName = this._hasTag(x,"LI")? this._tag(x.firstChild) : name;
1105 if(this._hasTag(x,"LI")){
1106 while(x.firstChild.lastChild){
1107 domConstruct.place(x.firstChild.lastChild,x.firstChild,"after");
1108 }
1109 x.removeChild(x.firstChild);
1110 }
1111 styledSpan = domConstruct.create("span",{innerHTML: this.bogusHtmlContent, bogusFormat: savedName},x,"first");
1112 }
1113 if(!has("webkit") && name != "DIV" && name != "P" && name != "LI"){
1114 return;
1115 }
1116 // In some cases, when one of insertlists command is executed for list of another type, and selection
1117 // includes the last item of this list, webkit loses current selection after native call.
1118 // To avoid this we append the list with bogus item, which finally will be removed by "post" action.
1119 if(has("webkit") && this._isListTypeChanged(x, arg) && x === x.parentNode.lastChild){
1120 domConstruct.create("li",{tempRole: "true"},x,"after");
1121 }
1122 if(name == "LI" && x.firstChild && x.firstChild.tagName){
1123 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1124 return;
1125 }
1126 }
1127 // When blocks are converted into list items, their attributes are lost.
1128 // We save attributes in some bogus inline element with the goal to restore
1129 // them after execution the command.
1130 var style = domStyle.getComputedStyle(x),curDir = style.direction,curAlign = style.textAlign;
1131 curAlign = this._refineAlignment(curDir, curAlign);
1132 var val = this._getLIIndent(x);
1133 var margin = val == 0? "" : "" + val + "px";
1134 if(has("webkit") && name == "LI"){
1135 domStyle.set(x,"textAlign","");
1136 }
1137 var span = styledSpan? x.firstChild : domConstruct.create("span",{innerHTML: this.bogusHtmlContent},x,"first");
1138 domAttr.set(span,"bogusDir",curDir);
1139 if(curAlign != ""){
1140 domAttr.set(span,"bogusAlign",curAlign);
1141 }
1142 if(margin){
1143 domAttr.set(span,"bogusMargin",margin);
1144 }
1145 }else if(has("ie")){
1146 // When IE executes insertlist command for list item, containing block,
1147 // it saves styles of list item in this block. We should then remove
1148 // bogus margins, if list item is converted into the block.
1149 if(this._hasTag(x,"LI")){
1150 var dir = domStyle.getComputedStyle(x).direction;
1151 domStyle.set(x,"marginRight","");
1152 domStyle.set(x,"marginLeft","");
1153 if(this._getLILevel(x) == 1 && !this._isListTypeChanged(x,cmd)){
1154 if(x.firstChild && this._hasTagFrom(x.firstChild,["P","PRE"])){
1155 domConstruct.create("span",{bogusIEFormat: this._tag(x.firstChild)},x.firstChild,"first");
1156 }
1157 //IE fais, when try to handle list items, containing PRE
1158 if(this._hasTag(x.firstChild,"PRE")){
1159 var p = domConstruct.create("p",null,x.firstChild,"after");
1160 while(x.firstChild.firstChild){
1161 domConstruct.place(x.firstChild.firstChild,p,"last");
1162 }
1163 p.style.cssText = x.style.cssText;
1164 x.removeChild(x.firstChild);
1165 }
1166 }
1167 }
1168 }
1169 },this);
1170 // If selection includes some cells of table and some items of one-level list, which is the table's next sibling,
1171 // webkit doesn't complete the action. For example, having <table>...</table><ul><li>One</li><li>Two</li></ul>,
1172 // after executing "insertunorderedlist" command, we get <table>...</table><ul><li>One</li>Two.
1173 // To avoid this, we add after the table some bogus list, which will be deleted after executing "post native" action.
1174 if(has("webkit")){
1175 query("table",this.editor.editNode).forEach(function(x,ind,arr){
1176 var sibling = x.nextSibling;
1177 if(sibling && this._hasTagFrom(sibling,["UL","OL"])){
1178 domConstruct.create("UL",{tempRole: "true"},x,"after");
1179 }
1180 },this);
1181 }
1182 },
1183
1184 _execInsertLists: function(nodesInfo){
1185 array.forEach(nodesInfo.nodes, function(x,index){
1186 if(this._hasTag(x,"LI")){
1187 //If one of "styled" text blocks, like <h*> or <pre>, is converted
1188 //into list item, it actually is included into new list item,
1189 //created without attributes. This causes problems in subsequent changes
1190 //of orientation or alignment of this list item.
1191 if(x.firstChild && x.firstChild.tagName){
1192 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1193 var style = domStyle.getComputedStyle(x.firstChild),
1194 align = this._refineAlignment(style.direction, style.textAlign);
1195 domStyle.set(x,{direction: style.direction, textAlign: align});
1196 var mLeft = this._getIntStyleValue(x,"marginLeft") + this._getIntStyleValue(x.firstChild,"marginLeft");
1197 var mRight = this._getIntStyleValue(x,"marginRight") + this._getIntStyleValue(x.firstChild,"marginRight");
1198 var leftMargin = mLeft? "" + mLeft + "px" : "";
1199 var rightMargin = mRight? "" + mRight + "px" : "";
1200 domStyle.set(x,{marginLeft: leftMargin, marginRight: rightMargin});
1201 domStyle.set(x.firstChild,{direction: "", textAlign: ""});
1202 if(!has("mozilla")){
1203 domStyle.set(x.firstChild,{marginLeft: "", marginRight: ""});
1204 }
1205 }
1206 }
1207 //Mozilla sometimes includes few empty text nodes (or text nodes, containing spaces)
1208 //to the end of newly created list item
1209 while(x.childNodes.length > 1){
1210 if(!(x.lastChild.nodeType == 3 && x.lastChild.previousSibling && x.lastChild.previousSibling.nodeType == 3 && lang.trim(x.lastChild.nodeValue) == "")){
1211 break;
1212 }
1213 x.removeChild(x.lastChild);
1214 }
1215 if(has("safari")){
1216 if(this._hasTag(x.firstChild,"SPAN") && domClass.contains(x.firstChild,"Apple-style-span")){
1217 var child = x.firstChild;
1218 if(this._hasTag(child.firstChild,"SPAN") && domAttr.has(child.firstChild,"bogusFormat")){
1219 while(child.lastChild){
1220 domConstruct.place(child.lastChild,child,"after");
1221 }
1222 x.removeChild(child);
1223 }
1224 }
1225 }
1226 }else if(this._hasTag(x,"DIV") && x.childNodes.length == 0){
1227 x.parentNode.removeChild(x);
1228 return;
1229 }
1230 if(has("ie")){
1231 // IE always converts list items to <P>
1232 if(this._hasTag(x,"P") && this.blockMode.toUpperCase() == "DIV"){
1233 if(this._hasTag(x.firstChild,"SPAN") && domAttr.has(x.firstChild,"bogusIEFormat")){
1234 if(domAttr.get(x.firstChild,"bogusIEFormat").toUpperCase() === "PRE"){
1235 var pre = domConstruct.create("pre",{innerHTML: x.innerHTML},x,"before");
1236 pre.style.cssText = x.style.cssText;
1237 pre.removeChild(pre.firstChild);
1238 x.parentNode.removeChild(x);
1239 }else{
1240 x.removeChild(x.firstChild);
1241 }
1242 return;
1243 }
1244 var nDiv = domConstruct.create("div");
1245 nDiv.style.cssText = x.style.cssText;
1246 x.parentNode.insertBefore(nDiv,x);
1247 while(x.firstChild){
1248 nDiv.appendChild(x.firstChild);
1249 }
1250 x.parentNode.removeChild(x);
1251 }
1252 if(!this._hasTag(x,"LI")){
1253 return;
1254 }
1255 this._refineLIMargins(x);
1256 // Instead of converting regular block into list item, IE includes block into the newly created item
1257 var div = x.firstChild;
1258 if(!this._hasTag(div,"DIV")){
1259 return;
1260 }
1261 if(!(div === x.lastChild)){
1262 return;
1263 }
1264 var style = domStyle.getComputedStyle(div), dir = style.direction, align = style.textAlign,
1265 curAlign = domStyle.getComputedStyle(x).textAlign;
1266 domStyle.set(x,"direction",dir);
1267 align = this._refineAlignment(dir, align);
1268 domStyle.set(x,"textAlign",align);
1269 while(div.firstChild){
1270 x.insertBefore(div.firstChild, div);
1271 }
1272 x.removeChild(div);
1273 }else if(!this._hasTag(x.firstChild,"SPAN")){
1274 if(this._hasTag(x,"LI")){
1275 this._refineLIMargins(x);
1276 if(has("mozilla") && this._hasStyledTextLineTag(x.firstChild)){
1277 this._recountLIMargins(x);
1278 }
1279 }
1280 return;
1281 }
1282 // Restore attributes and remove bogus elments
1283 var hasBogusSpan = false;
1284 var indentWithMargin = false;
1285 var hasBogusAlign = false;
1286 var marginVal = 0;
1287 if(domAttr.has(x.firstChild,"bogusDir")){
1288 hasBogusSpan = true;
1289 var dir = domAttr.get(x.firstChild,"bogusDir");
1290 domStyle.set(x,"direction",dir);
1291 }
1292 if(domAttr.has(x.firstChild,"bogusAlign")){
1293 hasBogusSpan = true;
1294 hasBogusAlign = true;
1295 var align = domAttr.get(x.firstChild,"bogusAlign");
1296 domStyle.set(x,"textAlign",align);
1297 var sibling = x.firstChild.nextSibling;
1298 if(this._hasTag(sibling,"SPAN") && domStyle.get(sibling,"textAlign") === align){
1299 domStyle.set(sibling,"textAlign","");
1300 if(sibling.style.cssText == ""){
1301 while(sibling.lastChild){
1302 domConstruct.place(sibling.lastChild,sibling,"after");
1303 }
1304 x.removeChild(sibling);
1305 }
1306 }
1307 }
1308 if(domAttr.has(x.firstChild,"bogusMargin")){
1309 hasBogusSpan = true;
1310 indentWithMargin = true;
1311 marginVal = parseInt(domAttr.get(x.firstChild,"bogusMargin"));
1312 if(!this._hasTag(x,"LI")){
1313 var mStyle = domStyle.get(x,"direction") === "rtl"? "marginRight" : "marginLeft";
1314 var mVal = this._getIntStyleValue(x,mStyle) + marginVal;
1315 domStyle.set(x,mStyle,(mVal == 0? "" : "" + mVal + "px"));
1316 }
1317 }
1318 if(domAttr.has(x.firstChild,"bogusFormat")){
1319 hasBogusSpan = false;
1320 domAttr.remove(x.firstChild,"bogusDir");
1321 if(x.firstChild.nextSibling && this._hasTag(x.firstChild.nextSibling,"SPAN")){
1322 var bogusStyles = x.firstChild.style.cssText.trim().split(";");
1323 var savedStyles = x.firstChild.nextSibling.style.cssText.trim().split(";");
1324 for(var i = 0; i < bogusStyles.length; i++){
1325 if(bogusStyles[i]){
1326 for(var j = 0; j < savedStyles.length; j++){
1327 if(bogusStyles[i].trim() == savedStyles[j].trim()){
1328 var style = bogusStyles[i].trim().split(":")[0];
1329 domStyle.set(x.firstChild.nextSibling,style,"");
1330 break;
1331 }
1332 }
1333 }
1334 }
1335 if(x.firstChild.nextSibling.style.cssText === ""){
1336 while(x.firstChild.nextSibling.firstChild){
1337 domConstruct.place(x.firstChild.nextSibling.firstChild,x.firstChild.nextSibling,"after");
1338 }
1339 x.removeChild(x.firstChild.nextSibling);
1340 }
1341 }
1342 var tag = domAttr.get(x.firstChild,"bogusFormat");
1343 var block = domConstruct.create(tag,null,x.firstChild,"after");
1344 while(block.nextSibling){
1345 domConstruct.place(block.nextSibling,block,"last");
1346 }
1347 x.removeChild(x.firstChild);
1348 if(has("webkit")){
1349 if(this._hasTag(x,"LI")){
1350 var parent = x.parentNode.parentNode;
1351 if(this._hasTag(parent,tag)){
1352 domAttr.set(parent,"tempRole","true");
1353 }
1354 }
1355 }
1356 if(x.childNodes.length == 1 && !this._hasTag(x,"TD")){
1357 if(!has("mozilla") && !this._hasTag(x,"LI")){
1358 block.style.cssText = x.style.cssText;
1359 domAttr.set(x,"tempRole","true");
1360 }else if(!this._hasTag(x,"LI")){
1361 block.style.cssText = x.style.cssText;
1362 domConstruct.place(block,x,"after");
1363 domAttr.set(x,"tempRole","true");
1364 }
1365 }
1366 }
1367 if(hasBogusSpan){
1368 x.removeChild(x.firstChild);
1369 }
1370 if(this._hasTag(x,"LI")){
1371 // Chrome: if direction of list item is differ from default orientation, text alignment
1372 // of this item should be set explicitly
1373 if(has("webkit") && !hasBogusAlign && domStyle.get(x,"textAlign") != "center"){
1374 domStyle.set(x,"textAlign",(domStyle.get(x,"direction") == "rtl"? "right" : "left"));
1375 }
1376 // Safari: when type of the list, having differently directed items, is changed, Safari inserts sometimes
1377 // into this list DIV with the contents of previous list item.
1378 if(has("safari") && this._hasTag(x,"DIV")){
1379 x.innerHTML = x.nextSibling.innerHTML;
1380 x.parentNode.removeChild(x.nextSibling);
1381 }
1382 var pDiv = x.parentNode.parentNode;
1383 if(pDiv !== this.editor.editNode && this._hasTag(pDiv,"DIV")){
1384 if(pDiv.childNodes.length == 1){
1385 pDiv.parentNode.insertBefore(x.parentNode,pDiv);
1386 pDiv.parentNode.removeChild(pDiv);
1387 }
1388 }
1389 this._refineLIMargins(x);
1390 if(indentWithMargin){
1391 this._recountLIMargins(x, marginVal);
1392 }
1393 }
1394 },this);
1395 if(has("mozilla")){
1396 query("*[tempRole]",this.editor.editNode).forEach(function(x,index,arr){
1397 if(this._hasTag(x,"SPAN")){
1398 if(domAttr.get(x.parentNode,"tempRole")){
1399 return;
1400 }else if(this._hasTag(x.parentNode,"LI")){
1401 x.parentNode.parentNode.removeChild(x.parentNode);
1402 return;
1403 }
1404 }
1405 x.parentNode.removeChild(x);
1406 },this);
1407 }else if(has("webkit")){
1408 query("*[tempRole]",this.editor.editNode).forEach(function(x,index,arr){
1409 if(this._hasTag(x, "LI") || this._hasTag(x,"UL")){
1410 return;
1411 }
1412 while(x.lastChild){
1413 domConstruct.place(x.lastChild,x,"after");
1414 }
1415 x.parentNode.removeChild(x);
1416 },this);
1417 }
1418 },
1419
1420 _execNormalizedIndent: function(nodesInfo){
1421 array.forEach(nodesInfo.nodes, function(x){
1422 var style = domStyle.get(x,"direction") === "rtl"? "marginRight" : "marginLeft";
1423 var cMargin = domStyle.get(x,style);
1424 var cIndent = isNaN(cMargin)? 0 : parseInt(cMargin);
1425 domStyle.set(x,style,"" + (cIndent + this._indentBy) + "px");
1426 },this);
1427 },
1428
1429 _execNormalizedOutdent: function(nodesInfo){
1430 array.forEach(nodesInfo.nodes, function(x){
1431 var style = domStyle.get(x,"direction") === "rtl"? "marginRight" : "marginLeft";
1432 var cMargin = domStyle.get(x,style)
1433 var cIndent = isNaN(cMargin)? 0 : parseInt(cMargin);
1434 var offs = 0;
1435 if(x.tagName.toUpperCase() === "LI"){
1436 var level = 0, tNode = x.parentNode, name;
1437 if(domStyle.get(x,"direction") != domStyle.get(tNode,"direction")){
1438 while(tNode !== this.editor.editNode){
1439 if(this._hasTagFrom(tNode,["OL","UL"])){
1440 level++;
1441 }
1442 tNode = tNode.parentNode;
1443 }
1444 offs = this._getMargins(level);
1445 }
1446 }
1447 if(cIndent >= this._indentBy + offs){
1448 domStyle.set(x,style,(cIndent == this._indentBy? "" : "" + (cIndent - this._indentBy) + "px"));
1449 }
1450 },this);
1451 },
1452
1453 _prepareIndent: function(nodesInfo){
1454 array.forEach(nodesInfo.nodes, function(x){
1455 if(has("mozilla")){
1456 var cell = this._getParentFrom(x,["TD"]);
1457 if(!!cell && (query("div[tempRole]",cell).length == 0)){
1458 domConstruct.create("div",{innerHTML: this.bogusHtmlContent, tempRole: "true"},cell);
1459 }
1460 if(this._hasTag(x,"LI")){
1461 var indent = this._getLIIndent(x);
1462 domAttr.set(x,"tempIndent",indent);
1463 }
1464 }
1465 if(has("webkit") && this._hasTag(x,"LI") && this._hasStyledTextLineTag(x.firstChild)){
1466 var name = this._tag(x.firstChild);
1467 while(x.firstChild.lastChild){
1468 domConstruct.place(x.firstChild.lastChild,x.firstChild,"after");
1469 }
1470 x.removeChild(x.firstChild);
1471 domConstruct.create("span",{innerHTML: this.bogusHtmlContent, bogusFormat: name},x,"first");
1472 }
1473 },this);
1474 },
1475
1476 _prepareOutdent: function(nodesInfo){
1477 array.forEach(nodesInfo.nodes, function(x){
1478 if(has("mozilla") || has("webkit")){
1479 if(has("mozilla")){
1480 var cell = this._getParentFrom(x,["TD"]);
1481 if(!!cell && (query("div[tempRole]",cell).length == 0)){
1482 domConstruct.create("div",{innerHTML: this.bogusHtmlContent, tempRole: "true"},cell);
1483 }
1484 }
1485 // FF: Outdent for the list items from first level's list converts them into sequence of
1486 // text elements, separated by <BR>s. Attributes of list items are lost.
1487 // Webkit: Attributes of items, placed into blockquote, are lost after outdent.
1488 // We save attributes in some bogus inline element with the goal to restore
1489 // them after execution the command.
1490 var name = this._tag(x);
1491 if(has("mozilla") && name !== "LI"){
1492 return;
1493 }
1494 var styledSpan = null;
1495 if(has("webkit")){
1496 if(this._hasTag(x,"LI") && this._hasStyledTextLineTag(x.firstChild)){
1497 name = this._tag(x.firstChild);
1498 var child = x.firstChild;
1499 while(child.lastChild){
1500 domConstruct.place(child.lastChild,child,"after");
1501 }
1502 x.removeChild(x.firstChild);
1503 styledSpan = domConstruct.create("span",{innerHTML: this.bogusHtmlContent, bogusFormat: name},x,"first");
1504 }
1505 }
1506 if(x.firstChild && x.firstChild.tagName){
1507 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1508 if(has("mozilla")){
1509 x.firstChild.style.cssText = x.style.cssText;
1510 var margin = domStyle.get(x,"direction") === "rtl"? "marginRight" : "marginLeft";
1511 var indent = this._getLIIndent(x);
1512 if(indent > 0){
1513 domStyle.set(x.firstChild,margin,"" + indent + "px");
1514 }
1515 }
1516 return;
1517 }
1518 }
1519 var style = domStyle.getComputedStyle(x),curDir = style.direction,curAlign = style.textAlign;
1520 curAlign = this._refineAlignment(curDir, curAlign);
1521 if(has("webkit") && name == "LI"){
1522 domStyle.set(x,"textAlign","");
1523 }
1524 var span = styledSpan? x.firstChild : domConstruct.create("span",{innerHTML: this.bogusHtmlContent},x,"first");
1525 domAttr.set(span,"bogusDir",curDir);
1526 if(curAlign != ""){
1527 domAttr.set(span,"bogusAlign",curAlign);
1528 }
1529 if(has("mozilla")){
1530 var indent = this._getLIIndent(x);
1531 domAttr.set(span,"bogusIndent",indent);
1532 }
1533 }
1534 if(has("ie")){
1535 if(x.tagName.toUpperCase() == "LI"){
1536 domStyle.set(x,"marginLeft","");
1537 domStyle.set(x,"marginRight","");
1538 if(this._getLILevel(x) == 1){
1539 if(x.firstChild && this._hasTagFrom(x.firstChild,["P","PRE"])){
1540 domConstruct.create("span",{bogusIEFormat: this._tag(x.firstChild)},x.firstChild,"first");
1541 }
1542 //IE fais, when try to handle first level list items, containing PRE
1543 if(this._hasTag(x.firstChild,"PRE")){
1544 var p = domConstruct.create("p",null,x.firstChild,"after");
1545 while(x.firstChild.firstChild){
1546 domConstruct.place(x.firstChild.firstChild,p,"last");
1547 }
1548 p.style.cssText = x.style.cssText;
1549 x.removeChild(x.firstChild);
1550 }
1551 }
1552 }
1553 }
1554 },this);
1555 },
1556
1557 _execIndent: function(nodesInfo){
1558 array.forEach(nodesInfo.nodes, function(x){
1559 if(!has("mozilla")){
1560 domStyle.set(x,"margin","");
1561 }
1562 if(this._hasTag(x,"LI")){
1563 var indent = 0;
1564 if(has("mozilla") && domAttr.has(x,"tempIndent")){
1565 indent = parseInt(domAttr.get(x,"tempIndent"));
1566 domAttr.remove(x,"tempIndent");
1567 }
1568 this._refineLIMargins(x);
1569 if(has("mozilla")){
1570 this._recountLIMargins(x,indent);
1571 }
1572 }
1573 if(domAttr.has(x.firstChild,"bogusFormat")){
1574 var tag = domAttr.get(x.firstChild,"bogusFormat");
1575 var block = domConstruct.create(tag,null,x.firstChild,"after");
1576 while(block.nextSibling){
1577 domConstruct.place(block.nextSibling,block,"last");
1578 }
1579 x.removeChild(x.firstChild);
1580 }
1581 if(has("ie") || has("webkit")){
1582 // Remove attribute dir from newly created blockquotes
1583 var supBq = x.parentNode;
1584 while(supBq !== this.editor.editNode){
1585 supBq = rangeapi.getBlockAncestor(supBq, /blockquote/i, this.editor.editNode).blockNode;
1586 if(!supBq){
1587 break;
1588 }
1589 if(domAttr.has(supBq, "dir")){
1590 domAttr.remove(supBq, "dir");
1591 }
1592 domStyle.set(supBq,"marginLeft","");
1593 domStyle.set(supBq,"marginRight","");
1594 domStyle.set(supBq,"margin","");
1595 supBq = supBq.parentNode;
1596 }
1597 }
1598 },this);
1599 if(has("mozilla")){
1600 query("div[tempRole]",this.editor.editNode).forEach(function(x,index,arr){
1601 x.parentNode.removeChild(x);
1602 });
1603 query("ul,ol",this.editor.editNode).forEach(function(x,index,arr){
1604 domStyle.set(x,"marginLeft","");
1605 domStyle.set(x,"marginRight","");
1606 });
1607 }
1608 },
1609
1610 _execOutdent: function(nodesInfo){
1611 array.forEach(nodesInfo.nodes, function(x){
1612 if(has("mozilla") || has("webkit")){
1613 if(!this._hasTag(x.firstChild,"SPAN")){
1614 if(this._hasTag(x,"LI")){
1615 this._refineLIMargins(x);
1616 if(has("mozilla") && this._hasStyledTextLineTag(x.firstChild)){
1617 this._recountLIMargins(x);
1618 x.firstChild.style.cssText = "";
1619 }
1620 }
1621 return;
1622 }
1623 // Restore attributes and remove bogus elments
1624 var hasBogusSpan = false;
1625 var isFormatted = false;
1626 var indent = 0;
1627 if(domAttr.has(x.firstChild,"bogusDir")){
1628 hasBogusSpan = true;
1629 var dir = domAttr.get(x.firstChild,"bogusDir");
1630 domStyle.set(x,"direction",dir);
1631 }
1632 if(domAttr.has(x.firstChild,"bogusAlign")){
1633 hasBogusSpan = true;
1634 var align = domAttr.get(x.firstChild,"bogusAlign");
1635 domStyle.set(x,"textAlign",align);
1636 }
1637 if(domAttr.has(x.firstChild,"bogusIndent")){
1638 hasBogusSpan = true;
1639 indent = parseInt(domAttr.get(x.firstChild,"bogusIndent"));
1640 if(!this._hasTag(x, "LI")){
1641 var marginStyle = domStyle.get(x,"direction") === "rtl"? "marginRight" : "marginLeft";
1642 var marginVal = "" + (this._getIntStyleValue(x,marginStyle) + indent) + "px";
1643 domStyle.set(x,marginStyle,marginVal);
1644 }
1645 }
1646 if(domAttr.has(x.firstChild,"bogusFormat")){
1647 hasBogusSpan = true;
1648 var tag = domAttr.get(x.firstChild,"bogusFormat");
1649 var block = domConstruct.create(tag,null,x.firstChild,"after");
1650 while(block.nextSibling){
1651 domConstruct.place(block.nextSibling,block,"last");
1652 }
1653 if(!this._hasTag(x,"LI")){
1654 block.style.cssText = x.style.cssText;
1655 isFormatted = true;
1656 }
1657 }
1658 if(hasBogusSpan){
1659 x.removeChild(x.firstChild);
1660 if(isFormatted){
1661 while(x.lastChild){
1662 domConstruct.place(x.lastChild,x,"after");
1663 }
1664 domAttr.set(x,"tempRole","true");
1665 }
1666 }
1667 if(has("webkit") && this._hasTag(x,"LI") && domStyle.get(x,"textAlign") != "center"){
1668 domStyle.set(x,"textAlign",(domStyle.get(x,"direction") == "rtl"? "right" : "left"));
1669 }
1670 if(has("mozilla") && this._hasTag(x,"LI")){
1671 var pDiv = x.parentNode.parentNode;
1672 if(pDiv !== this.editor.editNode && this._hasTag(pDiv,"DIV")){
1673 if(pDiv.childNodes.length == 1){
1674 pDiv.parentNode.insertBefore(x.parentNode,pDiv);
1675 pDiv.parentNode.removeChild(pDiv);
1676 }
1677 }
1678 }
1679 }
1680 if(has("ie")){
1681 // IE always converts list items to <P>
1682 if(this._hasTag(x,"P") && this.blockMode.toUpperCase() == "DIV"){
1683 if(this._hasTag(x.firstChild,"SPAN") && domAttr.has(x.firstChild,"bogusIEFormat")){
1684 if(domAttr.get(x.firstChild,"bogusIEFormat").toUpperCase() === "PRE"){
1685 var pre = domConstruct.create("pre",{innerHTML: x.innerHTML},x,"before");
1686 pre.style.cssText = x.style.cssText;
1687 pre.removeChild(pre.firstChild);
1688 x.parentNode.removeChild(x);
1689 }else{
1690 x.removeChild(x.firstChild);
1691 }
1692 return;
1693 }
1694 var nDiv = domConstruct.create("div");
1695 nDiv.style.cssText = x.style.cssText;
1696 x.parentNode.insertBefore(nDiv,x);
1697 while(x.firstChild){
1698 nDiv.appendChild(x.firstChild);
1699 }
1700 x.parentNode.removeChild(x);
1701 }
1702 }
1703 if(this._hasTag(x,"LI")){
1704 this._refineLIMargins(x);
1705 if(has("mozilla")){
1706 this._recountLIMargins(x,indent);
1707 }
1708 }
1709 },this);
1710 if(has("mozilla") || has("webkit")){
1711 query("div[tempRole]",this.editor.editNode).forEach(function(x,index,arr){
1712 x.parentNode.removeChild(x);
1713 });
1714 }
1715 },
1716
1717 _prepareFormat: function(nodesInfo, arg){
1718 array.forEach(nodesInfo.nodes, function(x){
1719 // In some cases Mozill'a native 'formatblock' command mistakely merges contents of list items.
1720 // For example, for list with three items, containing some text like "one", "two", "three" and first two items selected,
1721 // after changing their format from "None" to "Paragraph" we get from <li>one</li><li>two<li> something like
1722 // <li><p>Onetwo</p></li><li><br></li>. Problem can be solved by 'manual' formatting,
1723 // so with given example we create <li><p>...</p></li> for each list item.
1724 if(has("mozilla")){
1725 if(this._hasTag(x,"LI")){
1726 if(x.firstChild && !this._isBlockElement(x.firstChild)){
1727 var div = x.ownerDocument.createElement(arg), sibling = x.firstChild;
1728 x.insertBefore(div, x.firstChild);
1729 while(sibling){
1730 div.appendChild(sibling);
1731 sibling = sibling.nextSibling;
1732 }
1733 }
1734 var indent = this._getLIIndent(x);
1735 domAttr.set(x,"tempIndent",indent);
1736 }
1737 }
1738 if(has("webkit")){
1739 var styledSpan;
1740 // If "fomatblocks" command is executed for list items, which already contain some blocks,
1741 // webkit merges contents of items. For example, after calling "formatblocks" with argument "P"
1742 // for two items <ul><li><h3>Hello</h3></li><li><h3>World</h3></li></ul> we get one item
1743 // <ul><li><p>Hello<br>World<p></li></ul>. To avoid this, we move contents of each block into
1744 // its parent,delete empty blocks and save info about required format in some bogus spans with
1745 // empty contents. Action, executed after native call, will recreate blocks in required format
1746 // and remove bogus spans.
1747 if(this._hasTag(x,"LI")){
1748 var savedName = arg;
1749 if(this._hasStyledTextLineTag(x.firstChild)){
1750 while(x.firstChild.lastChild){
1751 domConstruct.place(x.firstChild.lastChild,x.firstChild,"after");
1752 }
1753 x.removeChild(x.firstChild);
1754 }
1755 styledSpan = domConstruct.create("span",{innerHTML: this.bogusHtmlContent, bogusFormat: savedName},x,"first");
1756 }
1757 // Webkit lose 'direction' and 'textAlign' styles of reformatted blocks.
1758 // We save info about these styles in attributes of some bogus SPANs with empty contents.
1759 // Action, executed after native call, will restore styles of these blocks and remove bogus spans.
1760 var style = domStyle.getComputedStyle(x),curDir = style.direction,curAlign = style.textAlign;
1761 curAlign = this._refineAlignment(curDir, curAlign);
1762 var span = styledSpan? x.firstChild : domConstruct.create("span",{innerHTML: this.bogusHtmlContent},x,"first");
1763 domAttr.set(span,"bogusDir",curDir);
1764 if(curAlign != ""){
1765 domAttr.set(span,"bogusAlign",curAlign);
1766 }
1767 }
1768 },this);
1769 },
1770
1771 _execFormatBlocks: function(nodesInfo, arg){
1772 array.forEach(nodesInfo.nodes, function(x){
1773 if(this._hasTagFrom(x, this._lineTextArray)){
1774 //FF adds empty text nodes or nodes, containing spaces, after last converted block
1775 if(this._hasTag(x.parentNode,"DIV") && x.parentNode !== this.editor.editNode){
1776 while(x.parentNode.lastChild){
1777 if(!(x.parentNode.lastChild.nodeType == 3 && lang.trim(x.parentNode.lastChild.nodeValue) == "" ||
1778 this._hasTag(x.parentNode.lastChild,"BR"))){
1779 break;
1780 }
1781 x.parentNode.removeChild(x.parentNode.lastChild);
1782 }
1783 }
1784 if(this._hasTag(x.parentNode,"DIV") && x.parentNode !== this.editor.editNode && x.parentNode.childNodes.length == 1){
1785 var div = x.parentNode,
1786 style = domStyle.getComputedStyle(div),
1787 align = this._refineAlignment(style.direction, style.textAlign);
1788 domStyle.set(x, {direction: style.direction, textAlign: align});
1789 var margin = style.direction === "rtl"? "marginRight" : "marginLeft";
1790 var marginVal = parseInt(domStyle.get(div,margin));
1791 if(marginVal != 0 && !isNan(marginVal)){
1792 domStyle.set(x,margin,marginVal);
1793 }
1794 div.parentNode.insertBefore(x, div);
1795 div.parentNode.removeChild(div);
1796 }
1797 }
1798 if(this._hasTag(x,"LI")){
1799 var indent = 0;
1800 if(domAttr.has(x,"tempIndent")){
1801 indent = parseInt(domAttr.get(x,"tempIndent"));
1802 domAttr.remove(x,"tempIndent");
1803 }
1804 this._refineLIMargins(x);
1805 if(indent){
1806 this._recountLIMargins(x,indent);
1807 }
1808 while(x.childNodes.length > 1){
1809 if(!(x.lastChild.nodeType == 3 && lang.trim(x.lastChild.nodeValue) == "")){
1810 break;
1811 }
1812 x.removeChild(x.lastChild);
1813 }
1814 if(this._hasTagFrom(x.firstChild,this._lineStyledTextArray)){
1815 var style = domStyle.getComputedStyle(x),
1816 align = this._refineAlignment(style.direction, style.textAlign);
1817 if(!has("mozilla") && !(has("ie") && this._hasTag(x,"LI"))){
1818 domStyle.set(x.firstChild, {direction : style.direction, textAlign: align});
1819 }
1820 }else if(this._hasTag(x.firstChild,"DIV")){
1821 var div = x.firstChild;
1822 while(div.firstChild){
1823 x.insertBefore(div.firstChild, div);
1824 }
1825 x.removeChild(div);
1826 }
1827 // IE doesn't format list items with not formatted content into paragraphs
1828 if(has("ie") && !this._hasTag(x.firstChild,"P") && arg === "<p>"){
1829 var p = domConstruct.create("p");
1830 var block = this._hasTagFrom(p.nextSibling,this._lineStyledTextArray)? p.nextSibling : x;
1831 while(block.firstChild){
1832 domConstruct.place(block.firstChild,p,"last");
1833 }
1834 domConstruct.place(p,x,"first");
1835 if(block !== x){
1836 x.removeChild(block);
1837 }
1838 }
1839 }
1840 if(has("webkit")){
1841 // When "formatblocks" with argument "div" is executed for list items, containing blocks like <h1>
1842 // or <pre>, Safari loads contents of these blocks into newly created DIVs, and places these DIVs
1843 // into the same list as next siblings of source items. For example, if we have something like
1844 // <li><h3>Hello</h3></li>, we get <li><br></li><div>Hello</div>. So we move contents of these DIV's
1845 // into items and set special attributes for future deleting.
1846 if(this._hasTag(x,"DIV")){
1847 if(domAttr.has(x,"tempRole")){
1848 return;
1849 }else if(this._hasTag(x.previousSibling,"LI")){
1850 while(x.firstChild){
1851 domConstruct.place(x.firstChild,x.previousSibling,"last");
1852 }
1853 domAttr.set(x,"tempRole",true);
1854 x = x.previousSibling;
1855 }
1856 }
1857 // Restore attributes and remove bogus elments
1858 var hasBogusSpan = false;
1859 if(domAttr.has(x.firstChild,"bogusDir")){
1860 hasBogusSpan = true;
1861 var dir = domAttr.get(x.firstChild,"bogusDir");
1862 domStyle.set(x,"direction",dir);
1863 }
1864 if(domAttr.has(x.firstChild,"bogusAlign")){
1865 hasBogusSpan = true;
1866 var align = domAttr.get(x.firstChild,"bogusAlign");
1867 domStyle.set(x,"textAlign",align);
1868 }
1869 if(domAttr.has(x.firstChild,"bogusFormat")){
1870 hasBogusSpan = true;
1871 var tag = domAttr.get(x.firstChild,"bogusFormat");
1872 var block;
1873 if(tag.toUpperCase() !== "DIV"){
1874 block = domConstruct.create(tag,null,x.firstChild,"after");
1875 while(block.nextSibling){
1876 domConstruct.place(block.nextSibling,block,"last");
1877 }
1878 }else{
1879 block = x;
1880 }
1881 if(has("safari") && this._hasTag(x.nextSibling,"DIV")){
1882 while(x.nextSibling.firstChild){
1883 domConstruct.place(x.nextSibling.firstChild,block,"last");
1884 }
1885 domAttr.set(x.nextSibling,"tempRole","true");
1886 }
1887 }
1888 if(hasBogusSpan){
1889 x.removeChild(x.firstChild);
1890 }
1891 if(tag && this._hasTag(x, "LI")){
1892 var parent = x.parentNode.parentNode;
1893 if(this._hasTag(parent,tag)){
1894 domAttr.set(parent,"tempRole","true");
1895 }
1896 }
1897 }
1898 },this);
1899 // Safari in some cases put ito lists unnecessary divs. They already empty and marked with 'tempRole' attribute.
1900 // Both Chrome and Safari create for each formatted list item its own list and place such lists
1901 // into top-level block elements. In this method above, needed "styled" blocks are already recreated inside
1902 // list items, so corresponding top-level elements become unnecessary. They already marked with 'tempRole' attribute.
1903 // Now all elements having 'tempRole' attribute should be removed.
1904 if(has("webkit")){
1905 query("*[tempRole]",this.editor.editNode).forEach(function(x,index,arr){
1906 while(x.lastChild){
1907 domConstruct.place(x.lastChild,x,"after");
1908 }
1909 x.parentNode.removeChild(x);
1910 },this);
1911 }
1912 },
1913
1914 _rebuildBlock: function(block){
1915 // summary:
1916 // Finds a sequences of inline elements that are placed
1917 // within a top-level block element or have block siblings.
1918 // Calls _repackInlneElements(), which moves this sequences
1919 // into newly created block.
1920 var node = block.firstChild, firstSibling, lastSibling;
1921 var hasOwnBlock = false;
1922 while(node){
1923 if(this._isInlineOrTextElement(node) && !this._hasTagFrom(node,this._tableContainers)){
1924 hasOwnBlock = !this._hasTagFrom(block,this._lineTextArray);
1925 if(!firstSibling){
1926 firstSibling = node;
1927 }
1928 lastSibling = node;
1929 }else if(this._isBlockElement(node) || this._hasTagFrom(node,this._tableContainers)){
1930 if(firstSibling){
1931 this._repackInlineElements(firstSibling, lastSibling, block);
1932 firstSibling = null;
1933 }
1934 hasOwnBlock = true;
1935 }
1936 node = node.nextSibling;
1937 }
1938 if(hasOwnBlock && firstSibling){
1939 this._repackInlineElements(firstSibling, lastSibling, block);
1940 }
1941 },
1942
1943 _repackInlineElements: function(firstSibling, lastSibling, parent){
1944 // summary:
1945 // Moves sequences of inline elements into
1946 // newly created blocks
1947 // description:
1948 // This method handles sequences of inline elements, which are recognized by the user as
1949 // separate line(s) of the text, but are not placed into their own block element. Text direction
1950 // or alignment can't be set for such lines.
1951 // Possibles cases:
1952 // a) sequence directly belongs to editor's editNode;
1953 // b) sequence has block-level siblings;
1954 // c) sequence has BR in the start or in the middle of it.
1955 // For all these cases we create new block and move elements from the sequence into it.
1956 // We try to preserve explicitly defined styles, which have effect on this line. In case of
1957 // sequences, which directly belong to editNode, it is only direction of the text.
1958 var divs = [], div = parent.ownerDocument.createElement(this.blockMode), newDiv;
1959 var cssTxt = firstSibling.previousSibling && firstSibling.previousSibling.nodeType == 1? firstSibling.previousSibling.style.cssText : parent.style.cssText;
1960 var isEditNode = parent === this.editor.editNode;
1961 divs.push(div);
1962 firstSibling = parent.replaceChild(div,firstSibling);
1963 domConstruct.place(firstSibling,div,"after");
1964 if(isEditNode){
1965 domStyle.set(div,'direction',domStyle.get(this.editor.editNode,"direction"));
1966 }else{
1967 div.style.cssText = cssTxt;
1968 }
1969 for(var sibling = firstSibling; sibling;){
1970 var tSibling = sibling.nextSibling;
1971 if(this._isInlineOrTextElement(sibling)){
1972 if(this._hasTag(sibling,"BR") && sibling !== lastSibling){
1973 newDiv = parent.ownerDocument.createElement(this.blockMode);
1974 divs.push(newDiv);
1975 sibling = parent.replaceChild(newDiv,sibling);
1976 domConstruct.place(sibling,newDiv,"after");
1977 if(isEditNode){
1978 domStyle.set(newDiv,'direction',domStyle.get(this.editor.editNode,"direction"));
1979 }else{
1980 newDiv.style.cssText = cssTxt;
1981 }
1982 }
1983 if((this._hasTag(sibling,"BR") || sibling.nodeType == 8) && !div.hasChildNodes())
1984 div.innerHTML = this.bogusHtmlContent;
1985 if(this._hasTag(sibling,"BR") && has("ie")){
1986 sibling.parentNode.removeChild(sibling);
1987 }else if(sibling.nodeType != 8){
1988 div.appendChild(sibling);
1989 }else{
1990 sibling.parentNode.removeChild(sibling);
1991 }
1992 if(sibling.nodeType == 3 && sibling.previousSibling && sibling.previousSibling.nodeType == 3){
1993 sibling.previousSibling.nodeValue += sibling.nodeValue;
1994 sibling.parentNode.removeChild(sibling);
1995 }
1996 if(newDiv){
1997 div = newDiv;
1998 newDiv = null;
1999 }
2000 }
2001 if(sibling === lastSibling){
2002 break;
2003 }
2004 sibling = tSibling;
2005 }
2006 return divs;
2007 },
2008
2009 _preFilterNewLines: function(html){
2010 var result = html.split(/(<\/?pre.*>)/i), inPre = false;
2011 for(var i = 0; i < result.length; i++){
2012 if(result[i].search(/<\/?pre/i) < 0 && !inPre){
2013 result[i] = result[i].replace(/\n/g,"").replace(/\t+/g,"\xA0").replace(/^\s+/,"\xA0").replace(/\xA0\xA0+$/,"");
2014 }else if(result[i].search(/<\/?pre/i) >= 0){
2015 inPre = !inPre;
2016 }
2017 }
2018 return result.join("");
2019 },
2020
2021 _refineAlignment: function(dir, align){
2022 // summary:
2023 // Refine the value, which should be used as textAlign style.
2024 // description:
2025 // This method allows to keep textAlign styles only for cases,
2026 // when it is defined explicitly.
2027 if(align.indexOf("left") >= 0 && dir == "rtl"){
2028 align = "left";
2029 }else if(align.indexOf("right") >= 0 && dir == "ltr"){
2030 align = "right";
2031 }else if(align.indexOf("center") >= 0){
2032 align = "center";
2033 }else{
2034 align = "";
2035 }
2036 return align;
2037 },
2038
2039 _refineLIMargins: function(node){
2040 // summary:
2041 // Line items, orientation of which is differ from their parents,
2042 // arn't shown correctly by all browsers.
2043 // Problem is solved by adding corresponding margins.
2044 var liDir = domStyle.get(node,"direction"),
2045 pDir = domStyle.get(node.parentNode,"direction"),
2046 level = 0, tNode = node.parentNode, name, style, offs, val;
2047 if(has("webkit")){
2048 pDir = domStyle.get(this.editor.editNode,"direction");
2049 }
2050 while(tNode !== this.editor.editNode){
2051 if(this._hasTagFrom(tNode,["OL","UL"])){
2052 level++;
2053 }
2054 tNode = tNode.parentNode;
2055 }
2056 domStyle.set(node,"marginRight","");
2057 domStyle.set(node,"marginLeft","");
2058 style = liDir == "rtl"? "marginRight" : "marginLeft";
2059 offs = this._getMargins(level);
2060 val = "" + offs + "px";
2061 if(liDir != pDir){
2062 domStyle.set(node,style,val);
2063 }
2064 },
2065
2066 _getMargins: function(level){
2067 if(level == 0){
2068 return 0;
2069 }
2070 var margin = 35;
2071 if(has("mozilla")){
2072 margin = 45;
2073 }else if(has("ie")){
2074 margin = 25;
2075 }
2076 return margin + (level-1)*40;
2077 },
2078
2079 _recountLIMargins: function(node, addValue){
2080 var liDir = domStyle.get(node,"direction"), pDir = domStyle.get(node.parentNode,"direction");
2081 var margin = liDir == "rtl"? "marginRight" : "marginLeft";
2082 var valPx = domStyle.get(node,margin);
2083 var val = (isNaN(parseInt(valPx))? 0 : parseInt(valPx)) + (addValue? addValue : 0);
2084 if(node.firstChild && node.firstChild.nodeType == 1){
2085 valPx = domStyle.get(node.firstChild,margin);
2086 val += isNaN(parseInt(valPx))? 0 : parseInt(valPx);
2087 domStyle.set(node.firstChild, {marginLeft: "", marginRight: ""});
2088 }
2089 if(liDir != pDir){
2090 val -= this._getMargins(this._getLILevel(node));
2091 }
2092 var parentMargin = this._getListMargins(node);
2093 if(parentMargin){
2094 for(var i = 0; i < parentMargin/40; i++){
2095 var newList = domConstruct.create(this._tag(node.parentNode),null,node,"before");
2096 domConstruct.place(node,newList,"last");
2097 }
2098 }
2099 if(liDir != pDir){
2100 val += this._getMargins(this._getLILevel(node));
2101 }
2102 if(val){
2103 domStyle.set(node,margin, "" + (val) + "px");
2104 }
2105 },
2106
2107 _getLILevel: function(node){
2108 var parent = node.parentNode;
2109 var level = 0;
2110 while(this._hasTagFrom(parent,["UL","OL"])){
2111 level++;
2112 parent = parent.parentNode;
2113 }
2114 return level;
2115 },
2116
2117 _getLIIndent: function(node){
2118 var parent = node.parentNode,
2119 liDir = domStyle.get(node,"direction"), pDir = domStyle.get(parent,"direction"),
2120 margin = liDir === "rtl"? "marginRight" : "marginLeft";
2121 var marginVal = this._getIntStyleValue(node,margin);
2122 var liMargin = liDir === pDir? 0 : this._getMargins(this._getLILevel(node));
2123 return marginVal - liMargin;
2124
2125 },
2126
2127 _getListMargins: function(node){
2128 var parent = node.parentNode;
2129 var margin, val = 0, valPx;
2130 while(this._hasTagFrom(parent,["UL","OL"])){
2131 var pDir = domStyle.get(parent,"direction");
2132 margin = pDir == "rtl"? "marginRight" : "marginLeft";
2133 valPx = domStyle.get(parent,margin);
2134 val += isNaN(parseInt(valPx))? 0 : parseInt(valPx);
2135 parent = parent.parentNode;
2136 }
2137 return val;
2138 },
2139
2140 _tag: function(node){
2141 return node && node.tagName && node.tagName.toUpperCase();
2142 },
2143
2144 _hasTag: function(node,tag){
2145 return (node && tag && node.tagName && node.tagName.toUpperCase() === tag.toUpperCase());
2146 },
2147
2148 _hasStyledTextLineTag: function(node){
2149 return this._hasTagFrom(node, this._lineStyledTextArray);
2150 },
2151
2152 _hasTagFrom: function(node,arr){
2153 return node && arr && node.tagName && array.indexOf(arr, node.tagName.toUpperCase()) >= 0;
2154 },
2155
2156 _getParentFrom: function(node,arr){
2157 if(!node || !arr || !arr.length){
2158 return null;
2159 }
2160 var x = node;
2161 while(x !== this.editor.editNode){
2162 if(this._hasTagFrom(x,arr)){
2163 return x;
2164 }
2165 x = x.parentNode;
2166 }
2167 return null;
2168 },
2169
2170 _isSimpleInfo: function(info){
2171 // summary:
2172 // returns true, if all nodes, for which current action should be executed,
2173 // may be handled in the same time (so, all nodes are in the same group)
2174 return !info || info.groups.length < 2;
2175 },
2176
2177 _isListTypeChanged: function(node, cmd){
2178 // summary:
2179 // Returns true, if command "insertorderedlist" executed for item from unordered list and
2180 // if command "insertunorderedlist" executed for item from ordered list
2181 if(!this._hasTag(node,"LI")){
2182 return false;
2183 }
2184 var parent = node.parentNode;
2185 return (this._hasTag(parent,"UL") && cmd === "insertorderedlist" || this._hasTag(parent,"OL") && cmd === "insertunorderedlist");
2186 },
2187
2188 _getIntStyleValue: function(node, style){
2189 var val = parseInt(domStyle.get(node,style));
2190 return isNaN(val)? 0 : val;
2191 },
2192
2193 _mergeLists: function(){
2194 // summary:
2195 // In some cases (like "formatblocks" for list items) lists of the the same type
2196 // are created as a siblings inside the same parent. These lists should be merged.
2197 var sel = rangeapi.getSelection(this.editor.window);
2198 var reselect = sel && sel.rangeCount > 0;
2199 if(reselect){
2200 var range = sel.getRangeAt(0).cloneRange();
2201 var startContainer = range.startContainer, startOffset = range.startOffset,
2202 endContainer = range.endContainer, endOffset = range.endOffset;
2203 }
2204 var wasMerged = false;
2205 query("ul,ol",this.editor.editNode).forEach(function(x,ind,arr){
2206 if(domAttr.has(x,"tempRole")){
2207 x.parentNode.removeChild(x);
2208 return;
2209 }
2210 var sibling = x.nextSibling;
2211 while(this._hasTag(sibling,this._tag(x))){
2212 while(sibling.firstChild){
2213 domConstruct.place(sibling.firstChild,x,"last");
2214 wasMerged = true;
2215 }
2216 domAttr.set(sibling,"tempRole","true");
2217 sibling = sibling.nextSibling;
2218 }
2219 },this);
2220 if(reselect && wasMerged){
2221 // Restore selection
2222 sel.removeAllRanges();
2223 try{
2224 range.setStart(startContainer, startOffset);
2225 range.setEnd(endContainer, endOffset);
2226 sel.addRange(range);
2227 }catch(e){
2228 }
2229 }
2230 },
2231
2232 _cleanLists: function(){
2233 // summary:
2234 // Removes remaining bogus elements, creating by the method _prepareLists()
2235 if(has("webkit")){
2236 query("table", this.editor.editNode).forEach(function(x,ind,arr){
2237 var sibling = x.nextSibling;
2238 if(this._hasTag(sibling,"UL") && domAttr.get(sibling,"tempRole") === "true"){
2239 sibling.parentNode.removeChild(sibling);
2240 }
2241 },this);
2242 query("li[tempRole]", this.editor.editNode).forEach(function(x,ind,arr){
2243 if(x.parentNode.childNodes.length == 1){
2244 x.parentNode.parentNode.removeChild(x.parentNode);
2245 }else{
2246 x.parentNode.removeChild(x);
2247 }
2248 });
2249 }
2250 var sel = rangeapi.getSelection(this.editor.window);
2251 var reselect = sel && sel.rangeCount > 0;
2252 if(reselect){
2253 var range = sel.getRangeAt(0).cloneRange();
2254 var startContainer = range.startContainer, startOffset = range.startOffset,
2255 endContainer = range.endContainer, endOffset = range.endOffset;
2256 }
2257 var wasMoved = false;
2258 query("span[bogusDir]", this.editor.editNode).forEach(function(x,ind,arr){
2259 var node = x.firstChild, sibling = node;
2260 if(node.nodeType == 1){
2261 while(node){
2262 sibling = node.nextSibling;
2263 domConstruct.place(node,x,"after");
2264 wasMoved = true;
2265 node = sibling;
2266 }
2267 }
2268 x.parentNode.removeChild(x);
2269 },this);
2270 if(reselect && wasMoved){
2271 // Restore selection
2272 sel.removeAllRanges();
2273 try{
2274 range.setStart(startContainer, startOffset);
2275 range.setEnd(endContainer, endOffset);
2276 sel.addRange(range);
2277 }catch(e){
2278 }
2279 }
2280 }
2281 });
2282 _Plugin.registry["bidiSupport"] = _Plugin.registry["bidisupport"] = function(args){
2283 return new BidiSupport({
2284 });
2285 };
2286 return BidiSupport;
2287 });