Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / core / src / dom / DomHelper.js
1 /**
2  * @class Ext.core.DomHelper
3  * <p>The DomHelper class provides a layer of abstraction from DOM and transparently supports creating
4  * elements via DOM or using HTML fragments. It also has the ability to create HTML fragment templates
5  * from your DOM building code.</p>
6  *
7  * <p><b><u>DomHelper element specification object</u></b></p>
8  * <p>A specification object is used when creating elements. Attributes of this object
9  * are assumed to be element attributes, except for 4 special attributes:
10  * <div class="mdetail-params"><ul>
11  * <li><b><tt>tag</tt></b> : <div class="sub-desc">The tag name of the element</div></li>
12  * <li><b><tt>children</tt></b> : or <tt>cn</tt><div class="sub-desc">An array of the
13  * same kind of element definition objects to be created and appended. These can be nested
14  * as deep as you want.</div></li>
15  * <li><b><tt>cls</tt></b> : <div class="sub-desc">The class attribute of the element.
16  * This will end up being either the "class" attribute on a HTML fragment or className
17  * for a DOM node, depending on whether DomHelper is using fragments or DOM.</div></li>
18  * <li><b><tt>html</tt></b> : <div class="sub-desc">The innerHTML for the element</div></li>
19  * </ul></div></p>
20  * <p><b>NOTE:</b> For other arbitrary attributes, the value will currently <b>not</b> be automatically
21  * HTML-escaped prior to building the element's HTML string. This means that if your attribute value
22  * contains special characters that would not normally be allowed in a double-quoted attribute value,
23  * you <b>must</b> manually HTML-encode it beforehand (see {@link Ext.String#htmlEncode}) or risk
24  * malformed HTML being created. This behavior may change in a future release.</p>
25  *
26  * <p><b><u>Insertion methods</u></b></p>
27  * <p>Commonly used insertion methods:
28  * <div class="mdetail-params"><ul>
29  * <li><b><tt>{@link #append}</tt></b> : <div class="sub-desc"></div></li>
30  * <li><b><tt>{@link #insertBefore}</tt></b> : <div class="sub-desc"></div></li>
31  * <li><b><tt>{@link #insertAfter}</tt></b> : <div class="sub-desc"></div></li>
32  * <li><b><tt>{@link #overwrite}</tt></b> : <div class="sub-desc"></div></li>
33  * <li><b><tt>{@link #createTemplate}</tt></b> : <div class="sub-desc"></div></li>
34  * <li><b><tt>{@link #insertHtml}</tt></b> : <div class="sub-desc"></div></li>
35  * </ul></div></p>
36  *
37  * <p><b><u>Example</u></b></p>
38  * <p>This is an example, where an unordered list with 3 children items is appended to an existing
39  * element with id <tt>'my-div'</tt>:<br>
40  <pre><code>
41 var dh = Ext.core.DomHelper; // create shorthand alias
42 // specification object
43 var spec = {
44     id: 'my-ul',
45     tag: 'ul',
46     cls: 'my-list',
47     // append children after creating
48     children: [     // may also specify 'cn' instead of 'children'
49         {tag: 'li', id: 'item0', html: 'List Item 0'},
50         {tag: 'li', id: 'item1', html: 'List Item 1'},
51         {tag: 'li', id: 'item2', html: 'List Item 2'}
52     ]
53 };
54 var list = dh.append(
55     'my-div', // the context element 'my-div' can either be the id or the actual node
56     spec      // the specification object
57 );
58  </code></pre></p>
59  * <p>Element creation specification parameters in this class may also be passed as an Array of
60  * specification objects. This can be used to insert multiple sibling nodes into an existing
61  * container very efficiently. For example, to add more list items to the example above:<pre><code>
62 dh.append('my-ul', [
63     {tag: 'li', id: 'item3', html: 'List Item 3'},
64     {tag: 'li', id: 'item4', html: 'List Item 4'}
65 ]);
66  * </code></pre></p>
67  *
68  * <p><b><u>Templating</u></b></p>
69  * <p>The real power is in the built-in templating. Instead of creating or appending any elements,
70  * <tt>{@link #createTemplate}</tt> returns a Template object which can be used over and over to
71  * insert new elements. Revisiting the example above, we could utilize templating this time:
72  * <pre><code>
73 // create the node
74 var list = dh.append('my-div', {tag: 'ul', cls: 'my-list'});
75 // get template
76 var tpl = dh.createTemplate({tag: 'li', id: 'item{0}', html: 'List Item {0}'});
77
78 for(var i = 0; i < 5, i++){
79     tpl.append(list, [i]); // use template to append to the actual node
80 }
81  * </code></pre></p>
82  * <p>An example using a template:<pre><code>
83 var html = '<a id="{0}" href="{1}" class="nav">{2}</a>';
84
85 var tpl = new Ext.core.DomHelper.createTemplate(html);
86 tpl.append('blog-roll', ['link1', 'http://www.edspencer.net/', "Ed&#39;s Site"]);
87 tpl.append('blog-roll', ['link2', 'http://www.dustindiaz.com/', "Dustin&#39;s Site"]);
88  * </code></pre></p>
89  *
90  * <p>The same example using named parameters:<pre><code>
91 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
92
93 var tpl = new Ext.core.DomHelper.createTemplate(html);
94 tpl.append('blog-roll', {
95     id: 'link1',
96     url: 'http://www.edspencer.net/',
97     text: "Ed&#39;s Site"
98 });
99 tpl.append('blog-roll', {
100     id: 'link2',
101     url: 'http://www.dustindiaz.com/',
102     text: "Dustin&#39;s Site"
103 });
104  * </code></pre></p>
105  *
106  * <p><b><u>Compiling Templates</u></b></p>
107  * <p>Templates are applied using regular expressions. The performance is great, but if
108  * you are adding a bunch of DOM elements using the same template, you can increase
109  * performance even further by {@link Ext.Template#compile "compiling"} the template.
110  * The way "{@link Ext.Template#compile compile()}" works is the template is parsed and
111  * broken up at the different variable points and a dynamic function is created and eval'ed.
112  * The generated function performs string concatenation of these parts and the passed
113  * variables instead of using regular expressions.
114  * <pre><code>
115 var html = '<a id="{id}" href="{url}" class="nav">{text}</a>';
116
117 var tpl = new Ext.core.DomHelper.createTemplate(html);
118 tpl.compile();
119
120 //... use template like normal
121  * </code></pre></p>
122  *
123  * <p><b><u>Performance Boost</u></b></p>
124  * <p>DomHelper will transparently create HTML fragments when it can. Using HTML fragments instead
125  * of DOM can significantly boost performance.</p>
126  * <p>Element creation specification parameters may also be strings. If {@link #useDom} is <tt>false</tt>,
127  * then the string is used as innerHTML. If {@link #useDom} is <tt>true</tt>, a string specification
128  * results in the creation of a text node. Usage:</p>
129  * <pre><code>
130 Ext.core.DomHelper.useDom = true; // force it to use DOM; reduces performance
131  * </code></pre>
132  * @singleton
133  */
134 Ext.ns('Ext.core');
135 Ext.core.DomHelper = function(){
136     var tempTableEl = null,
137         emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,
138         tableRe = /^table|tbody|tr|td$/i,
139         confRe = /tag|children|cn|html$/i,
140         tableElRe = /td|tr|tbody/i,
141         endRe = /end/i,
142         pub,
143         // kill repeat to save bytes
144         afterbegin = 'afterbegin',
145         afterend = 'afterend',
146         beforebegin = 'beforebegin',
147         beforeend = 'beforeend',
148         ts = '<table>',
149         te = '</table>',
150         tbs = ts+'<tbody>',
151         tbe = '</tbody>'+te,
152         trs = tbs + '<tr>',
153         tre = '</tr>'+tbe;
154
155     // private
156     function doInsert(el, o, returnElement, pos, sibling, append){
157         el = Ext.getDom(el);
158         var newNode;
159         if (pub.useDom) {
160             newNode = createDom(o, null);
161             if (append) {
162                 el.appendChild(newNode);
163             } else {
164                 (sibling == 'firstChild' ? el : el.parentNode).insertBefore(newNode, el[sibling] || el);
165             }
166         } else {
167             newNode = Ext.core.DomHelper.insertHtml(pos, el, Ext.core.DomHelper.createHtml(o));
168         }
169         return returnElement ? Ext.get(newNode, true) : newNode;
170     }
171     
172     function createDom(o, parentNode){
173         var el,
174             doc = document,
175             useSet,
176             attr,
177             val,
178             cn;
179
180         if (Ext.isArray(o)) {                       // Allow Arrays of siblings to be inserted
181             el = doc.createDocumentFragment(); // in one shot using a DocumentFragment
182             for (var i = 0, l = o.length; i < l; i++) {
183                 createDom(o[i], el);
184             }
185         } else if (typeof o == 'string') {         // Allow a string as a child spec.
186             el = doc.createTextNode(o);
187         } else {
188             el = doc.createElement( o.tag || 'div' );
189             useSet = !!el.setAttribute; // In IE some elements don't have setAttribute
190             for (attr in o) {
191                 if(!confRe.test(attr)){
192                     val = o[attr];
193                     if(attr == 'cls'){
194                         el.className = val;
195                     }else{
196                         if(useSet){
197                             el.setAttribute(attr, val);
198                         }else{
199                             el[attr] = val;
200                         }
201                     }
202                 }
203             }
204             Ext.core.DomHelper.applyStyles(el, o.style);
205
206             if ((cn = o.children || o.cn)) {
207                 createDom(cn, el);
208             } else if (o.html) {
209                 el.innerHTML = o.html;
210             }
211         }
212         if(parentNode){
213            parentNode.appendChild(el);
214         }
215         return el;
216     }
217
218     // build as innerHTML where available
219     function createHtml(o){
220         var b = '',
221             attr,
222             val,
223             key,
224             cn,
225             i;
226
227         if(typeof o == "string"){
228             b = o;
229         } else if (Ext.isArray(o)) {
230             for (i=0; i < o.length; i++) {
231                 if(o[i]) {
232                     b += createHtml(o[i]);
233                 }
234             }
235         } else {
236             b += '<' + (o.tag = o.tag || 'div');
237             for (attr in o) {
238                 val = o[attr];
239                 if(!confRe.test(attr)){
240                     if (typeof val == "object") {
241                         b += ' ' + attr + '="';
242                         for (key in val) {
243                             b += key + ':' + val[key] + ';';
244                         }
245                         b += '"';
246                     }else{
247                         b += ' ' + ({cls : 'class', htmlFor : 'for'}[attr] || attr) + '="' + val + '"';
248                     }
249                 }
250             }
251             // Now either just close the tag or try to add children and close the tag.
252             if (emptyTags.test(o.tag)) {
253                 b += '/>';
254             } else {
255                 b += '>';
256                 if ((cn = o.children || o.cn)) {
257                     b += createHtml(cn);
258                 } else if(o.html){
259                     b += o.html;
260                 }
261                 b += '</' + o.tag + '>';
262             }
263         }
264         return b;
265     }
266
267     function ieTable(depth, s, h, e){
268         tempTableEl.innerHTML = [s, h, e].join('');
269         var i = -1,
270             el = tempTableEl,
271             ns;
272         while(++i < depth){
273             el = el.firstChild;
274         }
275 //      If the result is multiple siblings, then encapsulate them into one fragment.
276         ns = el.nextSibling;
277         if (ns){
278             var df = document.createDocumentFragment();
279             while(el){
280                 ns = el.nextSibling;
281                 df.appendChild(el);
282                 el = ns;
283             }
284             el = df;
285         }
286         return el;
287     }
288
289     /**
290      * @ignore
291      * Nasty code for IE's broken table implementation
292      */
293     function insertIntoTable(tag, where, el, html) {
294         var node,
295             before;
296
297         tempTableEl = tempTableEl || document.createElement('div');
298
299         if(tag == 'td' && (where == afterbegin || where == beforeend) ||
300            !tableElRe.test(tag) && (where == beforebegin || where == afterend)) {
301             return null;
302         }
303         before = where == beforebegin ? el :
304                  where == afterend ? el.nextSibling :
305                  where == afterbegin ? el.firstChild : null;
306
307         if (where == beforebegin || where == afterend) {
308             el = el.parentNode;
309         }
310
311         if (tag == 'td' || (tag == 'tr' && (where == beforeend || where == afterbegin))) {
312             node = ieTable(4, trs, html, tre);
313         } else if ((tag == 'tbody' && (where == beforeend || where == afterbegin)) ||
314                    (tag == 'tr' && (where == beforebegin || where == afterend))) {
315             node = ieTable(3, tbs, html, tbe);
316         } else {
317             node = ieTable(2, ts, html, te);
318         }
319         el.insertBefore(node, before);
320         return node;
321     }
322     
323     /**
324      * @ignore
325      * Fix for IE9 createContextualFragment missing method
326      */   
327     function createContextualFragment(html){
328         var div = document.createElement("div"),
329             fragment = document.createDocumentFragment(),
330             i = 0,
331             length, childNodes;
332         
333         div.innerHTML = html;
334         childNodes = div.childNodes;
335         length = childNodes.length;
336
337         for (; i < length; i++) {
338             fragment.appendChild(childNodes[i].cloneNode(true));
339         }
340
341         return fragment;
342     }
343     
344     pub = {
345         /**
346          * Returns the markup for the passed Element(s) config.
347          * @param {Object} o The DOM object spec (and children)
348          * @return {String}
349          */
350         markup : function(o){
351             return createHtml(o);
352         },
353
354         /**
355          * Applies a style specification to an element.
356          * @param {String/HTMLElement} el The element to apply styles to
357          * @param {String/Object/Function} styles A style specification string e.g. 'width:100px', or object in the form {width:'100px'}, or
358          * a function which returns such a specification.
359          */
360         applyStyles : function(el, styles){
361             if (styles) {
362                 el = Ext.fly(el);
363                 if (typeof styles == "function") {
364                     styles = styles.call();
365                 }
366                 if (typeof styles == "string") {
367                     styles = Ext.core.Element.parseStyles(styles);
368                 }
369                 if (typeof styles == "object") {
370                     el.setStyle(styles);
371                 }
372             }
373         },
374
375         /**
376          * Inserts an HTML fragment into the DOM.
377          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
378          * @param {HTMLElement/TextNode} el The context element
379          * @param {String} html The HTML fragment
380          * @return {HTMLElement} The new node
381          */
382         insertHtml : function(where, el, html){
383             var hash = {},
384                 hashVal,
385                 range,
386                 rangeEl,
387                 setStart,
388                 frag,
389                 rs;
390
391             where = where.toLowerCase();
392             // add these here because they are used in both branches of the condition.
393             hash[beforebegin] = ['BeforeBegin', 'previousSibling'];
394             hash[afterend] = ['AfterEnd', 'nextSibling'];
395             
396             // if IE and context element is an HTMLElement
397             if (el.insertAdjacentHTML) {
398                 if(tableRe.test(el.tagName) && (rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html))){
399                     return rs;
400                 }
401                 
402                 // add these two to the hash.
403                 hash[afterbegin] = ['AfterBegin', 'firstChild'];
404                 hash[beforeend] = ['BeforeEnd', 'lastChild'];
405                 if ((hashVal = hash[where])) {
406                     el.insertAdjacentHTML(hashVal[0], html);
407                     return el[hashVal[1]];
408                 }
409             // if (not IE and context element is an HTMLElement) or TextNode
410             } else {
411                 // we cannot insert anything inside a textnode so...
412                 if (Ext.isTextNode(el)) {
413                     where = where === 'afterbegin' ? 'beforebegin' : where; 
414                     where = where === 'beforeend' ? 'afterend' : where;
415                 }
416                 range = Ext.supports.CreateContextualFragment ? el.ownerDocument.createRange() : undefined;
417                 setStart = 'setStart' + (endRe.test(where) ? 'After' : 'Before');
418                 if (hash[where]) {
419                     if (range) {
420                         range[setStart](el);
421                         frag = range.createContextualFragment(html);
422                     } else {
423                         frag = createContextualFragment(html);
424                     }
425                     el.parentNode.insertBefore(frag, where == beforebegin ? el : el.nextSibling);
426                     return el[(where == beforebegin ? 'previous' : 'next') + 'Sibling'];
427                 } else {
428                     rangeEl = (where == afterbegin ? 'first' : 'last') + 'Child';
429                     if (el.firstChild) {
430                         if (range) {
431                             range[setStart](el[rangeEl]);
432                             frag = range.createContextualFragment(html);
433                         } else {
434                             frag = createContextualFragment(html);
435                         }
436                         
437                         if(where == afterbegin){
438                             el.insertBefore(frag, el.firstChild);
439                         }else{
440                             el.appendChild(frag);
441                         }
442                     } else {
443                         el.innerHTML = html;
444                     }
445                     return el[rangeEl];
446                 }
447             }
448             //<debug>
449             Ext.Error.raise({
450                 sourceClass: 'Ext.core.DomHelper',
451                 sourceMethod: 'insertHtml',
452                 htmlToInsert: html,
453                 targetElement: el,
454                 msg: 'Illegal insertion point reached: "' + where + '"'
455             });
456             //</debug>
457         },
458
459         /**
460          * Creates new DOM element(s) and inserts them before el.
461          * @param {Mixed} el The context element
462          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
463          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
464          * @return {HTMLElement/Ext.core.Element} The new node
465          */
466         insertBefore : function(el, o, returnElement){
467             return doInsert(el, o, returnElement, beforebegin);
468         },
469
470         /**
471          * Creates new DOM element(s) and inserts them after el.
472          * @param {Mixed} el The context element
473          * @param {Object} o The DOM object spec (and children)
474          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
475          * @return {HTMLElement/Ext.core.Element} The new node
476          */
477         insertAfter : function(el, o, returnElement){
478             return doInsert(el, o, returnElement, afterend, 'nextSibling');
479         },
480
481         /**
482          * Creates new DOM element(s) and inserts them as the first child of el.
483          * @param {Mixed} el The context element
484          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
485          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
486          * @return {HTMLElement/Ext.core.Element} The new node
487          */
488         insertFirst : function(el, o, returnElement){
489             return doInsert(el, o, returnElement, afterbegin, 'firstChild');
490         },
491
492         /**
493          * Creates new DOM element(s) and appends them to el.
494          * @param {Mixed} el The context element
495          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
496          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
497          * @return {HTMLElement/Ext.core.Element} The new node
498          */
499         append : function(el, o, returnElement){
500             return doInsert(el, o, returnElement, beforeend, '', true);
501         },
502
503         /**
504          * Creates new DOM element(s) and overwrites the contents of el with them.
505          * @param {Mixed} el The context element
506          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
507          * @param {Boolean} returnElement (optional) true to return a Ext.core.Element
508          * @return {HTMLElement/Ext.core.Element} The new node
509          */
510         overwrite : function(el, o, returnElement){
511             el = Ext.getDom(el);
512             el.innerHTML = createHtml(o);
513             return returnElement ? Ext.get(el.firstChild) : el.firstChild;
514         },
515
516         createHtml : createHtml,
517         
518         /**
519          * Creates new DOM element(s) without inserting them to the document.
520          * @param {Object/String} o The DOM object spec (and children) or raw HTML blob
521          * @return {HTMLElement} The new uninserted node
522          * @method
523          */
524         createDom: createDom,
525         
526         /** True to force the use of DOM instead of html fragments @type Boolean */
527         useDom : false,
528         
529         /**
530          * Creates a new Ext.Template from the DOM object spec.
531          * @param {Object} o The DOM object spec (and children)
532          * @return {Ext.Template} The new template
533          */
534         createTemplate : function(o){
535             var html = Ext.core.DomHelper.createHtml(o);
536             return Ext.create('Ext.Template', html);
537         }
538     };
539     return pub;
540 }();