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