JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
66bb3be0e9f8d848f29e8744e630a5aca630a400
[ckeditor.git] / _source / core / htmlparser / fragment.js
1 /*\r
2 Copyright (c) 2003-2009, 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                         currentNode = fragment,\r
68                     // Indicate we're inside a <pre> element, spaces should be touched differently.\r
69                         inPre = false,\r
70                         returnPoint;\r
71 \r
72                 function checkPending( newTagName )\r
73                 {\r
74                         if ( pendingInline.length > 0 )\r
75                         {\r
76                                 for ( var i = 0 ; i < pendingInline.length ; i++ )\r
77                                 {\r
78                                         var pendingElement = pendingInline[ i ],\r
79                                                 pendingName = pendingElement.name,\r
80                                                 pendingDtd = CKEDITOR.dtd[ pendingName ],\r
81                                                 currentDtd = currentNode.name && CKEDITOR.dtd[ currentNode.name ];\r
82 \r
83                                         if ( ( !currentDtd || currentDtd[ pendingName ] ) && ( !newTagName || !pendingDtd || pendingDtd[ newTagName ] || !CKEDITOR.dtd[ newTagName ] ) )\r
84                                         {\r
85                                                 // Get a clone for the pending element.\r
86                                                 pendingElement = pendingElement.clone();\r
87 \r
88                                                 // Add it to the current node and make it the current,\r
89                                                 // so the new element will be added inside of it.\r
90                                                 pendingElement.parent = currentNode;\r
91                                                 currentNode = pendingElement;\r
92 \r
93                                                 // Remove the pending element (back the index by one\r
94                                                 // to properly process the next entry).\r
95                                                 pendingInline.splice( i, 1 );\r
96                                                 i--;\r
97                                         }\r
98                                 }\r
99                         }\r
100                 }\r
101 \r
102                 function addElement( element, target, enforceCurrent )\r
103                 {\r
104                         target = target || currentNode || fragment;\r
105 \r
106                         // If the target is the fragment and this element can't go inside\r
107                         // body (if fixForBody).\r
108                         if ( fixForBody && !target.type )\r
109                         {\r
110                                 var elementName, realElementName;\r
111                                 if ( element.attributes\r
112                                          && ( realElementName =\r
113                                                   element.attributes[ '_cke_real_element_type' ] ) )\r
114                                         elementName = realElementName;\r
115                                 else\r
116                                         elementName =  element.name;\r
117                                 if ( !( elementName in CKEDITOR.dtd.$body ) )\r
118                                 {\r
119                                         var savedCurrent = currentNode;\r
120 \r
121                                         // Create a <p> in the fragment.\r
122                                         currentNode = target;\r
123                                         parser.onTagOpen( fixForBody, {} );\r
124 \r
125                                         // The new target now is the <p>.\r
126                                         target = currentNode;\r
127 \r
128                                         if ( enforceCurrent )\r
129                                                 currentNode = savedCurrent;\r
130                                 }\r
131                         }\r
132 \r
133                         // Rtrim empty spaces on block end boundary. (#3585)\r
134                         if ( element._.isBlockLike\r
135                                  && element.name != 'pre' )\r
136                         {\r
137 \r
138                                 var length = element.children.length,\r
139                                         lastChild = element.children[ length - 1 ],\r
140                                         text;\r
141                                 if ( lastChild && lastChild.type == CKEDITOR.NODE_TEXT )\r
142                                 {\r
143                                         if ( !( text = CKEDITOR.tools.rtrim( lastChild.value ) ) )\r
144                                                 element.children.length = length -1;\r
145                                         else\r
146                                                 lastChild.value = text;\r
147                                 }\r
148                         }\r
149 \r
150                         target.add( element );\r
151 \r
152                         if ( element.returnPoint )\r
153                         {\r
154                                 currentNode = element.returnPoint;\r
155                                 delete element.returnPoint;\r
156                         }\r
157                 }\r
158 \r
159                 parser.onTagOpen = function( tagName, attributes, selfClosing )\r
160                 {\r
161                         var element = new CKEDITOR.htmlParser.element( tagName, attributes );\r
162 \r
163                         // "isEmpty" will be always "false" for unknown elements, so we\r
164                         // must force it if the parser has identified it as a selfClosing tag.\r
165                         if ( element.isUnknown && selfClosing )\r
166                                 element.isEmpty = true;\r
167 \r
168                         // This is a tag to be removed if empty, so do not add it immediately.\r
169                         if ( CKEDITOR.dtd.$removeEmpty[ tagName ] )\r
170                         {\r
171                                 pendingInline.push( element );\r
172                                 return;\r
173                         }\r
174                         else if ( tagName == 'pre' )\r
175                                 inPre = true;\r
176                         else if ( tagName == 'br' && inPre )\r
177                         {\r
178                                 currentNode.add( new CKEDITOR.htmlParser.text( '\n' ) );\r
179                                 return;\r
180                         }\r
181 \r
182                         var currentName = currentNode.name,\r
183                                 currentDtd = ( currentName && CKEDITOR.dtd[ currentName ] ) || ( currentNode._.isBlockLike ? CKEDITOR.dtd.div : CKEDITOR.dtd.span );\r
184 \r
185                         // If the element cannot be child of the current element.\r
186                         if ( !element.isUnknown && !currentNode.isUnknown && !currentDtd[ tagName ] )\r
187                         {\r
188                                 // If this is the fragment node, just ignore this tag and add\r
189                                 // its children.\r
190                                 if ( !currentName )\r
191                                         return;\r
192 \r
193                                 var reApply = false,\r
194                                         addPoint;   // New position to start adding nodes.\r
195 \r
196                                 // Fixing malformed nested lists(#3828).\r
197                                 if( tagName in listBlocks\r
198                                         && currentName in listBlocks )\r
199                                 {\r
200                                         var children = currentNode.children,\r
201                                                 lastChild = children[ children.length - 1 ];\r
202                                         // Move inner list into to previous list item if any.\r
203                                         if( lastChild && lastChild.name in listItems )\r
204                                                 returnPoint = currentNode, addPoint = lastChild;\r
205                                         // Move inner list outside in the worst case.\r
206                                         else\r
207                                                 addElement( currentNode, currentNode.parent );\r
208                                 }\r
209                                 // If the element name is the same as the current element name,\r
210                                 // then just close the current one and append the new one to the\r
211                                 // parent. This situation usually happens with <p>, <li>, <dt> and\r
212                                 // <dd>, specially in IE. Do not enter in this if block in this case.\r
213                                 else if ( tagName == currentName )\r
214                                 {\r
215                                         addElement( currentNode, currentNode.parent );\r
216                                 }\r
217                                 else\r
218                                 {\r
219                                         if ( nonBreakingBlocks[ currentName ] )\r
220                                         {\r
221                                                 if ( !returnPoint )\r
222                                                         returnPoint = currentNode;\r
223                                         }\r
224                                         else\r
225                                         {\r
226                                                 addElement( currentNode, currentNode.parent, true );\r
227 \r
228                                                 if ( !optionalClose[ currentName ] )\r
229                                                 {\r
230                                                         // The current element is an inline element, which\r
231                                                         // cannot hold the new one. Put it in the pending list,\r
232                                                         // and try adding the new one after it.\r
233                                                         pendingInline.unshift( currentNode );\r
234                                                 }\r
235                                         }\r
236 \r
237                                         reApply = true;\r
238                                 }\r
239 \r
240                                 if( addPoint )\r
241                                         currentNode = addPoint;\r
242                                 // Try adding it to the return point, or the parent element.\r
243                                 else\r
244                                         currentNode = currentNode.returnPoint || currentNode.parent;\r
245 \r
246                                 if ( reApply )\r
247                                 {\r
248                                         parser.onTagOpen.apply( this, arguments );\r
249                                         return;\r
250                                 }\r
251                         }\r
252 \r
253                         checkPending( tagName );\r
254 \r
255                         element.parent = currentNode;\r
256                         element.returnPoint = returnPoint;\r
257                         returnPoint = 0;\r
258 \r
259                         if ( element.isEmpty )\r
260                                 addElement( element );\r
261                         else\r
262                                 currentNode = element;\r
263                 };\r
264 \r
265                 parser.onTagClose = function( tagName )\r
266                 {\r
267                         // Check if there is any pending tag to be closed.\r
268                         for ( var i = pendingInline.length - 1 ; i >= 0 ; i-- )\r
269                         {\r
270                                 // If found, just remove it from the list.\r
271                                 if ( tagName == pendingInline[ i ].name )\r
272                                 {\r
273                                         pendingInline.splice( i, 1 );\r
274                                         return;\r
275                                 }\r
276                         }\r
277 \r
278                         var pendingAdd = [],\r
279                                 candidate = currentNode;\r
280 \r
281                         while ( candidate.type && candidate.name != tagName )\r
282                         {\r
283                                 // If this is an inline element, add it to the pending list, so\r
284                                 // it will continue after the closing tag.\r
285                                 if ( !candidate._.isBlockLike )\r
286                                         pendingInline.unshift( candidate );\r
287 \r
288                                 // This node should be added to it's parent at this point. But,\r
289                                 // it should happen only if the closing tag is really closing\r
290                                 // one of the nodes. So, for now, we just cache it.\r
291                                 pendingAdd.push( candidate );\r
292 \r
293                                 candidate = candidate.parent;\r
294                         }\r
295 \r
296                         if ( candidate.type )\r
297                         {\r
298                                 // Add all elements that have been found in the above loop.\r
299                                 for ( i = 0 ; i < pendingAdd.length ; i++ )\r
300                                 {\r
301                                         var node = pendingAdd[ i ];\r
302                                         addElement( node, node.parent );\r
303                                 }\r
304 \r
305                                 currentNode = candidate;\r
306 \r
307                                 if( currentNode.name == 'pre' )\r
308                                         inPre = false;\r
309 \r
310                                 addElement( candidate, candidate.parent );\r
311 \r
312                                 // The parent should start receiving new nodes now, except if\r
313                                 // addElement changed the currentNode.\r
314                                 if ( candidate == currentNode )\r
315                                         currentNode = currentNode.parent;\r
316                         }\r
317                 };\r
318 \r
319                 parser.onText = function( text )\r
320                 {\r
321                         // Trim empty spaces at beginning of element contents except <pre>.\r
322                         if ( !currentNode._.hasInlineStarted && !inPre )\r
323                         {\r
324                                 text = CKEDITOR.tools.ltrim( text );\r
325 \r
326                                 if ( text.length === 0 )\r
327                                         return;\r
328                         }\r
329 \r
330                         checkPending();\r
331 \r
332                         if ( fixForBody && !currentNode.type )\r
333                                 this.onTagOpen( fixForBody, {} );\r
334 \r
335                         // Shrinking consequential spaces into one single for all elements\r
336                         // text contents.\r
337                         if ( !inPre )\r
338                                 text = text.replace( /[\t\r\n ]{2,}|[\t\r\n]/g, ' ' );\r
339 \r
340                         currentNode.add( new CKEDITOR.htmlParser.text( text ) );\r
341                 };\r
342 \r
343                 parser.onCDATA = function( cdata )\r
344                 {\r
345                         currentNode.add( new CKEDITOR.htmlParser.cdata( cdata ) );\r
346                 };\r
347 \r
348                 parser.onComment = function( comment )\r
349                 {\r
350                         currentNode.add( new CKEDITOR.htmlParser.comment( comment ) );\r
351                 };\r
352 \r
353                 // Parse it.\r
354                 parser.parse( fragmentHtml );\r
355 \r
356                 // Close all pending nodes.\r
357                 while ( currentNode.type )\r
358                 {\r
359                         var parent = currentNode.parent,\r
360                                 node = currentNode;\r
361 \r
362                         if ( fixForBody && !parent.type && !CKEDITOR.dtd.$body[ node.name ] )\r
363                         {\r
364                                 currentNode = parent;\r
365                                 parser.onTagOpen( fixForBody, {} );\r
366                                 parent = currentNode;\r
367                         }\r
368 \r
369                         parent.add( node );\r
370                         currentNode = parent;\r
371                 }\r
372 \r
373                 return fragment;\r
374         };\r
375 \r
376         CKEDITOR.htmlParser.fragment.prototype =\r
377         {\r
378                 /**\r
379                  * Adds a node to this fragment.\r
380                  * @param {Object} node The node to be added. It can be any of of the\r
381                  *              following types: {@link CKEDITOR.htmlParser.element},\r
382                  *              {@link CKEDITOR.htmlParser.text} and\r
383                  *              {@link CKEDITOR.htmlParser.comment}.\r
384                  * @example\r
385                  */\r
386                 add : function( node )\r
387                 {\r
388                         var len = this.children.length,\r
389                                 previous = len > 0 && this.children[ len - 1 ] || null;\r
390 \r
391                         if ( previous )\r
392                         {\r
393                                 // If the block to be appended is following text, trim spaces at\r
394                                 // the right of it.\r
395                                 if ( node._.isBlockLike && previous.type == CKEDITOR.NODE_TEXT )\r
396                                 {\r
397                                         previous.value = CKEDITOR.tools.rtrim( previous.value );\r
398 \r
399                                         // If we have completely cleared the previous node.\r
400                                         if ( previous.value.length === 0 )\r
401                                         {\r
402                                                 // Remove it from the list and add the node again.\r
403                                                 this.children.pop();\r
404                                                 this.add( node );\r
405                                                 return;\r
406                                         }\r
407                                 }\r
408 \r
409                                 previous.next = node;\r
410                         }\r
411 \r
412                         node.previous = previous;\r
413                         node.parent = this;\r
414 \r
415                         this.children.push( node );\r
416 \r
417                         this._.hasInlineStarted = node.type == CKEDITOR.NODE_TEXT || ( node.type == CKEDITOR.NODE_ELEMENT && !node._.isBlockLike );\r
418                 },\r
419 \r
420                 /**\r
421                  * Writes the fragment HTML to a CKEDITOR.htmlWriter.\r
422                  * @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.\r
423                  * @example\r
424                  * var writer = new CKEDITOR.htmlWriter();\r
425                  * var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '&lt;P&gt;&lt;B&gt;Example' );\r
426                  * fragment.writeHtml( writer )\r
427                  * alert( writer.getHtml() );  "&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;&lt;/p&gt;"\r
428                  */\r
429                 writeHtml : function( writer, filter )\r
430                 {\r
431                         for ( var i = 0, len = this.children.length ; i < len ; i++ )\r
432                                 this.children[i].writeHtml( writer, filter );\r
433                 }\r
434         };\r
435 })();\r