Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / core / core / DomHelper.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.DomHelper\r
9  * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating\r
10  * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates\r
11  * from your DOM building code.</p>\r
12  *\r
13  * <p><b><u>DomHelper element specification object</u></b></p>\r
14  * <p>A specification object is used when creating elements. Attributes of this object\r
15  * are assumed to be element attributes, except for 4 special attributes:\r
16  * <div class="mdetail-params"><ul>\r
17  * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>\r
18  * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the\r
19  * same kind of element definition objects to be created and appended. These can be nested\r
20  * as deep as you want.</div></li>\r
21  * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.\r
22  * This will end up being either the "class" attribute on a HTML fragment or className\r
23  * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>\r
24  * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>\r
25  * </ul></div></p>\r
26  *\r
27  * <p><b><u>Insertion methods</u></b></p>\r
28  * <p>Commonly used insertion methods:\r
29  * <div class="mdetail-params"><ul>\r
30  * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>\r
31  * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>\r
32  * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>\r
33  * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>\r
34  * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>\r
35  * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>\r
36  * </ul></div></p>\r
37  *\r
38  * <p><b><u>Example</u></b></p>\r
39  * <p>This is an example, where an unordered list with 3 children items is appended to an existing\r
40  * element with id <tt>'my-div'</tt>:<br>\r
41  <pre><code>\r
42 var dh = Ext.DomHelper; // create shorthand alias\r
43 // specification object\r
44 var spec = {\r
45     id: 'my-ul',\r
46     tag: 'ul',\r
47     cls: 'my-list',\r
48     // append children after creating\r
49     children: [     // may also specify 'cn' instead of 'children'\r
50         {tag: 'li', id: 'item0', html: 'List Item 0'},\r
51         {tag: 'li', id: 'item1', html: 'List Item 1'},\r
52         {tag: 'li', id: 'item2', html: 'List Item 2'}\r
53     ]\r
54 };\r
55 var list = dh.append(\r
56     'my-div', // the context element 'my-div' can either be the id or the actual node\r
57     spec      // the specification object\r
58 );\r
59  </code></pre></p>\r
60  * <p>Element creation specification parameters in this class may also be passed as an Array of\r
61  * specification objects. This can be used to insert multiple sibling nodes into an existing\r
62  * container very efficiently. For example, to add more list items to the example above:<pre><code>\r
63 dh.append('my-ul', [\r
64     {tag: 'li', id: 'item3', html: 'List Item 3'},\r
65     {tag: 'li', id: 'item4', html: 'List Item 4'}\r
66 ]);\r
67  * </code></pre></p>\r
68  *\r
69  * <p><b><u>Templating</u></b></p>\r
70  * <p>The real power is in the built-in templating. Instead of creating or appending any elements,\r
71  * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to\r
72  * insert new elements. Revisiting the example above, we could utilize templating this time:\r
73  * <pre><code>\r
74 // create the node\r
75 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});\r
76 // get template\r
77 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});\r
78 \r
79 for(var i = 0; i < 5, i++){\r
80     tpl.append(list, [i]); // use template to append to the actual node\r
81 }\r
82  * </code></pre></p>\r
83  * <p>An example using a template:<pre><code>\r
84 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';\r
85 \r
86 var tpl = new Ext.DomHelper.createTemplate(html);\r
87 tpl.append('blog-roll', ['link1', 'http://www.jackslocum.com/', "Jack&#39;s Site"]);\r
88 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);\r
89  * </code></pre></p>\r
90  *\r
91  * <p>The same example using named parameters:<pre><code>\r
92 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';\r
93 \r
94 var tpl = new Ext.DomHelper.createTemplate(html);\r
95 tpl.append('blog-roll', {\r
96     id: 'link1',\r
97     url: 'http://www.jackslocum.com/',\r
98     text: "Jack&#39;s Site"\r
99 });\r
100 tpl.append('blog-roll', {\r
101     id: 'link2',\r
102     url: 'http://www.dustindiaz.com/',\r
103     text: "Dustin&#39;s Site"\r
104 });\r
105  * </code></pre></p>\r
106  *\r
107  * <p><b><u>Compiling Templates</u></b></p>\r
108  * <p>Templates are applied using regular expressions. The performance is great, but if\r
109  * you are adding a bunch of DOM elements using the same template, you can increase\r
110  * performance even further by {@link Ext.Template#compile "compiling"} the template.\r
111  * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and\r
112  * broken up at the different variable points and a dynamic function is created and eval'ed.\r
113  * The generated function performs string concatenation of these parts and the passed\r
114  * variables instead of using regular expressions.\r
115  * <pre><code>\r
116 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';\r
117 \r
118 var tpl = new Ext.DomHelper.createTemplate(html);\r
119 tpl.compile();\r
120 \r
121 //... use template like normal\r
122  * </code></pre></p>\r
123  *\r
124  * <p><b><u>Performance Boost</u></b></p>\r
125  * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead\r
126  * of DOM can significantly boost performance.</p>\r
127  * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,\r
128  * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification\r
129  * results in the creation of a text node. Usage:</p>\r
130  * <pre><code>\r
131 Ext.DomHelper.useDom = true; // force it to use DOM; reduces performance\r
132  * </code></pre>\r
133  * @singleton\r
134  */\r
135 Ext.DomHelper = function(){\r
136     var tempTableEl = null,\r
137         emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,\r
138         tableRe = /^table|tbody|tr|td$/i,\r
139         pub,\r
140         // kill repeat to save bytes\r
141         afterbegin = 'afterbegin',\r
142         afterend = 'afterend',\r
143         beforebegin = 'beforebegin',\r
144         beforeend = 'beforeend',\r
145         ts = '<table>',\r
146         te = '</table>',\r
147         tbs = ts+'<tbody>',\r
148         tbe = '</tbody>'+te,\r
149         trs = tbs + '<tr>',\r
150         tre = '</tr>'+tbe;\r
151 \r
152     // private\r
153     function doInsert(el, o, returnElement, pos, sibling, append){\r
154         var newNode = pub.insertHtml(pos, Ext.getDom(el), createHtml(o));\r
155         return returnElement ? Ext.get(newNode, true) : newNode;\r
156     }\r
157 \r
158     // build as innerHTML where available\r
159     function createHtml(o){\r
160         var b = '',\r
161             attr,\r
162             val,\r
163             key,\r
164             keyVal,\r
165             cn;\r
166 \r
167         if(Ext.isString(o)){\r
168             b = o;\r
169         } else if (Ext.isArray(o)) {\r
170             Ext.each(o, function(v) {\r
171                 b += createHtml(v);\r
172             });\r
173         } else {\r
174             b += '<' + (o.tag = o.tag || 'div');\r
175             Ext.iterate(o, function(attr, val){\r
176                 if(!/tag|children|cn|html$/i.test(attr)){\r
177                     if (Ext.isObject(val)) {\r
178                         b += ' ' + attr + '="';\r
179                         Ext.iterate(val, function(key, keyVal){\r
180                             b += key + ':' + keyVal + ';';\r
181                         });\r
182                         b += '"';\r
183                     }else{\r
184                         b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';\r
185                     }\r
186                 }\r
187             });\r
188             // Now either just close the tag or try to add children and close the tag.\r
189             if (emptyTags.test(o.tag)) {\r
190                 b += '/>';\r
191             } else {\r
192                 b += '>';\r
193                 if ((cn = o.children || o.cn)) {\r
194                     b += createHtml(cn);\r
195                 } else if(o.html){\r
196                     b += o.html;\r
197                 }\r
198                 b += '</' + o.tag + '>';\r
199             }\r
200         }\r
201         return b;\r
202     }\r
203 \r
204     function ieTable(depth, s, h, e){\r
205         tempTableEl.innerHTML = [s, h, e].join('');\r
206         var i = -1,\r
207             el = tempTableEl,\r
208             ns;\r
209         while(++i < depth){\r
210             el = el.firstChild;\r
211         }\r
212 //      If the result is multiple siblings, then encapsulate them into one fragment.\r
213         if(ns = el.nextSibling){\r
214             var df = document.createDocumentFragment();\r
215             while(el){\r
216                 ns = el.nextSibling;\r
217                 df.appendChild(el);\r
218                 el = ns;\r
219             }\r
220             el = df;\r
221         }\r
222         return el;\r
223     }\r
224 \r
225     /**\r
226      * @ignore\r
227      * Nasty code for IE's broken table implementation\r
228      */\r
229     function insertIntoTable(tag, where, el, html) {\r
230         var node,\r
231             before;\r
232 \r
233         tempTableEl = tempTableEl || document.createElement('div');\r
234 \r
235         if(tag == 'td' && (where == afterbegin || where == beforeend) ||\r
236            !/td|tr|tbody/i.test(tag) && (where == beforebegin || where == afterend)) {\r
237             return;\r
238         }\r
239         before = where == beforebegin ? el :\r
240                  where == afterend ? el.nextSibling :\r
241                  where == afterbegin ? el.firstChild : null;\r
242 \r
243         if (where == beforebegin || where == afterend) {\r
244             el = el.parentNode;\r
245         }\r
246 \r
247         if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {\r
248             node = ieTable(4, trs, html, tre);\r
249         } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||\r
250                    (tag == 'tr' && (where == beforebegin || where == afterend))) {\r
251             node = ieTable(3, tbs, html, tbe);\r
252         } else {\r
253             node = ieTable(2, ts, html, te);\r
254         }\r
255         el.insertBefore(node, before);\r
256         return node;\r
257     }\r
258 \r
259 \r
260     pub = {\r
261         /**\r
262          * Returns the markup for the passed Element(s) config.\r
263          * @param {Object} o The DOM object spec (and children)\r
264          * @return {String}\r
265          */\r
266         markup : function(o){\r
267             return createHtml(o);\r
268         },\r
269         \r
270         /**\r
271          * Applies a style specification to an element.\r
272          * @param {String/HTMLElement} el The element to apply styles to\r
273          * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or\r
274          * a function which returns such a specification.\r
275          */\r
276         applyStyles : function(el, styles){\r
277             if(styles){\r
278                 var i = 0,\r
279                     len,\r
280                     style;\r
281 \r
282                 el = Ext.fly(el);\r
283                 if(Ext.isFunction(styles)){\r
284                     styles = styles.call();\r
285                 }\r
286                 if(Ext.isString(styles)){\r
287                     styles = styles.trim().split(/\s*(?::|;)\s*/);\r
288                     for(len = styles.length; i < len;){\r
289                         el.setStyle(styles[i++], styles[i++]);\r
290                     }\r
291                 }else if (Ext.isObject(styles)){\r
292                     el.setStyle(styles);\r
293                 }\r
294             }\r
295         },\r
296 \r
297         /**\r
298          * Inserts an HTML fragment into the DOM.\r
299          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.\r
300          * @param {HTMLElement} el The context element\r
301          * @param {String} html The HTML fragment\r
302          * @return {HTMLElement} The new node\r
303          */\r
304         insertHtml : function(where, el, html){\r
305             var hash = {},\r
306                 hashVal,\r
307                 setStart,\r
308                 range,\r
309                 frag,\r
310                 rangeEl,\r
311                 rs;\r
312 \r
313             where = where.toLowerCase();\r
314             // add these here because they are used in both branches of the condition.\r
315             hash[beforebegin] = ['BeforeBegin', 'previousSibling'];\r
316             hash[afterend] = ['AfterEnd', 'nextSibling'];\r
317 \r
318             if (el.insertAdjacentHTML) {\r
319                 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){\r
320                     return rs;\r
321                 }\r
322                 // add these two to the hash.\r
323                 hash[afterbegin] = ['AfterBegin', 'firstChild'];\r
324                 hash[beforeend] = ['BeforeEnd', 'lastChild'];\r
325                 if ((hashVal = hash[where])) {\r
326                     el.insertAdjacentHTML(hashVal[0], html);\r
327                     return el[hashVal[1]];\r
328                 }\r
329             } else {\r
330                 range = el.ownerDocument.createRange();\r
331                 setStart = 'setStart' + (/end/i.test(where) ? 'After' : 'Before');\r
332                 if (hash[where]) {\r
333                     range[setStart](el);\r
334                     frag = range.createContextualFragment(html);\r
335                     el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);\r
336                     return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];\r
337                 } else {\r
338                     rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';\r
339                     if (el.firstChild) {\r
340                         range[setStart](el[rangeEl]);\r
341                         frag = range.createContextualFragment(html);\r
342                         if(where == afterbegin){\r
343                             el.insertBefore(frag, el.firstChild);\r
344                         }else{\r
345                             el.appendChild(frag);\r
346                         }\r
347                     } else {\r
348                         el.innerHTML = html;\r
349                     }\r
350                     return el[rangeEl];\r
351                 }\r
352             }\r
353             throw 'Illegal insertion point -> "' + where + '"';\r
354         },\r
355 \r
356         /**\r
357          * Creates new DOM element(s) and inserts them before el.\r
358          * @param {Mixed} el The context element\r
359          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
360          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
361          * @return {HTMLElement/Ext.Element} The new node\r
362          */\r
363         insertBefore : function(el, o, returnElement){\r
364             return doInsert(el, o, returnElement, beforebegin);\r
365         },\r
366 \r
367         /**\r
368          * Creates new DOM element(s) and inserts them after el.\r
369          * @param {Mixed} el The context element\r
370          * @param {Object} o The DOM object spec (and children)\r
371          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
372          * @return {HTMLElement/Ext.Element} The new node\r
373          */\r
374         insertAfter : function(el, o, returnElement){\r
375             return doInsert(el, o, returnElement, afterend, 'nextSibling');\r
376         },\r
377 \r
378         /**\r
379          * Creates new DOM element(s) and inserts them as the first child of el.\r
380          * @param {Mixed} el The context element\r
381          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
382          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
383          * @return {HTMLElement/Ext.Element} The new node\r
384          */\r
385         insertFirst : function(el, o, returnElement){\r
386             return doInsert(el, o, returnElement, afterbegin, 'firstChild');\r
387         },\r
388 \r
389         /**\r
390          * Creates new DOM element(s) and appends them to el.\r
391          * @param {Mixed} el The context element\r
392          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
393          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
394          * @return {HTMLElement/Ext.Element} The new node\r
395          */\r
396         append : function(el, o, returnElement){\r
397             return doInsert(el, o, returnElement, beforeend, '', true);\r
398         },\r
399 \r
400         /**\r
401          * Creates new DOM element(s) and overwrites the contents of el with them.\r
402          * @param {Mixed} el The context element\r
403          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
404          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
405          * @return {HTMLElement/Ext.Element} The new node\r
406          */\r
407         overwrite : function(el, o, returnElement){\r
408             el = Ext.getDom(el);\r
409             el.innerHTML = createHtml(o);\r
410             return returnElement ? Ext.get(el.firstChild) : el.firstChild;\r
411         },\r
412 \r
413         createHtml : createHtml\r
414     };\r
415     return pub;\r
416 }();