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