JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
vanilla ckeditor-3.0.1
[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                         var index = 0,\r
268                                 pendingAdd = [],\r
269                                 candidate = currentNode;\r
270 \r
271                         while ( candidate.type && candidate.name != tagName )\r
272                         {\r
273                                 // If this is an inline element, add it to the pending list, so\r
274                                 // it will continue after the closing tag.\r
275                                 if ( !candidate._.isBlockLike )\r
276                                 {\r
277                                         pendingInline.unshift( candidate );\r
278 \r
279                                         // Increase the index, so it will not get checked again in\r
280                                         // the pending list check that follows.\r
281                                         index++;\r
282                                 }\r
283 \r
284                                 // This node should be added to it's parent at this point. But,\r
285                                 // it should happen only if the closing tag is really closing\r
286                                 // one of the nodes. So, for now, we just cache it.\r
287                                 pendingAdd.push( candidate );\r
288 \r
289                                 candidate = candidate.parent;\r
290                         }\r
291 \r
292                         if ( candidate.type )\r
293                         {\r
294                                 // Add all elements that have been found in the above loop.\r
295                                 for ( var i = 0 ; i < pendingAdd.length ; i++ )\r
296                                 {\r
297                                         var node = pendingAdd[ i ];\r
298                                         addElement( node, node.parent );\r
299                                 }\r
300 \r
301                                 currentNode = candidate;\r
302 \r
303                                 if( currentNode.name == 'pre' )\r
304                                         inPre = false;\r
305 \r
306                                 addElement( candidate, candidate.parent );\r
307 \r
308                                 // The parent should start receiving new nodes now, except if\r
309                                 // addElement changed the currentNode.\r
310                                 if ( candidate == currentNode )\r
311                                         currentNode = currentNode.parent;\r
312                         }\r
313                         // The tag is not actually closing anything, thus we need invalidate\r
314                         // the pending elements.(#3862)\r
315                         else\r
316                         {\r
317                                 pendingInline.splice( 0, index );\r
318                                 index = 0;\r
319                         }\r
320 \r
321                         // Check if there is any pending tag to be closed.\r
322                         for ( ; index < pendingInline.length ; index++ )\r
323                         {\r
324                                 // If found, just remove it from the list.\r
325                                 if ( tagName == pendingInline[ index ].name )\r
326                                 {\r
327                                         pendingInline.splice( index, 1 );\r
328 \r
329                                         // Decrease the index so we continue from the next one.\r
330                                         index--;\r
331                                 }\r
332                         }\r
333                 };\r
334 \r
335                 parser.onText = function( text )\r
336                 {\r
337                         // Trim empty spaces at beginning of element contents except <pre>.\r
338                         if ( !currentNode._.hasInlineStarted && !inPre )\r
339                         {\r
340                                 text = CKEDITOR.tools.ltrim( text );\r
341 \r
342                                 if ( text.length === 0 )\r
343                                         return;\r
344                         }\r
345 \r
346                         checkPending();\r
347 \r
348                         if ( fixForBody && !currentNode.type )\r
349                                 this.onTagOpen( fixForBody, {} );\r
350 \r
351                         // Shrinking consequential spaces into one single for all elements\r
352                         // text contents.\r
353                         if ( !inPre )\r
354                                 text = text.replace( /[\t\r\n ]{2,}|[\t\r\n]/g, ' ' );\r
355 \r
356                         currentNode.add( new CKEDITOR.htmlParser.text( text ) );\r
357                 };\r
358 \r
359                 parser.onCDATA = function( cdata )\r
360                 {\r
361                         currentNode.add( new CKEDITOR.htmlParser.cdata( cdata ) );\r
362                 };\r
363 \r
364                 parser.onComment = function( comment )\r
365                 {\r
366                         currentNode.add( new CKEDITOR.htmlParser.comment( comment ) );\r
367                 };\r
368 \r
369                 // Parse it.\r
370                 parser.parse( fragmentHtml );\r
371 \r
372                 // Close all pending nodes.\r
373                 while ( currentNode.type )\r
374                 {\r
375                         var parent = currentNode.parent,\r
376                                 node = currentNode;\r
377 \r
378                         if ( fixForBody && !parent.type && !CKEDITOR.dtd.$body[ node.name ] )\r
379                         {\r
380                                 currentNode = parent;\r
381                                 parser.onTagOpen( fixForBody, {} );\r
382                                 parent = currentNode;\r
383                         }\r
384 \r
385                         parent.add( node );\r
386                         currentNode = parent;\r
387                 }\r
388 \r
389                 return fragment;\r
390         };\r
391 \r
392         CKEDITOR.htmlParser.fragment.prototype =\r
393         {\r
394                 /**\r
395                  * Adds a node to this fragment.\r
396                  * @param {Object} node The node to be added. It can be any of of the\r
397                  *              following types: {@link CKEDITOR.htmlParser.element},\r
398                  *              {@link CKEDITOR.htmlParser.text} and\r
399                  *              {@link CKEDITOR.htmlParser.comment}.\r
400                  * @example\r
401                  */\r
402                 add : function( node )\r
403                 {\r
404                         var len = this.children.length,\r
405                                 previous = len > 0 && this.children[ len - 1 ] || null;\r
406 \r
407                         if ( previous )\r
408                         {\r
409                                 // If the block to be appended is following text, trim spaces at\r
410                                 // the right of it.\r
411                                 if ( node._.isBlockLike && previous.type == CKEDITOR.NODE_TEXT )\r
412                                 {\r
413                                         previous.value = CKEDITOR.tools.rtrim( previous.value );\r
414 \r
415                                         // If we have completely cleared the previous node.\r
416                                         if ( previous.value.length === 0 )\r
417                                         {\r
418                                                 // Remove it from the list and add the node again.\r
419                                                 this.children.pop();\r
420                                                 this.add( node );\r
421                                                 return;\r
422                                         }\r
423                                 }\r
424 \r
425                                 previous.next = node;\r
426                         }\r
427 \r
428                         node.previous = previous;\r
429                         node.parent = this;\r
430 \r
431                         this.children.push( node );\r
432 \r
433                         this._.hasInlineStarted = node.type == CKEDITOR.NODE_TEXT || ( node.type == CKEDITOR.NODE_ELEMENT && !node._.isBlockLike );\r
434                 },\r
435 \r
436                 /**\r
437                  * Writes the fragment HTML to a CKEDITOR.htmlWriter.\r
438                  * @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.\r
439                  * @example\r
440                  * var writer = new CKEDITOR.htmlWriter();\r
441                  * var fragment = CKEDITOR.htmlParser.fragment.fromHtml( '&lt;P&gt;&lt;B&gt;Example' );\r
442                  * fragment.writeHtml( writer )\r
443                  * alert( writer.getHtml() );  "&lt;p&gt;&lt;b&gt;Example&lt;/b&gt;&lt;/p&gt;"\r
444                  */\r
445                 writeHtml : function( writer, filter )\r
446                 {\r
447                         for ( var i = 0, len = this.children.length ; i < len ; i++ )\r
448                                 this.children[i].writeHtml( writer, filter );\r
449                 }\r
450         };\r
451 })();\r