commit extjs-2.2.1
[extjs.git] / source / core / DomHelper.js
1 /*\r
2  * Ext JS Library 2.2.1\r
3  * Copyright(c) 2006-2009, Ext JS, LLC.\r
4  * licensing@extjs.com\r
5  * \r
6  * http://extjs.com/license\r
7  */\r
8 \r
9 /**\r
10  * @class Ext.DomHelper\r
11  * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.<br>\r
12  * This is an example, where an unordered list with 5 children items is appended to an existing element with id 'my-div':<br>\r
13  <pre><code>\r
14 var dh = Ext.DomHelper;\r
15 var list = dh.append('my-div', {\r
16     id: 'my-ul', tag: 'ul', cls: 'my-list', children: [\r
17         {tag: 'li', id: 'item0', html: 'List Item 0'},\r
18         {tag: 'li', id: 'item1', html: 'List Item 1'},\r
19         {tag: 'li', id: 'item2', html: 'List Item 2'},\r
20         {tag: 'li', id: 'item3', html: 'List Item 3'},\r
21         {tag: 'li', id: 'item4', html: 'List Item 4'}\r
22     ]\r
23 });\r
24  </code></pre>\r
25  * <p>Element creation specification parameters in this class may also be passed as an Array of\r
26  * specification objects. This can be used to insert multiple sibling nodes into an existing\r
27  * container very efficiently. For example, to add more list items to the example above:<pre><code>\r
28 dh.append('my-ul', [\r
29     {tag: 'li', id: 'item5', html: 'List Item 5'},\r
30     {tag: 'li', id: 'item6', html: 'List Item 6'} ]);\r
31 </code></pre></p>\r
32  * <p>Element creation specification parameters may also be strings. If {@link useDom} is false, then the string is used\r
33  * as innerHTML. If {@link useDom} is true, a string specification results in the creation of a text node.</p>\r
34  * For more information and examples, see <a href="http://www.jackslocum.com/blog/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">the original blog post</a>.\r
35  * @singleton\r
36  */\r
37 Ext.DomHelper = function(){\r
38     var tempTableEl = null;\r
39     var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;\r
40     var tableRe = /^table|tbody|tr|td$/i;\r
41 \r
42     // build as innerHTML where available\r
43     var createHtml = function(o){\r
44         if(typeof o == 'string'){\r
45             return o;\r
46         }\r
47         var b = "";\r
48         if (Ext.isArray(o)) {\r
49             for (var i = 0, l = o.length; i < l; i++) {\r
50                 b += createHtml(o[i]);\r
51             }\r
52             return b;\r
53         }\r
54         if(!o.tag){\r
55             o.tag = "div";\r
56         }\r
57         b += "<" + o.tag;\r
58         for(var attr in o){\r
59             if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") continue;\r
60             if(attr == "style"){\r
61                 var s = o["style"];\r
62                 if(typeof s == "function"){\r
63                     s = s.call();\r
64                 }\r
65                 if(typeof s == "string"){\r
66                     b += ' style="' + s + '"';\r
67                 }else if(typeof s == "object"){\r
68                     b += ' style="';\r
69                     for(var key in s){\r
70                         if(typeof s[key] != "function"){\r
71                             b += key + ":" + s[key] + ";";\r
72                         }\r
73                     }\r
74                     b += '"';\r
75                 }\r
76             }else{\r
77                 if(attr == "cls"){\r
78                     b += ' class="' + o["cls"] + '"';\r
79                 }else if(attr == "htmlFor"){\r
80                     b += ' for="' + o["htmlFor"] + '"';\r
81                 }else{\r
82                     b += " " + attr + '="' + o[attr] + '"';\r
83                 }\r
84             }\r
85         }\r
86         if(emptyTags.test(o.tag)){\r
87             b += "/>";\r
88         }else{\r
89             b += ">";\r
90             var cn = o.children || o.cn;\r
91             if(cn){\r
92                 b += createHtml(cn);\r
93             } else if(o.html){\r
94                 b += o.html;\r
95             }\r
96             b += "</" + o.tag + ">";\r
97         }\r
98         return b;\r
99     };\r
100 \r
101     // build as dom\r
102     /** @ignore */\r
103     var createDom = function(o, parentNode){\r
104         var el;\r
105         if (Ext.isArray(o)) {                       // Allow Arrays of siblings to be inserted\r
106             el = document.createDocumentFragment(); // in one shot using a DocumentFragment\r
107             for(var i = 0, l = o.length; i < l; i++) {\r
108                 createDom(o[i], el);\r
109             }\r
110         } else if (typeof o == "string") {         // Allow a string as a child spec.\r
111             el = document.createTextNode(o);\r
112         } else {\r
113             el = document.createElement(o.tag||'div');\r
114             var useSet = !!el.setAttribute; // In IE some elements don't have setAttribute\r
115             for(var attr in o){\r
116                 if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || attr == "style" || typeof o[attr] == "function") continue;\r
117                 if(attr=="cls"){\r
118                     el.className = o["cls"];\r
119                 }else{\r
120                     if(useSet) el.setAttribute(attr, o[attr]);\r
121                     else el[attr] = o[attr];\r
122                 }\r
123             }\r
124             Ext.DomHelper.applyStyles(el, o.style);\r
125             var cn = o.children || o.cn;\r
126             if(cn){\r
127                 createDom(cn, el);\r
128             } else if(o.html){\r
129                 el.innerHTML = o.html;\r
130             }\r
131         }\r
132         if(parentNode){\r
133            parentNode.appendChild(el);\r
134         }\r
135         return el;\r
136     };\r
137 \r
138     var ieTable = function(depth, s, h, e){\r
139         tempTableEl.innerHTML = [s, h, e].join('');\r
140         var i = -1, el = tempTableEl;\r
141         while(++i < depth){\r
142             el = el.firstChild;\r
143         }\r
144         return el;\r
145     };\r
146 \r
147     // kill repeat to save bytes\r
148     var ts = '<table>',\r
149         te = '</table>',\r
150         tbs = ts+'<tbody>',\r
151         tbe = '</tbody>'+te,\r
152         trs = tbs + '<tr>',\r
153         tre = '</tr>'+tbe;\r
154 \r
155     /**\r
156      * @ignore\r
157      * Nasty code for IE's broken table implementation\r
158      */\r
159     var insertIntoTable = function(tag, where, el, html){\r
160         if(!tempTableEl){\r
161             tempTableEl = document.createElement('div');\r
162         }\r
163         var node;\r
164         var before = null;\r
165         if(tag == 'td'){\r
166             if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD\r
167                 return;\r
168             }\r
169             if(where == 'beforebegin'){\r
170                 before = el;\r
171                 el = el.parentNode;\r
172             } else{\r
173                 before = el.nextSibling;\r
174                 el = el.parentNode;\r
175             }\r
176             node = ieTable(4, trs, html, tre);\r
177         }\r
178         else if(tag == 'tr'){\r
179             if(where == 'beforebegin'){\r
180                 before = el;\r
181                 el = el.parentNode;\r
182                 node = ieTable(3, tbs, html, tbe);\r
183             } else if(where == 'afterend'){\r
184                 before = el.nextSibling;\r
185                 el = el.parentNode;\r
186                 node = ieTable(3, tbs, html, tbe);\r
187             } else{ // INTO a TR\r
188                 if(where == 'afterbegin'){\r
189                     before = el.firstChild;\r
190                 }\r
191                 node = ieTable(4, trs, html, tre);\r
192             }\r
193         } else if(tag == 'tbody'){\r
194             if(where == 'beforebegin'){\r
195                 before = el;\r
196                 el = el.parentNode;\r
197                 node = ieTable(2, ts, html, te);\r
198             } else if(where == 'afterend'){\r
199                 before = el.nextSibling;\r
200                 el = el.parentNode;\r
201                 node = ieTable(2, ts, html, te);\r
202             } else{\r
203                 if(where == 'afterbegin'){\r
204                     before = el.firstChild;\r
205                 }\r
206                 node = ieTable(3, tbs, html, tbe);\r
207             }\r
208         } else{ // TABLE\r
209             if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table\r
210                 return;\r
211             }\r
212             if(where == 'afterbegin'){\r
213                 before = el.firstChild;\r
214             }\r
215             node = ieTable(2, ts, html, te);\r
216         }\r
217         el.insertBefore(node, before);\r
218         return node;\r
219     };\r
220 \r
221 \r
222     return {\r
223     /** True to force the use of DOM instead of html fragments @type Boolean */\r
224     useDom : false,\r
225 \r
226     /**\r
227      * Returns the markup for the passed Element(s) config.\r
228      * @param {Object} o The DOM object spec (and children)\r
229      * @return {String}\r
230      */\r
231     markup : function(o){\r
232         return createHtml(o);\r
233     },\r
234 \r
235     /**\r
236      * Applies a style specification to an element.\r
237      * @param {String/HTMLElement} el The element to apply styles to\r
238      * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or\r
239      * a function which returns such a specification.\r
240      */\r
241     applyStyles : function(el, styles){\r
242         if(styles){\r
243            el = Ext.fly(el);\r
244            if(typeof styles == "string"){\r
245                var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;\r
246                var matches;\r
247                while ((matches = re.exec(styles)) != null){\r
248                    el.setStyle(matches[1], matches[2]);\r
249                }\r
250            }else if (typeof styles == "object"){\r
251                for (var style in styles){\r
252                   el.setStyle(style, styles[style]);\r
253                }\r
254            }else if (typeof styles == "function"){\r
255                 Ext.DomHelper.applyStyles(el, styles.call());\r
256            }\r
257         }\r
258     },\r
259 \r
260     /**\r
261      * Inserts an HTML fragment into the DOM.\r
262      * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.\r
263      * @param {HTMLElement} el The context element\r
264      * @param {String} html The HTML fragmenet\r
265      * @return {HTMLElement} The new node\r
266      */\r
267     insertHtml : function(where, el, html){\r
268         where = where.toLowerCase();\r
269         if(el.insertAdjacentHTML){\r
270             if(tableRe.test(el.tagName)){\r
271                 var rs;\r
272                 if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){\r
273                     return rs;\r
274                 }\r
275             }\r
276             switch(where){\r
277                 case "beforebegin":\r
278                     el.insertAdjacentHTML('BeforeBegin', html);\r
279                     return el.previousSibling;\r
280                 case "afterbegin":\r
281                     el.insertAdjacentHTML('AfterBegin', html);\r
282                     return el.firstChild;\r
283                 case "beforeend":\r
284                     el.insertAdjacentHTML('BeforeEnd', html);\r
285                     return el.lastChild;\r
286                 case "afterend":\r
287                     el.insertAdjacentHTML('AfterEnd', html);\r
288                     return el.nextSibling;\r
289             }\r
290             throw 'Illegal insertion point -> "' + where + '"';\r
291         }\r
292         var range = el.ownerDocument.createRange();\r
293         var frag;\r
294         switch(where){\r
295              case "beforebegin":\r
296                 range.setStartBefore(el);\r
297                 frag = range.createContextualFragment(html);\r
298                 el.parentNode.insertBefore(frag, el);\r
299                 return el.previousSibling;\r
300              case "afterbegin":\r
301                 if(el.firstChild){\r
302                     range.setStartBefore(el.firstChild);\r
303                     frag = range.createContextualFragment(html);\r
304                     el.insertBefore(frag, el.firstChild);\r
305                     return el.firstChild;\r
306                 }else{\r
307                     el.innerHTML = html;\r
308                     return el.firstChild;\r
309                 }\r
310             case "beforeend":\r
311                 if(el.lastChild){\r
312                     range.setStartAfter(el.lastChild);\r
313                     frag = range.createContextualFragment(html);\r
314                     el.appendChild(frag);\r
315                     return el.lastChild;\r
316                 }else{\r
317                     el.innerHTML = html;\r
318                     return el.lastChild;\r
319                 }\r
320             case "afterend":\r
321                 range.setStartAfter(el);\r
322                 frag = range.createContextualFragment(html);\r
323                 el.parentNode.insertBefore(frag, el.nextSibling);\r
324                 return el.nextSibling;\r
325             }\r
326             throw 'Illegal insertion point -> "' + where + '"';\r
327     },\r
328 \r
329     /**\r
330      * Creates new DOM element(s) and inserts them before el.\r
331      * @param {Mixed} el The context element\r
332      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
333      * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
334      * @return {HTMLElement/Ext.Element} The new node\r
335      */\r
336     insertBefore : function(el, o, returnElement){\r
337         return this.doInsert(el, o, returnElement, "beforeBegin");\r
338     },\r
339 \r
340     /**\r
341      * Creates new DOM element(s) and inserts them after el.\r
342      * @param {Mixed} el The context element\r
343      * @param {Object} o The DOM object spec (and children)\r
344      * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
345      * @return {HTMLElement/Ext.Element} The new node\r
346      */\r
347     insertAfter : function(el, o, returnElement){\r
348         return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");\r
349     },\r
350 \r
351     /**\r
352      * Creates new DOM element(s) and inserts them as the first child of el.\r
353      * @param {Mixed} el The context element\r
354      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
355      * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
356      * @return {HTMLElement/Ext.Element} The new node\r
357      */\r
358     insertFirst : function(el, o, returnElement){\r
359         return this.doInsert(el, o, returnElement, "afterBegin", "firstChild");\r
360     },\r
361 \r
362     // private\r
363     doInsert : function(el, o, returnElement, pos, sibling){\r
364         el = Ext.getDom(el);\r
365         var newNode;\r
366         if(this.useDom){\r
367             newNode = createDom(o, null);\r
368             (sibling === "firstChild" ? el : el.parentNode).insertBefore(newNode, sibling ? el[sibling] : el);\r
369         }else{\r
370             var html = createHtml(o);\r
371             newNode = this.insertHtml(pos, el, html);\r
372         }\r
373         return returnElement ? Ext.get(newNode, true) : newNode;\r
374     },\r
375 \r
376     /**\r
377      * Creates new DOM element(s) and appends them to el.\r
378      * @param {Mixed} el The context element\r
379      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
380      * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
381      * @return {HTMLElement/Ext.Element} The new node\r
382      */\r
383     append : function(el, o, returnElement){\r
384         el = Ext.getDom(el);\r
385         var newNode;\r
386         if(this.useDom){\r
387             newNode = createDom(o, null);\r
388             el.appendChild(newNode);\r
389         }else{\r
390             var html = createHtml(o);\r
391             newNode = this.insertHtml("beforeEnd", el, html);\r
392         }\r
393         return returnElement ? Ext.get(newNode, true) : newNode;\r
394     },\r
395 \r
396     /**\r
397      * Creates new DOM element(s) and overwrites the contents of el with them.\r
398      * @param {Mixed} el The context element\r
399      * @param {Object/String} o The DOM object spec (and children) or raw HTML blob\r
400      * @param {Boolean} returnElement (optional) true to return a Ext.Element\r
401      * @return {HTMLElement/Ext.Element} The new node\r
402      */\r
403     overwrite : function(el, o, returnElement){\r
404         el = Ext.getDom(el);\r
405         el.innerHTML = createHtml(o);\r
406         return returnElement ? Ext.get(el.firstChild, true) : el.firstChild;\r
407     },\r
408 \r
409     /**\r
410      * Creates a new Ext.Template from the DOM object spec.\r
411      * @param {Object} o The DOM object spec (and children)\r
412      * @return {Ext.Template} The new template\r
413      */\r
414     createTemplate : function(o){\r
415         var html = createHtml(o);\r
416         return new Ext.Template(html);\r
417     }\r
418     };\r
419 }();\r