JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
d31b0508d787e00a331a59cf5c6e9f0214da45a1
[ckeditor.git] / _source / core / htmlparser / fragment.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  * A lightweight representation of an HTML DOM structure.\r
8  * @constructor\r
9  * @example\r
10  */\r
11 CKEDITOR.htmlParser.fragment = function()\r
12 {\r
13         /**\r
14          * The nodes contained in the root of this fragment.\r
15          * @type Array\r
16          * @example\r
17          * var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<b>Sample</b> Text' );\r
18          * alert( fragment.children.length );  "2"\r
19          */\r
20         this.children = [];\r
21 \r
22         /**\r
23          * Get the fragment parent. Should always be null.\r
24          * @type Object\r
25          * @default null\r
26          * @example\r
27          */\r
28         this.parent = null;\r
29 \r
30         /** @private */\r
31         this._ =\r
32         {\r
33                 isBlockLike : true,\r
34                 hasInlineStarted : false\r
35         };\r
36 };\r
37 \r
38 (function()\r
39 {\r
40         // Elements which the end tag is marked as optional in the HTML 4.01 DTD\r
41         // (expect empty elements).\r
42         var optionalClose = {colgroup:1,dd:1,dt:1,li:1,option:1,p:1,td:1,tfoot:1,th:1,thead:1,tr:1};\r
43 \r
44         // Block-level elements whose internal structure should be respected during\r
45         // parser fixing.\r
46         var nonBreakingBlocks = CKEDITOR.tools.extend(\r
47                         {table:1,ul:1,ol:1,dl:1},\r
48                         CKEDITOR.dtd.table, CKEDITOR.dtd.ul, CKEDITOR.dtd.ol, CKEDITOR.dtd.dl ),\r
49                 listBlocks = CKEDITOR.dtd.$list, listItems = CKEDITOR.dtd.$listItem;\r
50 \r
51         /**\r
52          * Creates a {@link CKEDITOR.htmlParser.fragment} from an HTML string.\r
53          * @param {String} fragmentHtml The HTML to be parsed, filling the fragment.\r
54          * @param {Number} [fixForBody=false] Wrap body with specified element if needed.\r
55          * @returns CKEDITOR.htmlParser.fragment The fragment created.\r
56          * @example\r
57          * var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '<b>Sample</b> Text' );\r
58          * alert( fragment.children[0].name );  "b"\r
59          * alert( fragment.children[1].value );  " Text"\r
60          */\r
61         CKEDITOR.htmlParser.fragment.fromHtml = function( fragmentHtml, fixForBody )\r
62         {\r
63                 var parser = new CKEDITOR.htmlParser(),\r
64                         html = [],\r
65                         fragment = new CKEDITOR.htmlParser.fragment(),\r
66                         pendingInline = [],\r
67                         pendingBRs = [],\r
68                         currentNode = fragment,\r
69                     // Indicate we're inside a <pre> element, spaces should be touched differently.\r
70                         inPre = false,\r
71                         returnPoint;\r
72 \r
73                 function checkPending( newTagName )\r
74                 {\r
75                         var pendingBRsSent;\r
76 \r
77                         if ( pendingInline.length > 0 )\r
78                         {\r
79                                 for ( var i = 0 ; i < pendingInline.length ; i++ )\r
80                                 {\r
81                                         var pendingElement = pendingInline[ i ],\r
82                                                 pendingName = pendingElement.name,\r
83                                                 pendingDtd = CKEDITOR.dtd[ pendingName ],\r
84                                                 currentDtd = currentNode.name && CKEDITOR.dtd[ currentNode.name ];\r
85 \r
86                                         if ( ( !currentDtd || currentDtd[ pendingName ] ) && ( !newTagName || !pendingDtd || pendingDtd[ newTagName ] || !CKEDITOR.dtd[ newTagName ] ) )\r
87                                         {\r
88                                                 if ( !pendingBRsSent )\r
89                                                 {\r
90                                                         sendPendingBRs();\r
91                                                         pendingBRsSent = 1;\r
92                                                 }\r
93 \r
94                                                 // Get a clone for the pending element.\r
95                                                 pendingElement = pendingElement.clone();\r
96 \r
97                                                 // Add it to the current node and make it the current,\r
98                                                 // so the new element will be added inside of it.\r
99                                                 pendingElement.parent = currentNode;\r
100                                                 currentNode = pendingElement;\r
101 \r
102                                                 // Remove the pending element (back the index by one\r
103                                                 // to properly process the next entry).\r
104                                                 pendingInline.splice( i, 1 );\r
105                                                 i--;\r
106                                         }\r
107                                 }\r
108                         }\r
109                 }\r
110 \r
111                 function sendPendingBRs( brsToIgnore )\r
112                 {\r
113                         while ( pendingBRs.length - ( brsToIgnore || 0 ) > 0 )\r
114                                 currentNode.add( pendingBRs.shift() );\r
115                 }\r
116 \r
117                 function addElement( element, target, enforceCurrent )\r
118                 {\r
119                         target = target || currentNode || fragment;\r
120 \r
121                         // If the target is the fragment and this element can't go inside\r
122                         // body (if fixForBody).\r
123                         if ( fixForBody && !target.type )\r
124                         {\r
125                                 var elementName, realElementName;\r
126                                 if ( element.attributes\r
127                                          && ( realElementName =\r
128                                                   element.attributes[ '_cke_real_element_type' ] ) )\r
129                                         elementName = realElementName;\r
130                                 else\r
131                                         elementName =  element.name;\r
132                                 if ( elementName\r
133                                                 && !( elementName in CKEDITOR.dtd.$body )\r
134                                                 && !( elementName in CKEDITOR.dtd.$nonBodyContent )  )\r
135                                 {\r
136                                         var savedCurrent = currentNode;\r
137 \r
138                                         // Create a <p> in the fragment.\r
139                                         currentNode = target;\r
140                                         parser.onTagOpen( fixForBody, {} );\r
141 \r
142                                         // The new target now is the <p>.\r
143                                         target = currentNode;\r
144 \r
145                                         if ( enforceCurrent )\r
146                                                 currentNode = savedCurrent;\r
147                                 }\r
148                         }\r
149 \r
150                         // Rtrim empty spaces on block end boundary. (#3585)\r
151                         if ( element._.isBlockLike\r
152                                  && element.name != 'pre' )\r
153                         {\r
154 \r
155                                 var length = element.children.length,\r
156                                         lastChild = element.children[ length - 1 ],\r
157                                         text;\r
158                                 if ( lastChild && lastChild.type == CKEDITOR.NODE_TEXT )\r
159                                 {\r
160                                         if ( !( text = CKEDITOR.tools.rtrim( lastChild.value ) ) )\r
161                                                 element.children.length = length -1;\r
162                                         else\r
163                                                 lastChild.value = text;\r
164                                 }\r
165                         }\r
166 \r
167                         target.add( element );\r
168 \r
169                         if ( element.returnPoint )\r
170                         {\r
171                                 currentNode = element.returnPoint;\r
172                                 delete element.returnPoint;\r
173                         }\r
174                 }\r
175 \r
176                 parser.onTagOpen = function( tagName, attributes, selfClosing )\r
177                 {\r
178                         var element = new CKEDITOR.htmlParser.element( tagName, attributes );\r
179 \r
180                         // "isEmpty" will be always "false" for unknown elements, so we\r
181                         // must force it if the parser has identified it as a selfClosing tag.\r
182                         if ( element.isUnknown && selfClosing )\r
183                                 element.isEmpty = true;\r
184 \r
185                         // This is a tag to be removed if empty, so do not add it immediately.\r
186                         if ( CKEDITOR.dtd.$removeEmpty[ tagName ] )\r
187                         {\r
188                                 pendingInline.push( element );\r
189                                 return;\r
190                         }\r
191                         else if ( tagName == 'pre' )\r
192                                 inPre = true;\r
193                         else if ( tagName == 'br' && inPre )\r
194                         {\r
195                                 currentNode.add( new CKEDITOR.htmlParser.text( '\n' ) );\r
196                                 return;\r
197                         }\r
198 \r
199                         if ( tagName == 'br' )\r
200                         {\r
201                                 pendingBRs.push( element );\r
202                                 return;\r
203                         }\r
204 \r
205                         var currentName = currentNode.name;\r
206 \r
207                         var currentDtd = currentName\r
208                                 && ( CKEDITOR.dtd[ currentName ]\r
209                                         || ( currentNode._.isBlockLike ? CKEDITOR.dtd.div : CKEDITOR.dtd.span ) );\r
210 \r
211                         // If the element cannot be child of the current element.\r
212                         if ( currentDtd   // Fragment could receive any elements.\r
213                                  && !element.isUnknown && !currentNode.isUnknown && !currentDtd[ tagName ] )\r
214                         {\r
215 \r
216                                 var reApply = false,\r
217                                         addPoint;   // New position to start adding nodes.\r
218 \r
219                                 // Fixing malformed nested lists by moving it into a previous list item. (#3828)\r
220                                 if ( tagName in listBlocks\r
221                                         && currentName in listBlocks )\r
222                                 {\r
223                                         var children = currentNode.children,\r
224                                                 lastChild = children[ children.length - 1 ];\r
225 \r
226                                         // Establish the list item if it's not existed.\r
227                                         if ( !( lastChild && lastChild.name in listItems ) )\r
228                                                 addElement( ( lastChild = new CKEDITOR.htmlParser.element( 'li' ) ), currentNode );\r
229 \r
230                                         returnPoint = currentNode, addPoint = lastChild;\r
231                                 }\r
232                                 // If the element name is the same as the current element name,\r
233                                 // then just close the current one and append the new one to the\r
234                                 // parent. This situation usually happens with <p>, <li>, <dt> and\r
235                                 // <dd>, specially in IE. Do not enter in this if block in this case.\r
236                                 else if ( tagName == currentName )\r
237                                 {\r
238                                         addElement( currentNode, currentNode.parent );\r
239                                 }\r
240                                 else\r
241                                 {\r
242                                         if ( nonBreakingBlocks[ currentName ] )\r
243                                         {\r
244                                                 if ( !returnPoint )\r
245                                                         returnPoint = currentNode;\r
246                                         }\r
247                                         else\r
248                                         {\r
249                                                 addElement( currentNode, currentNode.parent, true );\r
250 \r
251                                                 if ( !optionalClose[ currentName ] )\r
252                                                 {\r
253                                                         // The current element is an inline element, which\r
254                                                         // cannot hold the new one. Put it in the pending list,\r
255                                                         // and try adding the new one after it.\r
256                                                         pendingInline.unshift( currentNode );\r
257                                                 }\r
258                                         }\r
259 \r
260                                         reApply = true;\r
261                                 }\r
262 \r
263                                 if ( addPoint )\r
264                                         currentNode = addPoint;\r
265                                 // Try adding it to the return point, or the parent element.\r
266                                 else\r
267                                         currentNode = currentNode.returnPoint || currentNode.parent;\r
268 \r
269                                 if ( reApply )\r
270                                 {\r
271                                         parser.onTagOpen.apply( this, arguments );\r
272                                         return;\r
273                                 }\r
274                         }\r
275 \r
276                         checkPending( tagName );\r
277                         sendPendingBRs();\r
278 \r
279                         element.parent = currentNode;\r
280                         element.returnPoint = returnPoint;\r
281                         returnPoint = 0;\r
282 \r
283                         if ( element.isEmpty )\r
284                                 addElement( element );\r
285                         else\r
286                                 currentNode = element;\r
287                 };\r
288 \r
289                 parser.onTagClose = function( tagName )\r
290                 {\r
291                         // Check if there is any pending tag to be closed.\r
292                         for ( var i = pendingInline.length - 1 ; i >= 0 ; i-- )\r
293                         {\r
294                                 // If found, just remove it from the list.\r
295                                 if ( tagName == pendingInline[ i ].name )\r
296                                 {\r
297                                         pendingInline.splice( i, 1 );\r
298                                         return;\r
299                                 }\r
300                         }\r
301 \r
302                         var pendingAdd = [],\r
303                                 newPendingInline = [],\r
304                                 candidate = currentNode;\r
305 \r
306                         while ( candidate.type && candidate.name != tagName )\r
307                         {\r
308                                 // If this is an inline element, add it to the pending list, if we're\r
309                                 // really closing one of the parents element later, they will continue\r
310                                 // after it.\r
311                                 if ( !candidate._.isBlockLike )\r
312                                         newPendingInline.unshift( candidate );\r
313 \r
314                                 // This node should be added to it's parent at this point. But,\r
315                                 // it should happen only if the closing tag is really closing\r
316                                 // one of the nodes. So, for now, we just cache it.\r
317                                 pendingAdd.push( candidate );\r
318 \r
319                                 candidate = candidate.parent;\r
320                         }\r
321 \r
322                         if ( candidate.type )\r
323                         {\r
324                                 // Add all elements that have been found in the above loop.\r
325                                 for ( i = 0 ; i < pendingAdd.length ; i++ )\r
326                                 {\r
327                                         var node = pendingAdd[ i ];\r
328                                         addElement( node, node.parent );\r
329                                 }\r
330 \r
331                                 currentNode = candidate;\r
332 \r
333                                 if ( currentNode.name == 'pre' )\r
334                                         inPre = false;\r
335 \r
336                                 if ( candidate._.isBlockLike )\r
337                                         sendPendingBRs();\r
338 \r
339                                 addElement( candidate, candidate.parent );\r
340 \r
341                                 // The parent should start receiving new nodes now, except if\r
342                                 // addElement changed the currentNode.\r
343                                 if ( candidate == currentNode )\r
344                                         currentNode = currentNode.parent;\r
345 \r
346                                 pendingInline = pendingInline.concat( newPendingInline );\r
347                         }\r
348 \r
349                         if ( tagName == 'body' )\r
350                                 fixForBody = false;\r
351                 };\r
352 \r
353                 parser.onText = function( text )\r
354                 {\r
355                         // Trim empty spaces at beginning of element contents except <pre>.\r
356                         if ( !currentNode._.hasInlineStarted && !inPre )\r
357                         {\r
358                                 text = CKEDITOR.tools.ltrim( text );\r
359 \r
360                                 if ( text.length === 0 )\r
361                                         return;\r
362                         }\r
363 \r
364                         sendPendingBRs();\r
365                         checkPending();\r
366 \r
367                         if ( fixForBody\r
368                                  && ( !currentNode.type || currentNode.name == 'body' )\r
369                                  && CKEDITOR.tools.trim( text ) )\r
370                         {\r
371                                 this.onTagOpen( fixForBody, {} );\r
372                         }\r
373 \r
374                         // Shrinking consequential spaces into one single for all elements\r
375                         // text contents.\r
376                         if ( !inPre )\r
377                                 text = text.replace( /[\t\r\n ]{2,}|[\t\r\n]/g, ' ' );\r
378 \r
379                         currentNode.add( new CKEDITOR.htmlParser.text( text ) );\r
380                 };\r
381 \r
382                 parser.onCDATA = function( cdata )\r
383                 {\r
384                         currentNode.add( new CKEDITOR.htmlParser.cdata( cdata ) );\r
385                 };\r
386 \r
387                 parser.onComment = function( comment )\r
388                 {\r
389                         currentNode.add( new CKEDITOR.htmlParser.comment( comment ) );\r
390                 };\r
391 \r
392                 // Parse it.\r
393                 parser.parse( fragmentHtml );\r
394 \r
395                 // Send all pending BRs except one, which we consider a unwanted bogus. (#5293)\r
396                 sendPendingBRs( !CKEDITOR.env.ie && 1 );\r
397 \r
398                 // Close all pending nodes.\r
399                 while ( currentNode.type )\r
400                 {\r
401                         var parent = currentNode.parent,\r
402                                 node = currentNode;\r
403 \r
404                         if ( fixForBody\r
405                                  && ( !parent.type || parent.name == 'body' )\r
406                                  && !CKEDITOR.dtd.$body[ node.name ] )\r
407                         {\r
408                                 currentNode = parent;\r
409                                 parser.onTagOpen( fixForBody, {} );\r
410                                 parent = currentNode;\r
411                         }\r
412 \r
413                         parent.add( node );\r
414                         currentNode = parent;\r
415                 }\r
416 \r
417                 return fragment;\r
418         };\r
419 \r
420         CKEDITOR.htmlParser.fragment.prototype =\r
421         {\r
422                 /**\r
423                  * Adds a node to this fragment.\r
424                  * @param {Object} node The node to be added. It can be any of of the\r
425                  *              following types: {@link CKEDITOR.htmlParser.element},\r
426                  *              {@link CKEDITOR.htmlParser.text} and\r
427                  *              {@link CKEDITOR.htmlParser.comment}.\r
428                  * @example\r
429                  */\r
430                 add : function( node )\r
431                 {\r
432                         var len = this.children.length,\r
433                                 previous = len > 0 && this.children[ len - 1 ] || null;\r
434 \r
435                         if ( previous )\r
436                         {\r
437                                 // If the block to be appended is following text, trim spaces at\r
438                                 // the right of it.\r
439                                 if ( node._.isBlockLike && previous.type == CKEDITOR.NODE_TEXT )\r
440                                 {\r
441                                         previous.value = CKEDITOR.tools.rtrim( previous.value );\r
442 \r
443                                         // If we have completely cleared the previous node.\r
444                                         if ( previous.value.length === 0 )\r
445                                         {\r
446                                                 // Remove it from the list and add the node again.\r
447                                                 this.children.pop();\r
448                                                 this.add( node );\r
449                                                 return;\r
450                                         }\r
451                                 }\r
452 \r
453                                 previous.next = node;\r
454                         }\r
455 \r
456                         node.previous = previous;\r
457                         node.parent = this;\r
458 \r
459                         this.children.push( node );\r
460 \r
461                         this._.hasInlineStarted = node.type == CKEDITOR.NODE_TEXT || ( node.type == CKEDITOR.NODE_ELEMENT && !node._.isBlockLike );\r
462                 },\r
463 \r
464                 /**\r
465                  * Writes the fragment HTML to a CKEDITOR.htmlWriter.\r
466                  * @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.\r
467                  * @example\r
468                  * var writer = new CKEDITOR.htmlWriter();\r
469                  * var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '&lt;P&gt;&lt;B&gt;Example' );\r
470                  * fragment.writeHtml( writer )\r
471                  * alert( writer.getHtml() );  "&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;&lt;/p&gt;"\r
472                  */\r
473                 writeHtml : function( writer, filter )\r
474                 {\r
475                         var isChildrenFiltered;\r
476                         this.filterChildren = function()\r
477                         {\r
478                                 var writer = new CKEDITOR.htmlParser.basicWriter();\r
479                                 this.writeChildrenHtml.call( this, writer, filter, true );\r
480                                 var html = writer.getHtml();\r
481                                 this.children = new CKEDITOR.htmlParser.fragment.fromHtml( html ).children;\r
482                                 isChildrenFiltered = 1;\r
483                         };\r
484 \r
485                         // Filtering the root fragment before anything else.\r
486                         !this.name && filter && filter.onFragment( this );\r
487 \r
488                         this.writeChildrenHtml( writer, isChildrenFiltered ? null : filter );\r
489                 },\r
490 \r
491                 writeChildrenHtml : function( writer, filter )\r
492                 {\r
493                         for ( var i = 0 ; i < this.children.length ; i++ )\r
494                                 this.children[i].writeHtml( writer, filter );\r
495                 }\r
496         };\r
497 })();\r