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