Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / core / core / DomHelper.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 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             for (var i=0; i < o.length; i++) {\r
171                 if(o[i]) {\r
172                     b += createHtml(o[i]);\r
173                 }\r
174             };\r
175         } else {\r
176             b += '<' + (o.tag = o.tag || 'div');\r
177             Ext.iterate(o, function(attr, val){\r
178                 if(!/tag|children|cn|html$/i.test(attr)){\r
179                     if (Ext.isObject(val)) {\r
180                         b += ' ' + attr + '="';\r
181                         Ext.iterate(val, function(key, keyVal){\r
182                             b += key + ':' + keyVal + ';';\r
183                         });\r
184                         b += '"';\r
185                     }else{\r
186                         b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';\r
187                     }\r
188                 }\r
189             });\r
190             // Now either just close the tag or try to add children and close the tag.\r
191             if (emptyTags.test(o.tag)) {\r
192                 b += '/>';\r
193             } else {\r
194                 b += '>';\r
195                 if ((cn = o.children || o.cn)) {\r
196                     b += createHtml(cn);\r
197                 } else if(o.html){\r
198                     b += o.html;\r
199                 }\r
200                 b += '</' + o.tag + '>';\r
201             }\r
202         }\r
203         return b;\r
204     }\r
205 \r
206     function ieTable(depth, s, h, e){\r
207         tempTableEl.innerHTML = [s, h, e].join('');\r
208         var i = -1,\r
209             el = tempTableEl,\r
210             ns;\r
211         while(++i < depth){\r
212             el = el.firstChild;\r
213         }\r
214 //      If the result is multiple siblings, then encapsulate them into one fragment.\r
215         if(ns = el.nextSibling){\r
216             var df = document.createDocumentFragment();\r
217             while(el){\r
218                 ns = el.nextSibling;\r
219                 df.appendChild(el);\r
220                 el = ns;\r
221             }\r
222             el = df;\r
223         }\r
224         return el;\r
225     }\r
226 \r
227     /**\r
228      * @ignore\r
229      * Nasty code for IE's broken table implementation\r
230      */\r
231     function insertIntoTable(tag, where, el, html) {\r
232         var node,\r
233             before;\r
234 \r
235         tempTableEl = tempTableEl || document.createElement('div');\r
236 \r
237         if(tag == 'td' && (where == afterbegin || where == beforeend) ||\r
238            !/td|tr|tbody/i.test(tag) && (where == beforebegin || where == afterend)) {\r
239             return;\r
240         }\r
241         before = where == beforebegin ? el :\r
242                  where == afterend ? el.nextSibling :\r
243                  where == afterbegin ? el.firstChild : null;\r
244 \r
245         if (where == beforebegin || where == afterend) {\r
246             el = el.parentNode;\r
247         }\r
248 \r
249         if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {\r
250             node = ieTable(4, trs, html, tre);\r
251         } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||\r
252                    (tag == 'tr' && (where == beforebegin || where == afterend))) {\r
253             node = ieTable(3, tbs, html, tbe);\r
254         } else {\r
255             node = ieTable(2, ts, html, te);\r
256         }\r
257         el.insertBefore(node, before);\r
258         return node;\r
259     }\r
260 \r
261 \r
262     pub = {\r
263         /**\r
264          * Returns the markup for the passed Element(s) config.\r
265          * @param {Object} o The DOM object spec (and children)\r
266          * @return {String}\r
267          */\r
268         markup : function(o){\r
269             return createHtml(o);\r
270         },\r
271         \r
272         /**\r
273          * Applies a style specification to an element.\r
274          * @param {String/HTMLElement} el The element to apply styles to\r
275          * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or\r
276          * a function which returns such a specification.\r
277          */\r
278         applyStyles : function(el, styles){\r
279             if(styles){\r
280                 var i = 0,\r
281                     len,\r
282                     style;\r
283 \r
284                 el = Ext.fly(el);\r
285                 if(Ext.isFunction(styles)){\r
286                     styles = styles.call();\r
287                 }\r
288                 if(Ext.isString(styles)){\r
289                     styles = styles.trim().split(/\s*(?::|;)\s*/);\r
290                     for(len = styles.length; i < len;){\r
291                         el.setStyle(styles[i++], styles[i++]);\r
292                     }\r
293                 }else if (Ext.isObject(styles)){\r
294                     el.setStyle(styles);\r
295                 }\r
296             }\r
297         },\r
298 \r
299         /**\r
300          * Inserts an HTML fragment into the DOM.\r
301          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.\r
302          * @param {HTMLElement} el The context element\r
303          * @param {String} html The HTML fragment\r
304          * @return {HTMLElement} The new node\r
305          */\r
306         insertHtml : function(where, el, html){\r
307             var hash = {},\r
308                 hashVal,\r
309                 setStart,\r
310                 range,\r
311                 frag,\r
312                 rangeEl,\r
313                 rs;\r
314 \r
315             where = where.toLowerCase();\r
316             // add these here because they are used in both branches of the condition.\r
317             hash[beforebegin] = ['BeforeBegin', 'previousSibling'];\r
318             hash[afterend] = ['AfterEnd', 'nextSibling'];\r
319 \r
320             if (el.insertAdjacentHTML) {\r
321                 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){\r
322                     return rs;\r
323                 }\r
324                 // add these two to the hash.\r
325                 hash[afterbegin] = ['AfterBegin', 'firstChild'];\r
326                 hash[beforeend] = ['BeforeEnd', 'lastChild'];\r
327                 if ((hashVal = hash[where])) {\r
328                     el.insertAdjacentHTML(hashVal[0], html);\r
329                     return el[hashVal[1]];\r
330                 }\r
331             } else {\r
332                 range = el.ownerDocument.createRange();\r
333                 setStart = 'setStart' + (/end/i.test(where) ? 'After' : 'Before');\r
334                 if (hash[where]) {\r
335                     range[setStart](el);\r
336                     frag = range.createContextualFragment(html);\r
337                     el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);\r
338                     return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];\r
339                 } else {\r
340                     rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';\r
341                     if (el.firstChild) {\r
342                         range[setStart](el[rangeEl]);\r
343                         frag = range.createContextualFragment(html);\r
344                         if(where == afterbegin){\r
345                             el.insertBefore(frag, el.firstChild);\r
346                         }else{\r
347                             el.appendChild(frag);\r
348                         }\r
349                     } else {\r
350                         el.innerHTML = html;\r
351                     }\r
352                     return el[rangeEl];\r
353                 }\r
354             }\r
355             throw 'Illegal insertion point -> "' + where + '"';\r
356         },\r
357 \r
358         /**\r
359          * Creates new DOM element(s) and inserts them before el.\r
360          * @param {Mixed} el The context element\r
361          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
362          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
363          * @return {HTMLElement/Ext.Element} The new node\r
364          */\r
365         insertBefore : function(el, o, returnElement){\r
366             return doInsert(el, o, returnElement, beforebegin);\r
367         },\r
368 \r
369         /**\r
370          * Creates new DOM element(s) and inserts them after el.\r
371          * @param {Mixed} el The context element\r
372          * @param {Object} o The DOM object spec (and children)\r
373          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
374          * @return {HTMLElement/Ext.Element} The new node\r
375          */\r
376         insertAfter : function(el, o, returnElement){\r
377             return doInsert(el, o, returnElement, afterend, 'nextSibling');\r
378         },\r
379 \r
380         /**\r
381          * Creates new DOM element(s) and inserts them as the first child of el.\r
382          * @param {Mixed} el The context element\r
383          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
384          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
385          * @return {HTMLElement/Ext.Element} The new node\r
386          */\r
387         insertFirst : function(el, o, returnElement){\r
388             return doInsert(el, o, returnElement, afterbegin, 'firstChild');\r
389         },\r
390 \r
391         /**\r
392          * Creates new DOM element(s) and appends them to el.\r
393          * @param {Mixed} el The context element\r
394          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
395          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
396          * @return {HTMLElement/Ext.Element} The new node\r
397          */\r
398         append : function(el, o, returnElement){\r
399             return doInsert(el, o, returnElement, beforeend, '', true);\r
400         },\r
401 \r
402         /**\r
403          * Creates new DOM element(s) and overwrites the contents of el with them.\r
404          * @param {Mixed} el The context element\r
405          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
406          * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
407          * @return {HTMLElement/Ext.Element} The new node\r
408          */\r
409         overwrite : function(el, o, returnElement){\r
410             el = Ext.getDom(el);\r
411             el.innerHTML = createHtml(o);\r
412             return returnElement ? Ext.get(el.firstChild) : el.firstChild;\r
413         },\r
414 \r
415         createHtml : createHtml\r
416     };\r
417     return pub;\r
418 }();