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