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