JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
7967c78b660676e917a4d3a96f299665f11c6923
[ckeditor.git] / _source / plugins / indent / plugin.js
1 /*\r
2 Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.\r
3 For licensing, see LICENSE.html or http://ckeditor.com/license\r
4 */\r
5 \r
6 /**\r
7  * @file Increse and decrease indent commands.\r
8  */\r
9 \r
10 (function()\r
11 {\r
12         var listNodeNames = { ol : 1, ul : 1 },\r
13                 isNotWhitespaces = CKEDITOR.dom.walker.whitespaces( true ),\r
14                 isNotBookmark = CKEDITOR.dom.walker.bookmark( false, true );\r
15 \r
16         function onSelectionChange( evt )\r
17         {\r
18                 var editor = evt.editor,\r
19                         elementPath = evt.data.path,\r
20                         list = elementPath && elementPath.contains( listNodeNames ),\r
21                         firstBlock = elementPath.block || elementPath.blockLimit;\r
22 \r
23                 if ( list )\r
24                                 return this.setState( CKEDITOR.TRISTATE_OFF );\r
25 \r
26                 if ( !this.useIndentClasses && this.name == 'indent' )\r
27                         return this.setState( CKEDITOR.TRISTATE_OFF );\r
28 \r
29                 if ( !firstBlock )\r
30                         return this.setState( CKEDITOR.TRISTATE_DISABLED );\r
31 \r
32                 if ( this.useIndentClasses )\r
33                 {\r
34                         var indentClass = firstBlock.$.className.match( this.classNameRegex ),\r
35                                 indentStep = 0;\r
36                         if ( indentClass )\r
37                         {\r
38                                 indentClass = indentClass[1];\r
39                                 indentStep = this.indentClassMap[ indentClass ];\r
40                         }\r
41                         if ( ( this.name == 'outdent' && !indentStep ) ||\r
42                                         ( this.name == 'indent' && indentStep == editor.config.indentClasses.length ) )\r
43                                 return this.setState( CKEDITOR.TRISTATE_DISABLED );\r
44                         return this.setState( CKEDITOR.TRISTATE_OFF );\r
45                 }\r
46                 else\r
47                 {\r
48                         var indent = parseInt( firstBlock.getStyle( getIndentCssProperty( firstBlock ) ), 10 );\r
49                         if ( isNaN( indent ) )\r
50                                 indent = 0;\r
51                         if ( indent <= 0 )\r
52                                 return this.setState( CKEDITOR.TRISTATE_DISABLED );\r
53                         return this.setState( CKEDITOR.TRISTATE_OFF );\r
54                 }\r
55         }\r
56 \r
57         function indentCommand( editor, name )\r
58         {\r
59                 this.name = name;\r
60                 this.useIndentClasses = editor.config.indentClasses && editor.config.indentClasses.length > 0;\r
61                 if ( this.useIndentClasses )\r
62                 {\r
63                         this.classNameRegex = new RegExp( '(?:^|\\s+)(' + editor.config.indentClasses.join( '|' ) + ')(?=$|\\s)' );\r
64                         this.indentClassMap = {};\r
65                         for ( var i = 0 ; i < editor.config.indentClasses.length ; i++ )\r
66                                 this.indentClassMap[ editor.config.indentClasses[i] ] = i + 1;\r
67                 }\r
68 \r
69                 this.startDisabled = name == 'outdent';\r
70         }\r
71 \r
72         // Returns the CSS property to be used for identing a given element.\r
73         function getIndentCssProperty( element, dir )\r
74         {\r
75                 return ( dir || element.getComputedStyle( 'direction' ) ) == 'ltr' ? 'margin-left' : 'margin-right';\r
76         }\r
77 \r
78         function isListItem( node )\r
79         {\r
80                 return node.type = CKEDITOR.NODE_ELEMENT && node.is( 'li' );\r
81         }\r
82 \r
83         indentCommand.prototype = {\r
84                 exec : function( editor )\r
85                 {\r
86                         var self = this, database = {};\r
87 \r
88                         function indentList( listNode )\r
89                         {\r
90                                 // Our starting and ending points of the range might be inside some blocks under a list item...\r
91                                 // So before playing with the iterator, we need to expand the block to include the list items.\r
92                                 var startContainer = range.startContainer,\r
93                                         endContainer = range.endContainer;\r
94                                 while ( startContainer && !startContainer.getParent().equals( listNode ) )\r
95                                         startContainer = startContainer.getParent();\r
96                                 while ( endContainer && !endContainer.getParent().equals( listNode ) )\r
97                                         endContainer = endContainer.getParent();\r
98 \r
99                                 if ( !startContainer || !endContainer )\r
100                                         return;\r
101 \r
102                                 // Now we can iterate over the individual items on the same tree depth.\r
103                                 var block = startContainer,\r
104                                         itemsToMove = [],\r
105                                         stopFlag = false;\r
106                                 while ( !stopFlag )\r
107                                 {\r
108                                         if ( block.equals( endContainer ) )\r
109                                                 stopFlag = true;\r
110                                         itemsToMove.push( block );\r
111                                         block = block.getNext();\r
112                                 }\r
113                                 if ( itemsToMove.length < 1 )\r
114                                         return;\r
115 \r
116                                 // Do indent or outdent operations on the array model of the list, not the\r
117                                 // list's DOM tree itself. The array model demands that it knows as much as\r
118                                 // possible about the surrounding lists, we need to feed it the further\r
119                                 // ancestor node that is still a list.\r
120                                 var listParents = listNode.getParents( true );\r
121                                 for ( var i = 0 ; i < listParents.length ; i++ )\r
122                                 {\r
123                                         if ( listParents[i].getName && listNodeNames[ listParents[i].getName() ] )\r
124                                         {\r
125                                                 listNode = listParents[i];\r
126                                                 break;\r
127                                         }\r
128                                 }\r
129                                 var indentOffset = self.name == 'indent' ? 1 : -1,\r
130                                         startItem = itemsToMove[0],\r
131                                         lastItem = itemsToMove[ itemsToMove.length - 1 ];\r
132 \r
133                                 // Convert the list DOM tree into a one dimensional array.\r
134                                 var listArray = CKEDITOR.plugins.list.listToArray( listNode, database );\r
135 \r
136                                 // Apply indenting or outdenting on the array.\r
137                                 var baseIndent = listArray[ lastItem.getCustomData( 'listarray_index' ) ].indent;\r
138                                 for ( i = startItem.getCustomData( 'listarray_index' ); i <= lastItem.getCustomData( 'listarray_index' ); i++ )\r
139                                 {\r
140                                         listArray[ i ].indent += indentOffset;\r
141                                         // Make sure the newly created sublist get a brand-new element of the same type. (#5372)\r
142                                         var listRoot = listArray[ i ].parent;\r
143                                         listArray[ i ].parent = new CKEDITOR.dom.element( listRoot.getName(), listRoot.getDocument() );\r
144                                 }\r
145 \r
146                                 for ( i = lastItem.getCustomData( 'listarray_index' ) + 1 ;\r
147                                                 i < listArray.length && listArray[i].indent > baseIndent ; i++ )\r
148                                         listArray[i].indent += indentOffset;\r
149 \r
150                                 // Convert the array back to a DOM forest (yes we might have a few subtrees now).\r
151                                 // And replace the old list with the new forest.\r
152                                 var newList = CKEDITOR.plugins.list.arrayToList( listArray, database, null, editor.config.enterMode, listNode.getDirection() );\r
153 \r
154                                 // Avoid nested <li> after outdent even they're visually same,\r
155                                 // recording them for later refactoring.(#3982)\r
156                                 if ( self.name == 'outdent' )\r
157                                 {\r
158                                         var parentLiElement;\r
159                                         if ( ( parentLiElement = listNode.getParent() ) && parentLiElement.is( 'li' ) )\r
160                                         {\r
161                                                 var children = newList.listNode.getChildren(),\r
162                                                         pendingLis = [],\r
163                                                         count = children.count(),\r
164                                                         child;\r
165 \r
166                                                 for ( i = count - 1 ; i >= 0 ; i-- )\r
167                                                 {\r
168                                                         if ( ( child = children.getItem( i ) ) && child.is && child.is( 'li' )  )\r
169                                                                 pendingLis.push( child );\r
170                                                 }\r
171                                         }\r
172                                 }\r
173 \r
174                                 if ( newList )\r
175                                         newList.listNode.replace( listNode );\r
176 \r
177                                 // Move the nested <li> to be appeared after the parent.\r
178                                 if ( pendingLis && pendingLis.length )\r
179                                 {\r
180                                         for (  i = 0; i < pendingLis.length ; i++ )\r
181                                         {\r
182                                                 var li = pendingLis[ i ],\r
183                                                         followingList = li;\r
184 \r
185                                                 // Nest preceding <ul>/<ol> inside current <li> if any.\r
186                                                 while ( ( followingList = followingList.getNext() ) &&\r
187                                                            followingList.is &&\r
188                                                            followingList.getName() in listNodeNames )\r
189                                                 {\r
190                                                         // IE requires a filler NBSP for nested list inside empty list item,\r
191                                                         // otherwise the list item will be inaccessiable. (#4476)\r
192                                                         if ( CKEDITOR.env.ie && !li.getFirst( function( node ){ return isNotWhitespaces( node ) && isNotBookmark( node ); } ) )\r
193                                                                 li.append( range.document.createText( '\u00a0' ) );\r
194 \r
195                                                         li.append( followingList );\r
196                                                 }\r
197 \r
198                                                 li.insertAfter( parentLiElement );\r
199                                         }\r
200                                 }\r
201                         }\r
202 \r
203                         function indentBlock()\r
204                         {\r
205                                 var iterator = range.createIterator(),\r
206                                         enterMode = editor.config.enterMode;\r
207                                 iterator.enforceRealBlocks = true;\r
208                                 iterator.enlargeBr = enterMode != CKEDITOR.ENTER_BR;\r
209                                 var block;\r
210                                 while ( ( block = iterator.getNextParagraph( enterMode == CKEDITOR.ENTER_P ? 'p' : 'div' ) ) )\r
211                                         indentElement( block );\r
212                         }\r
213 \r
214                         function indentElement( element, dir )\r
215                         {\r
216                                 if ( element.getCustomData( 'indent_processed' ) )\r
217                                         return false;\r
218 \r
219                                 if ( self.useIndentClasses )\r
220                                 {\r
221                                         // Transform current class name to indent step index.\r
222                                         var indentClass = element.$.className.match( self.classNameRegex ),\r
223                                                         indentStep = 0;\r
224                                         if ( indentClass )\r
225                                         {\r
226                                                 indentClass = indentClass[1];\r
227                                                 indentStep = self.indentClassMap[ indentClass ];\r
228                                         }\r
229 \r
230                                         // Operate on indent step index, transform indent step index back to class\r
231                                         // name.\r
232                                         if ( self.name == 'outdent' )\r
233                                                 indentStep--;\r
234                                         else\r
235                                                 indentStep++;\r
236 \r
237                                         if ( indentStep < 0 )\r
238                                                 return false;\r
239 \r
240                                         indentStep = Math.min( indentStep, editor.config.indentClasses.length );\r
241                                         indentStep = Math.max( indentStep, 0 );\r
242                                         element.$.className = CKEDITOR.tools.ltrim( element.$.className.replace( self.classNameRegex, '' ) );\r
243                                         if ( indentStep > 0 )\r
244                                                 element.addClass( editor.config.indentClasses[ indentStep - 1 ] );\r
245                                 }\r
246                                 else\r
247                                 {\r
248                                         var indentCssProperty = getIndentCssProperty( element, dir ),\r
249                                                 currentOffset = parseInt( element.getStyle( indentCssProperty ), 10 );\r
250                                         if ( isNaN( currentOffset ) )\r
251                                                 currentOffset = 0;\r
252                                         var indentOffset = editor.config.indentOffset || 40;\r
253                                         currentOffset += ( self.name == 'indent' ? 1 : -1 ) * indentOffset;\r
254 \r
255                                         if ( currentOffset < 0 )\r
256                                                 return false;\r
257 \r
258                                         currentOffset = Math.max( currentOffset, 0 );\r
259                                         currentOffset = Math.ceil( currentOffset / indentOffset ) * indentOffset;\r
260                                         element.setStyle( indentCssProperty, currentOffset ? currentOffset + ( editor.config.indentUnit || 'px' ) : '' );\r
261                                         if ( element.getAttribute( 'style' ) === '' )\r
262                                                 element.removeAttribute( 'style' );\r
263                                 }\r
264 \r
265                                 CKEDITOR.dom.element.setMarker( database, element, 'indent_processed', 1 );\r
266                                 return true;\r
267                         }\r
268 \r
269                         var selection = editor.getSelection(),\r
270                                 bookmarks = selection.createBookmarks( 1 ),\r
271                                 ranges = selection && selection.getRanges( 1 ),\r
272                                 range;\r
273 \r
274 \r
275                         var iterator = ranges.createIterator();\r
276                         while ( ( range = iterator.getNextRange() ) )\r
277                         {\r
278                                 var rangeRoot = range.getCommonAncestor(),\r
279                                         nearestListBlock = rangeRoot;\r
280 \r
281                                 while ( nearestListBlock && !( nearestListBlock.type == CKEDITOR.NODE_ELEMENT &&\r
282                                         listNodeNames[ nearestListBlock.getName() ] ) )\r
283                                         nearestListBlock = nearestListBlock.getParent();\r
284 \r
285                                 // Avoid having selection enclose the entire list. (#6138)\r
286                                 // [<ul><li>...</li></ul>] =><ul><li>[...]</li></ul>\r
287                                 if ( !nearestListBlock )\r
288                                 {\r
289                                         var selectedNode = range.getEnclosedNode();\r
290                                         if ( selectedNode\r
291                                                 && selectedNode.type == CKEDITOR.NODE_ELEMENT\r
292                                                 && selectedNode.getName() in listNodeNames)\r
293                                         {\r
294                                                 range.setStartAt( selectedNode, CKEDITOR.POSITION_AFTER_START );\r
295                                                 range.setEndAt( selectedNode, CKEDITOR.POSITION_BEFORE_END );\r
296                                                 nearestListBlock = selectedNode;\r
297                                         }\r
298                                 }\r
299 \r
300                                 // Avoid selection anchors under list root.\r
301                                 // <ul>[<li>...</li>]</ul> =>   <ul><li>[...]</li></ul>\r
302                                 if ( nearestListBlock && range.startContainer.type == CKEDITOR.NODE_ELEMENT\r
303                                         && range.startContainer.getName() in listNodeNames )\r
304                                 {\r
305                                         var walker = new CKEDITOR.dom.walker( range );\r
306                                         walker.evaluator = isListItem;\r
307                                         range.startContainer = walker.next();\r
308                                 }\r
309 \r
310                                 if ( nearestListBlock && range.endContainer.type == CKEDITOR.NODE_ELEMENT\r
311                                         && range.endContainer.getName() in listNodeNames )\r
312                                 {\r
313                                         walker = new CKEDITOR.dom.walker( range );\r
314                                         walker.evaluator = isListItem;\r
315                                         range.endContainer = walker.previous();\r
316                                 }\r
317 \r
318                                 if ( nearestListBlock )\r
319                                 {\r
320                                         var firstListItem = nearestListBlock.getFirst( isListItem ),\r
321                                                 hasMultipleItems = !!firstListItem.getNext( isListItem ),\r
322                                                 rangeStart = range.startContainer,\r
323                                                 indentWholeList = firstListItem.equals( rangeStart ) || firstListItem.contains( rangeStart );\r
324 \r
325                                         // Indent the entire list if cursor is inside the first list item. (#3893)\r
326                                         // Only do that for indenting or when using indent classes or when there is something to outdent. (#6141)\r
327                                         if ( !( indentWholeList &&\r
328                                                 ( self.name == 'indent' || self.useIndentClasses || parseInt( nearestListBlock.getStyle( getIndentCssProperty( nearestListBlock ) ), 10 ) ) &&\r
329                                                         indentElement( nearestListBlock, !hasMultipleItems && firstListItem.getDirection() ) ) )\r
330                                                                 indentList( nearestListBlock );\r
331                                 }\r
332                                 else\r
333                                         indentBlock();\r
334                         }\r
335 \r
336                         // Clean up the markers.\r
337                         CKEDITOR.dom.element.clearAllMarkers( database );\r
338 \r
339                         editor.forceNextSelectionCheck();\r
340                         selection.selectBookmarks( bookmarks );\r
341                 }\r
342         };\r
343 \r
344         CKEDITOR.plugins.add( 'indent',\r
345         {\r
346                 init : function( editor )\r
347                 {\r
348                         // Register commands.\r
349                         var indent = editor.addCommand( 'indent', new indentCommand( editor, 'indent' ) ),\r
350                                 outdent = editor.addCommand( 'outdent', new indentCommand( editor, 'outdent' ) );\r
351 \r
352                         // Register the toolbar buttons.\r
353                         editor.ui.addButton( 'Indent',\r
354                                 {\r
355                                         label : editor.lang.indent,\r
356                                         command : 'indent'\r
357                                 });\r
358                         editor.ui.addButton( 'Outdent',\r
359                                 {\r
360                                         label : editor.lang.outdent,\r
361                                         command : 'outdent'\r
362                                 });\r
363 \r
364                         // Register the state changing handlers.\r
365                         editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, indent ) );\r
366                         editor.on( 'selectionChange', CKEDITOR.tools.bind( onSelectionChange, outdent ) );\r
367 \r
368                         // [IE6/7] Raw lists are using margin instead of padding for visual indentation in wysiwyg mode. (#3893)\r
369                         if ( CKEDITOR.env.ie6Compat || CKEDITOR.env.ie7Compat )\r
370                         {\r
371                                 editor.addCss(\r
372                                         "ul,ol" +\r
373                                         "{" +\r
374                                         "       margin-left: 0px;" +\r
375                                         "       padding-left: 40px;" +\r
376                                         "}" );\r
377                         }\r
378 \r
379                         // Register dirChanged listener.\r
380                         editor.on( 'dirChanged', function( e )\r
381                         {\r
382                                 var range = new CKEDITOR.dom.range( editor.document );\r
383                                 range.setStartBefore( e.data.node );\r
384                                 range.setEndAfter( e.data.node );\r
385 \r
386                                 var walker = new CKEDITOR.dom.walker( range ),\r
387                                         node;\r
388 \r
389                                 while ( ( node = walker.next() ) )\r
390                                 {\r
391                                         if ( node.type == CKEDITOR.NODE_ELEMENT )\r
392                                         {\r
393                                                 // A child with the defined dir is to be ignored.\r
394                                                 if ( !node.equals( e.data.node ) && node.getDirection() )\r
395                                                 {\r
396                                                         range.setStartAfter( node );\r
397                                                         walker = new CKEDITOR.dom.walker( range );\r
398                                                         continue;\r
399                                                 }\r
400 \r
401                                                 // Switch alignment classes.\r
402                                                 var classes = editor.config.indentClasses;\r
403                                                 if ( classes )\r
404                                                 {\r
405                                                         var suffix = ( e.data.dir == 'ltr' ) ? [ '_rtl', '' ] : [ '', '_rtl' ];\r
406                                                         for ( var i = 0; i < classes.length; i++ )\r
407                                                         {\r
408                                                                 if ( node.hasClass( classes[ i ] + suffix[ 0 ] ) )\r
409                                                                 {\r
410                                                                         node.removeClass( classes[ i ] + suffix[ 0 ] );\r
411                                                                         node.addClass( classes[ i ] + suffix[ 1 ] );\r
412                                                                 }\r
413                                                         }\r
414                                                 }\r
415 \r
416                                                 // Switch the margins.\r
417                                                 var marginLeft = node.getStyle( 'margin-right' ),\r
418                                                         marginRight = node.getStyle( 'margin-left' );\r
419 \r
420                                                 marginLeft ? node.setStyle( 'margin-left', marginLeft ) : node.removeStyle( 'margin-left' );\r
421                                                 marginRight ? node.setStyle( 'margin-right', marginRight ) : node.removeStyle( 'margin-right' );\r
422                                         }\r
423                                 }\r
424                         });\r
425                 },\r
426 \r
427                 requires : [ 'domiterator', 'list' ]\r
428         } );\r
429 })();\r
430 \r
431 /**\r
432  * Size of each indentation step\r
433  * @name CKEDITOR.config.indentOffset\r
434  * @type Number\r
435  * @default 40\r
436  * @example\r
437  * config.indentOffset = 4;\r
438  */\r
439 \r
440  /**\r
441  * Unit for the indentation style\r
442  * @name CKEDITOR.config.indentUnit\r
443  * @type String\r
444  * @default 'px'\r
445  * @example\r
446  * config.indentUnit = 'em';\r
447  */\r
448 \r
449  /**\r
450  * List of classes to use for indenting the contents. If it's null, no classes will be used\r
451  * and instead the {@link #indentUnit} and {@link #indentOffset} properties will be used.\r
452  * @name CKEDITOR.config.indentClasses\r
453  * @type Array\r
454  * @default null\r
455  * @example\r
456  * // Use the classes 'Indent1', 'Indent2', 'Indent3'\r
457  * config.indentClasses = ['Indent1', 'Indent2', 'Indent3'];\r
458  */\r