roojs-core.js
[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 // nasty IE9 hack - what a pile of crap that is..
14
15  if (typeof Range != "undefined" && typeof Range.prototype.createContextualFragment == "undefined") {
16     Range.prototype.createContextualFragment = function (html) {
17         var doc = window.document;
18         var container = doc.createElement("div");
19         container.innerHTML = html;
20         var frag = doc.createDocumentFragment(), n;
21         while ((n = container.firstChild)) {
22             frag.appendChild(n);
23         }
24         return frag;
25     };
26 }
27
28 /**
29  * @class Roo.DomHelper
30  * Utility class for working with DOM and/or Templates. It transparently supports using HTML fragments or DOM.
31  * For more information see <a href="http://web.archive.org/web/20071221063734/http://www.jackslocum.com/blog/2006/10/06/domhelper-create-elements-using-dom-html-fragments-or-templates/">this blog post with examples</a>.
32  * @static
33  */
34 Roo.DomHelper = function(){
35     var tempTableEl = null;
36     var emptyTags = /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i;
37     var tableRe = /^table|tbody|tr|td$/i;
38     var xmlns = {};
39     // build as innerHTML where available
40     /** @ignore */
41     var createHtml = function(o){
42         if(typeof o == 'string'){
43             return o;
44         }
45         var b = "";
46         if(!o.tag){
47             o.tag = "div";
48         }
49         b += "<" + o.tag;
50         for(var attr in o){
51             if(attr == "tag" || attr == "children" || attr == "cn" || attr == "html" || typeof o[attr] == "function") { continue; }
52             if(attr == "style"){
53                 var s = o["style"];
54                 if(typeof s == "function"){
55                     s = s.call();
56                 }
57                 if(typeof s == "string"){
58                     b += ' style="' + s + '"';
59                 }else if(typeof s == "object"){
60                     b += ' style="';
61                     for(var key in s){
62                         if(typeof s[key] != "function"){
63                             b += key + ":" + s[key] + ";";
64                         }
65                     }
66                     b += '"';
67                 }
68             }else{
69                 if(attr == "cls"){
70                     b += ' class="' + o["cls"] + '"';
71                 }else if(attr == "htmlFor"){
72                     b += ' for="' + o["htmlFor"] + '"';
73                 }else{
74                     b += " " + attr + '="' + o[attr] + '"';
75                 }
76             }
77         }
78         if(emptyTags.test(o.tag)){
79             b += "/>";
80         }else{
81             b += ">";
82             var cn = o.children || o.cn;
83             if(cn){
84                 //http://bugs.kde.org/show_bug.cgi?id=71506
85                 if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
86                     for(var i = 0, len = cn.length; i < len; i++) {
87                         b += createHtml(cn[i], b);
88                     }
89                 }else{
90                     b += createHtml(cn, b);
91                 }
92             }
93             if(o.html){
94                 b += o.html;
95             }
96             b += "</" + o.tag + ">";
97         }
98         return b;
99     };
100
101     // build as dom
102     /** @ignore */
103     var createDom = function(o, parentNode){
104          
105         // defininition craeted..
106         var ns = false;
107         if (o.ns && o.ns != 'html') {
108                
109             if (o.xmlns && typeof(xmlns[o.ns]) == 'undefined') {
110                 xmlns[o.ns] = o.xmlns;
111                 ns = o.xmlns;
112             }
113             if (typeof(xmlns[o.ns]) == 'undefined') {
114                 console.log("Trying to create namespace element " + o.ns + ", however no xmlns was sent to builder previously");
115             }
116             ns = xmlns[o.ns];
117         }
118         
119         
120         if (typeof(o) == 'string') {
121             return parentNode.appendChild(document.createTextNode(o));
122         }
123         o.tag = o.tag || div;
124         if (o.ns && Roo.isIE) {
125             ns = false;
126             o.tag = o.ns + ':' + o.tag;
127             
128         }
129         var el = ns ? document.createElementNS( ns, o.tag||'div') :  document.createElement(o.tag||'div');
130         var useSet = el.setAttribute ? true : false; // In IE some elements don't have setAttribute
131         for(var attr in o){
132             
133             if(attr == "tag" || attr == "ns" ||attr == "xmlns" ||attr == "children" || attr == "cn" || attr == "html" || 
134                     attr == "style" || typeof o[attr] == "function") { continue; }
135                     
136             if(attr=="cls" && Roo.isIE){
137                 el.className = o["cls"];
138             }else{
139                 if(useSet) { el.setAttribute(attr=="cls" ? 'class' : attr, o[attr]);}
140                 else { 
141                     el[attr] = o[attr];
142                 }
143             }
144         }
145         Roo.DomHelper.applyStyles(el, o.style);
146         var cn = o.children || o.cn;
147         if(cn){
148             //http://bugs.kde.org/show_bug.cgi?id=71506
149              if((cn instanceof Array) || (Roo.isSafari && typeof(cn.join) == "function")){
150                 for(var i = 0, len = cn.length; i < len; i++) {
151                     createDom(cn[i], el);
152                 }
153             }else{
154                 createDom(cn, el);
155             }
156         }
157         if(o.html){
158             el.innerHTML = o.html;
159         }
160         if(parentNode){
161            parentNode.appendChild(el);
162         }
163         return el;
164     };
165
166     var ieTable = function(depth, s, h, e){
167         tempTableEl.innerHTML = [s, h, e].join('');
168         var i = -1, el = tempTableEl;
169         while(++i < depth && el.firstChild){
170             el = el.firstChild;
171         }
172         return el;
173     };
174
175     // kill repeat to save bytes
176     var ts = '<table>',
177         te = '</table>',
178         tbs = ts+'<tbody>',
179         tbe = '</tbody>'+te,
180         trs = tbs + '<tr>',
181         tre = '</tr>'+tbe;
182
183     /**
184      * @ignore
185      * Nasty code for IE's broken table implementation
186      */
187     var insertIntoTable = function(tag, where, el, html){
188         if(!tempTableEl){
189             tempTableEl = document.createElement('div');
190         }
191         var node;
192         var before = null;
193         if(tag == 'td'){
194             if(where == 'afterbegin' || where == 'beforeend'){ // INTO a TD
195                 return;
196             }
197             if(where == 'beforebegin'){
198                 before = el;
199                 el = el.parentNode;
200             } else{
201                 before = el.nextSibling;
202                 el = el.parentNode;
203             }
204             node = ieTable(4, trs, html, tre);
205         }
206         else if(tag == 'tr'){
207             if(where == 'beforebegin'){
208                 before = el;
209                 el = el.parentNode;
210                 node = ieTable(3, tbs, html, tbe);
211             } else if(where == 'afterend'){
212                 before = el.nextSibling;
213                 el = el.parentNode;
214                 node = ieTable(3, tbs, html, tbe);
215             } else{ // INTO a TR
216                 if(where == 'afterbegin'){
217                     before = el.firstChild;
218                 }
219                 node = ieTable(4, trs, html, tre);
220             }
221         } else if(tag == 'tbody'){
222             if(where == 'beforebegin'){
223                 before = el;
224                 el = el.parentNode;
225                 node = ieTable(2, ts, html, te);
226             } else if(where == 'afterend'){
227                 before = el.nextSibling;
228                 el = el.parentNode;
229                 node = ieTable(2, ts, html, te);
230             } else{
231                 if(where == 'afterbegin'){
232                     before = el.firstChild;
233                 }
234                 node = ieTable(3, tbs, html, tbe);
235             }
236         } else{ // TABLE
237             if(where == 'beforebegin' || where == 'afterend'){ // OUTSIDE the table
238                 return;
239             }
240             if(where == 'afterbegin'){
241                 before = el.firstChild;
242             }
243             node = ieTable(2, ts, html, te);
244         }
245         el.insertBefore(node, before);
246         return node;
247     };
248     
249     // this is a bit like the react update code...
250     // 
251     
252     var updateNode = function(from, to)
253     {
254         // should we handle non-standard elements?
255         Roo.log(["UpdateNode" , from, to]);
256         if (from.nodeType != to.nodeType) {
257             Roo.log(["ReplaceChild - mismatch notType" , to, from ]);
258             from.parentNode.replaceChild(to, from);
259         }
260         
261         if (from.nodeType == 3) {
262             // assume it's text?!
263             if (from.data == to.data) {
264                 return;
265             }
266             from.data = to.data;
267             return;
268         }
269         if (!from.parentNode) {
270             // not sure why this is happening?
271             return;
272         }
273         // assume 'to' doesnt have '1/3 nodetypes!
274         // not sure why, by from, parent node might not exist?
275         if (from.nodeType !=1 || from.tagName != to.tagName) {
276             Roo.log(["ReplaceChild" , from, to ]);
277             
278             from.parentNode.replaceChild(to, from);
279             return;
280         }
281         // compare attributes
282         var ar = Array.from(from.attributes);
283         for(var i = 0; i< ar.length;i++) {
284             if (to.hasAttribute(ar[i].name)) {
285                 continue;
286             }
287             if (ar[i].name == 'id') { // always keep ids?
288                continue;
289             }
290             //if (ar[i].name == 'style') {
291             //   throw "style removed?";
292             //}
293             Roo.log("removeAttribute" + ar[i].name);
294             from.removeAttribute(ar[i].name);
295         }
296         ar = to.attributes;
297         for(var i = 0; i< ar.length;i++) {
298             if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
299                 Roo.log("skipAttribute " + ar[i].name  + '=' + to.getAttribute(ar[i].name));
300                 continue;
301             }
302             Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
303             from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
304         }
305         // children
306         var far = Array.from(from.childNodes);
307         var tar = Array.from(to.childNodes);
308         // if the lengths are different.. then it's probably a editable content change, rather than
309         // a change of the block definition..
310         
311         // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
312          /*if (from.innerHTML == to.innerHTML) {
313             return;
314         }
315         if (far.length != tar.length) {
316             from.innerHTML = to.innerHTML;
317             return;
318         }
319         */
320         
321         for(var i = 0; i < Math.max(tar.length, far.length); i++) {
322             if (i >= far.length) {
323                 from.appendChild(tar[i]);
324                 Roo.log(["add", tar[i]]);
325                 
326             } else if ( i  >= tar.length) {
327                 from.removeChild(far[i]);
328                 Roo.log(["remove", far[i]]);
329             } else {
330                 
331                 updateNode(far[i], tar[i]);
332             }    
333         }
334         
335         
336         
337         
338     };
339     
340     
341
342     return {
343         /** True to force the use of DOM instead of html fragments @type Boolean */
344         useDom : false,
345     
346         /**
347          * Returns the markup for the passed Element(s) config
348          * @param {Object} o The Dom object spec (and children)
349          * @return {String}
350          */
351         markup : function(o){
352             return createHtml(o);
353         },
354     
355         /**
356          * Applies a style specification to an element
357          * @param {String/HTMLElement} el The element to apply styles to
358          * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
359          * a function which returns such a specification.
360          */
361         applyStyles : function(el, styles){
362             if(styles){
363                el = Roo.fly(el);
364                if(typeof styles == "string"){
365                    var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
366                    var matches;
367                    while ((matches = re.exec(styles)) != null){
368                        el.setStyle(matches[1], matches[2]);
369                    }
370                }else if (typeof styles == "object"){
371                    for (var style in styles){
372                       el.setStyle(style, styles[style]);
373                    }
374                }else if (typeof styles == "function"){
375                     Roo.DomHelper.applyStyles(el, styles.call());
376                }
377             }
378         },
379     
380         /**
381          * Inserts an HTML fragment into the Dom
382          * @param {String} where Where to insert the html in relation to el - beforeBegin, afterBegin, beforeEnd, afterEnd.
383          * @param {HTMLElement} el The context element
384          * @param {String} html The HTML fragmenet
385          * @return {HTMLElement} The new node
386          */
387         insertHtml : function(where, el, html){
388             where = where.toLowerCase();
389             if(el.insertAdjacentHTML){
390                 if(tableRe.test(el.tagName)){
391                     var rs;
392                     if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
393                         return rs;
394                     }
395                 }
396                 switch(where){
397                     case "beforebegin":
398                         el.insertAdjacentHTML('BeforeBegin', html);
399                         return el.previousSibling;
400                     case "afterbegin":
401                         el.insertAdjacentHTML('AfterBegin', html);
402                         return el.firstChild;
403                     case "beforeend":
404                         el.insertAdjacentHTML('BeforeEnd', html);
405                         return el.lastChild;
406                     case "afterend":
407                         el.insertAdjacentHTML('AfterEnd', html);
408                         return el.nextSibling;
409                 }
410                 throw 'Illegal insertion point -> "' + where + '"';
411             }
412             var range = el.ownerDocument.createRange();
413             var frag;
414             switch(where){
415                  case "beforebegin":
416                     range.setStartBefore(el);
417                     frag = range.createContextualFragment(html);
418                     el.parentNode.insertBefore(frag, el);
419                     return el.previousSibling;
420                  case "afterbegin":
421                     if(el.firstChild){
422                         range.setStartBefore(el.firstChild);
423                         frag = range.createContextualFragment(html);
424                         el.insertBefore(frag, el.firstChild);
425                         return el.firstChild;
426                     }else{
427                         el.innerHTML = html;
428                         return el.firstChild;
429                     }
430                 case "beforeend":
431                     if(el.lastChild){
432                         range.setStartAfter(el.lastChild);
433                         frag = range.createContextualFragment(html);
434                         el.appendChild(frag);
435                         return el.lastChild;
436                     }else{
437                         el.innerHTML = html;
438                         return el.lastChild;
439                     }
440                 case "afterend":
441                     range.setStartAfter(el);
442                     frag = range.createContextualFragment(html);
443                     el.parentNode.insertBefore(frag, el.nextSibling);
444                     return el.nextSibling;
445                 }
446                 throw 'Illegal insertion point -> "' + where + '"';
447         },
448     
449         /**
450          * Creates new Dom element(s) and inserts them before el
451          * @param {String/HTMLElement/Element} el The context element
452          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
453          * @param {Boolean} returnElement (optional) true to return a Roo.Element
454          * @return {HTMLElement/Roo.Element} The new node
455          */
456         insertBefore : function(el, o, returnElement){
457             return this.doInsert(el, o, returnElement, "beforeBegin");
458         },
459     
460         /**
461          * Creates new Dom element(s) and inserts them after el
462          * @param {String/HTMLElement/Element} el The context element
463          * @param {Object} o The Dom object spec (and children)
464          * @param {Boolean} returnElement (optional) true to return a Roo.Element
465          * @return {HTMLElement/Roo.Element} The new node
466          */
467         insertAfter : function(el, o, returnElement){
468             return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
469         },
470     
471         /**
472          * Creates new Dom element(s) and inserts them as the first child of el
473          * @param {String/HTMLElement/Element} el The context element
474          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
475          * @param {Boolean} returnElement (optional) true to return a Roo.Element
476          * @return {HTMLElement/Roo.Element} The new node
477          */
478         insertFirst : function(el, o, returnElement){
479             return this.doInsert(el, o, returnElement, "afterBegin");
480         },
481     
482         // private
483         doInsert : function(el, o, returnElement, pos, sibling){
484             el = Roo.getDom(el);
485             var newNode;
486             if(this.useDom || o.ns){
487                 newNode = createDom(o, null);
488                 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
489             }else{
490                 var html = createHtml(o);
491                 newNode = this.insertHtml(pos, el, html);
492             }
493             return returnElement ? Roo.get(newNode, true) : newNode;
494         },
495     
496         /**
497          * Creates new Dom element(s) and appends them to el
498          * @param {String/HTMLElement/Element} el The context element
499          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
500          * @param {Boolean} returnElement (optional) true to return a Roo.Element
501          * @return {HTMLElement/Roo.Element} The new node
502          */
503         append : function(el, o, returnElement){
504             el = Roo.getDom(el);
505             var newNode;
506             if(this.useDom || o.ns){
507                 newNode = createDom(o, null);
508                 el.appendChild(newNode);
509             }else{
510                 var html = createHtml(o);
511                 newNode = this.insertHtml("beforeEnd", el, html);
512             }
513             return returnElement ? Roo.get(newNode, true) : newNode;
514         },
515     
516         /**
517          * Creates new Dom element(s) and overwrites the contents of el with them
518          * @param {String/HTMLElement/Element} el The context element
519          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
520          * @param {Boolean} returnElement (optional) true to return a Roo.Element
521          * @return {HTMLElement/Roo.Element} The new node
522          */
523         overwrite : function(el, o, returnElement)
524         {
525             el = Roo.getDom(el);
526             if (o.ns) {
527               
528                 while (el.childNodes.length) {
529                     el.removeChild(el.firstChild);
530                 }
531                 createDom(o, el);
532             } else {
533                 el.innerHTML = createHtml(o);   
534             }
535             
536             return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
537         },
538     
539         /**
540          * Creates a new Roo.DomHelper.Template from the Dom object spec
541          * @param {Object} o The Dom object spec (and children)
542          * @return {Roo.DomHelper.Template} The new template
543          */
544         createTemplate : function(o){
545             var html = createHtml(o);
546             return new Roo.Template(html);
547         },
548          /**
549          * Updates the first element with the spec from the o (replacing if necessary)
550          * This iterates through the children, and updates attributes / children etc..
551          * @param {String/HTMLElement/Element} el The context element
552          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
553          */
554         
555         update : function(el, o)
556         {
557             updateNode(Roo.getDom(el), createDom(o));
558             
559         }
560         
561         
562     };
563 }();