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 DOM iterator, which iterates over list items, lines and paragraphs.
  8  */
  9 
 10 CKEDITOR.plugins.add( 'domiterator' );
 11 
 12 (function()
 13 {
 14 	/**
 15 	 * @name CKEDITOR.dom.iterator
 16 	 */
 17 	function iterator( range )
 18 	{
 19 		if ( arguments.length < 1 )
 20 			return;
 21 
 22 		this.range = range;
 23 		this.forceBrBreak = 0;
 24 
 25 		// Whether include <br>s into the enlarged range.(#3730).
 26 		this.enlargeBr = 1;
 27 		this.enforceRealBlocks = 0;
 28 
 29 		this._ || ( this._ = {} );
 30 	}
 31 
 32 	var beginWhitespaceRegex = /^[\r\n\t ]+$/,
 33 		// Ignore bookmark nodes.(#3783)
 34 		bookmarkGuard = CKEDITOR.dom.walker.bookmark( false, true ),
 35 		whitespacesGuard = CKEDITOR.dom.walker.whitespaces( true ),
 36 		skipGuard = function( node ) { return bookmarkGuard( node ) && whitespacesGuard( node ); };
 37 
 38 	// Get a reference for the next element, bookmark nodes are skipped.
 39 	function getNextSourceNode( node, startFromSibling, lastNode )
 40 	{
 41 		var next = node.getNextSourceNode( startFromSibling, null, lastNode );
 42 		while ( !bookmarkGuard( next ) )
 43 			next = next.getNextSourceNode( startFromSibling, null, lastNode );
 44 		return next;
 45 	}
 46 
 47 	iterator.prototype = {
 48 		getNextParagraph : function( blockTag )
 49 		{
 50 			// The block element to be returned.
 51 			var block;
 52 
 53 			// The range object used to identify the paragraph contents.
 54 			var range;
 55 
 56 			// Indicats that the current element in the loop is the last one.
 57 			var isLast;
 58 
 59 			// Indicate at least one of the range boundaries is inside a preformat block.
 60 			var touchPre;
 61 
 62 			// Instructs to cleanup remaining BRs.
 63 			var removePreviousBr, removeLastBr;
 64 
 65 			// This is the first iteration. Let's initialize it.
 66 			if ( !this._.started )
 67 			{
 68 				range = this.range.clone();
 69 
 70 				// Shrink the range to exclude harmful "noises" (#4087, #4450, #5435).
 71 				range.shrink( CKEDITOR.NODE_ELEMENT, true );
 72 
 73 				touchPre = range.endContainer.hasAscendant( 'pre', true )
 74 					|| range.startContainer.hasAscendant( 'pre', true );
 75 
 76 				range.enlarge( this.forceBrBreak && !touchPre || !this.enlargeBr ?
 77 							   CKEDITOR.ENLARGE_LIST_ITEM_CONTENTS : CKEDITOR.ENLARGE_BLOCK_CONTENTS );
 78 
 79 				if ( !range.collapsed )
 80 				{
 81 					var walker = new CKEDITOR.dom.walker( range.clone() ),
 82 						ignoreBookmarkTextEvaluator = CKEDITOR.dom.walker.bookmark( true, true );
 83 					// Avoid anchor inside bookmark inner text.
 84 					walker.evaluator = ignoreBookmarkTextEvaluator;
 85 					this._.nextNode = walker.next();
 86 					// TODO: It's better to have walker.reset() used here.
 87 					walker = new CKEDITOR.dom.walker( range.clone() );
 88 					walker.evaluator = ignoreBookmarkTextEvaluator;
 89 					var lastNode = walker.previous();
 90 					this._.lastNode = lastNode.getNextSourceNode( true );
 91 
 92 					// We may have an empty text node at the end of block due to [3770].
 93 					// If that node is the lastNode, it would cause our logic to leak to the
 94 					// next block.(#3887)
 95 					if ( this._.lastNode &&
 96 							this._.lastNode.type == CKEDITOR.NODE_TEXT &&
 97 							!CKEDITOR.tools.trim( this._.lastNode.getText() ) &&
 98 							this._.lastNode.getParent().isBlockBoundary() )
 99 					{
100 						var testRange = new CKEDITOR.dom.range( range.document );
101 						testRange.moveToPosition( this._.lastNode, CKEDITOR.POSITION_AFTER_END );
102 						if ( testRange.checkEndOfBlock() )
103 						{
104 							var path = new CKEDITOR.dom.elementPath( testRange.endContainer );
105 							var lastBlock = path.block || path.blockLimit;
106 							this._.lastNode = lastBlock.getNextSourceNode( true );
107 						}
108 					}
109 
110 					// Probably the document end is reached, we need a marker node.
111 					if ( !this._.lastNode )
112 					{
113 						this._.lastNode = this._.docEndMarker = range.document.createText( '' );
114 						this._.lastNode.insertAfter( lastNode );
115 					}
116 
117 					// Let's reuse this variable.
118 					range = null;
119 				}
120 
121 				this._.started = 1;
122 			}
123 
124 			var currentNode = this._.nextNode;
125 			lastNode = this._.lastNode;
126 
127 			this._.nextNode = null;
128 			while ( currentNode )
129 			{
130 				// closeRange indicates that a paragraph boundary has been found,
131 				// so the range can be closed.
132 				var closeRange = 0,
133 					parentPre = currentNode.hasAscendant( 'pre' );
134 
135 				// includeNode indicates that the current node is good to be part
136 				// of the range. By default, any non-element node is ok for it.
137 				var includeNode = ( currentNode.type != CKEDITOR.NODE_ELEMENT ),
138 					continueFromSibling = 0;
139 
140 				// If it is an element node, let's check if it can be part of the
141 				// range.
142 				if ( !includeNode )
143 				{
144 					var nodeName = currentNode.getName();
145 
146 					if ( currentNode.isBlockBoundary( this.forceBrBreak &&
147 							!parentPre && { br : 1 } ) )
148 					{
149 						// <br> boundaries must be part of the range. It will
150 						// happen only if ForceBrBreak.
151 						if ( nodeName == 'br' )
152 							includeNode = 1;
153 						else if ( !range && !currentNode.getChildCount() && nodeName != 'hr' )
154 						{
155 							// If we have found an empty block, and haven't started
156 							// the range yet, it means we must return this block.
157 							block = currentNode;
158 							isLast = currentNode.equals( lastNode );
159 							break;
160 						}
161 
162 						// The range must finish right before the boundary,
163 						// including possibly skipped empty spaces. (#1603)
164 						if ( range )
165 						{
166 							range.setEndAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
167 
168 							// The found boundary must be set as the next one at this
169 							// point. (#1717)
170 							if ( nodeName != 'br' )
171 								this._.nextNode = currentNode;
172 						}
173 
174 						closeRange = 1;
175 					}
176 					else
177 					{
178 						// If we have child nodes, let's check them.
179 						if ( currentNode.getFirst() )
180 						{
181 							// If we don't have a range yet, let's start it.
182 							if ( !range )
183 							{
184 								range = new CKEDITOR.dom.range( this.range.document );
185 								range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
186 							}
187 
188 							currentNode = currentNode.getFirst();
189 							continue;
190 						}
191 						includeNode = 1;
192 					}
193 				}
194 				else if ( currentNode.type == CKEDITOR.NODE_TEXT )
195 				{
196 					// Ignore normal whitespaces (i.e. not including   or
197 					// other unicode whitespaces) before/after a block node.
198 					if ( beginWhitespaceRegex.test( currentNode.getText() ) )
199 						includeNode = 0;
200 				}
201 
202 				// The current node is good to be part of the range and we are
203 				// starting a new range, initialize it first.
204 				if ( includeNode && !range )
205 				{
206 					range = new CKEDITOR.dom.range( this.range.document );
207 					range.setStartAt( currentNode, CKEDITOR.POSITION_BEFORE_START );
208 				}
209 
210 				// The last node has been found.
211 				isLast = ( ( !closeRange || includeNode ) && currentNode.equals( lastNode ) );
212 
213 				// If we are in an element boundary, let's check if it is time
214 				// to close the range, otherwise we include the parent within it.
215 				if ( range && !closeRange )
216 				{
217 					while ( !currentNode.getNext( skipGuard ) && !isLast )
218 					{
219 						var parentNode = currentNode.getParent();
220 
221 						if ( parentNode.isBlockBoundary( this.forceBrBreak
222 								&& !parentPre && { br : 1 } ) )
223 						{
224 							closeRange = 1;
225 							includeNode = 0;
226 							isLast = isLast || ( parentNode.equals( lastNode) );
227 							// Make sure range includes bookmarks at the end of the block. (#7359)
228 							range.setEndAt( parentNode, CKEDITOR.POSITION_BEFORE_END );
229 							break;
230 						}
231 
232 						currentNode = parentNode;
233 						includeNode = 1;
234 						isLast = ( currentNode.equals( lastNode ) );
235 						continueFromSibling = 1;
236 					}
237 				}
238 
239 				// Now finally include the node.
240 				if ( includeNode )
241 					range.setEndAt( currentNode, CKEDITOR.POSITION_AFTER_END );
242 
243 				currentNode = getNextSourceNode ( currentNode, continueFromSibling, lastNode );
244 				isLast = !currentNode;
245 
246 				// We have found a block boundary. Let's close the range and move out of the
247 				// loop.
248 				if ( isLast || ( closeRange && range ) )
249 						break;
250 			}
251 
252 			// Now, based on the processed range, look for (or create) the block to be returned.
253 			if ( !block )
254 			{
255 				// If no range has been found, this is the end.
256 				if ( !range )
257 				{
258 					this._.docEndMarker && this._.docEndMarker.remove();
259 					this._.nextNode = null;
260 					return null;
261 				}
262 
263 				var startPath = new CKEDITOR.dom.elementPath( range.startContainer );
264 				var startBlockLimit = startPath.blockLimit,
265 					checkLimits = { div : 1, th : 1, td : 1 };
266 				block = startPath.block;
267 
268 				if ( !block
269 						&& !this.enforceRealBlocks
270 						&& checkLimits[ startBlockLimit.getName() ]
271 						&& range.checkStartOfBlock()
272 						&& range.checkEndOfBlock() )
273 					block = startBlockLimit;
274 				else if ( !block || ( this.enforceRealBlocks && block.getName() == 'li' ) )
275 				{
276 					// Create the fixed block.
277 					block = this.range.document.createElement( blockTag || 'p' );
278 
279 						// Move the contents of the temporary range to the fixed block.
280 						range.extractContents().appendTo( block );
281 						block.trim();
282 
283 						// Insert the fixed block into the DOM.
284 						range.insertNode( block );
285 
286 						removePreviousBr = removeLastBr = true;
287 				}
288 				else if ( block.getName() != 'li' )
289 				{
290 					// If the range doesn't includes the entire contents of the
291 					// block, we must split it, isolating the range in a dedicated
292 					// block.
293 					if ( !range.checkStartOfBlock() || !range.checkEndOfBlock() )
294 					{
295 						// The resulting block will be a clone of the current one.
296 						block = block.clone( false );
297 
298 						// Extract the range contents, moving it to the new block.
299 						range.extractContents().appendTo( block );
300 						block.trim();
301 
302 						// Split the block. At this point, the range will be in the
303 						// right position for our intents.
304 						var splitInfo = range.splitBlock();
305 
306 						removePreviousBr = !splitInfo.wasStartOfBlock;
307 						removeLastBr = !splitInfo.wasEndOfBlock;
308 
309 						// Insert the new block into the DOM.
310 						range.insertNode( block );
311 					}
312 				}
313 				else if ( !isLast )
314 				{
315 					// LIs are returned as is, with all their children (due to the
316 					// nested lists). But, the next node is the node right after
317 					// the current range, which could be an <li> child (nested
318 					// lists) or the next sibling <li>.
319 
320 					this._.nextNode = ( block.equals( lastNode ) ? null : getNextSourceNode( range.getBoundaryNodes().endNode, 1, lastNode ) );
321 				}
322 			}
323 
324 			if ( removePreviousBr )
325 			{
326 				var previousSibling = block.getPrevious();
327 				if ( previousSibling && previousSibling.type == CKEDITOR.NODE_ELEMENT )
328 				{
329 					if ( previousSibling.getName() == 'br' )
330 						previousSibling.remove();
331 					else if ( previousSibling.getLast() && previousSibling.getLast().$.nodeName.toLowerCase() == 'br' )
332 						previousSibling.getLast().remove();
333 				}
334 			}
335 
336 			if ( removeLastBr )
337 			{
338 				var lastChild = block.getLast();
339 				if ( lastChild && lastChild.type == CKEDITOR.NODE_ELEMENT && lastChild.getName() == 'br' )
340 				{
341 					// Take care not to remove the block expanding <br> in non-IE browsers.
342 					if ( CKEDITOR.env.ie
343 						 || lastChild.getPrevious( bookmarkGuard )
344 						 || lastChild.getNext( bookmarkGuard ) )
345 						lastChild.remove();
346 				}
347 			}
348 
349 			// Get a reference for the next element. This is important because the
350 			// above block can be removed or changed, so we can rely on it for the
351 			// next interation.
352 			if ( !this._.nextNode )
353 			{
354 				this._.nextNode = ( isLast || block.equals( lastNode ) || !lastNode ) ? null :
355 					getNextSourceNode( block, 1, lastNode );
356 			}
357 
358 			return block;
359 		}
360 	};
361 
362 	CKEDITOR.dom.range.prototype.createIterator = function()
363 	{
364 		return new iterator( this );
365 	};
366 })();
367