Roo/htmleditor/BlockTd.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         
270         // assume 'to' doesnt have '1/3 nodetypes!
271         if (from.nodeType !=1 || from.tagName != to.tagName) {
272             Roo.log(["ReplaceChild" , from, to ]);
273             from.parentNode.replaceChild(to, from);
274             return;
275         }
276         // compare attributes
277         var ar = Array.from(from.attributes);
278         for(var i = 0; i< ar.length;i++) {
279             if (to.hasAttribute(ar[i].name)) {
280                 continue;
281             }
282             if (ar[i].name == 'id') { // always keep ids?
283                continue;
284             }
285             //if (ar[i].name == 'style') {
286             //   throw "style removed?";
287             //}
288             Roo.log("removeAttribute" + ar[i].name);
289             from.removeAttribute(ar[i].name);
290         }
291         ar = to.attributes;
292         for(var i = 0; i< ar.length;i++) {
293             if (from.getAttribute(ar[i].name) == to.getAttribute(ar[i].name)) {
294                 Roo.log("skipAttribute " + ar[i].name  + '=' + to.getAttribute(ar[i].name));
295                 continue;
296             }
297             Roo.log("updateAttribute " + ar[i].name + '=>' + to.getAttribute(ar[i].name));
298             from.setAttribute(ar[i].name, to.getAttribute(ar[i].name));
299         }
300         // children
301         var far = Array.from(from.childNodes);
302         var tar = Array.from(to.childNodes);
303         // if the lengths are different.. then it's probably a editable content change, rather than
304         // a change of the block definition..
305         
306         // this did notwork , as our rebuilt nodes did not include ID's so did not match at all.
307          /*if (from.innerHTML == to.innerHTML) {
308             return;
309         }
310         if (far.length != tar.length) {
311             from.innerHTML = to.innerHTML;
312             return;
313         }
314         */
315         
316         for(var i = 0; i < Math.max(tar.length, far.length); i++) {
317             if (i >= far.length) {
318                 from.appendChild(tar[i]);
319                 Roo.log(["add", tar[i]]);
320                 
321             } else if ( i  >= tar.length) {
322                 from.removeChild(far[i]);
323                 Roo.log(["remove", far[i]]);
324             } else {
325                 
326                 updateNode(far[i], tar[i]);
327             }    
328         }
329         
330         
331         
332         
333     };
334     
335     
336
337     return {
338         /** True to force the use of DOM instead of html fragments @type Boolean */
339         useDom : false,
340     
341         /**
342          * Returns the markup for the passed Element(s) config
343          * @param {Object} o The Dom object spec (and children)
344          * @return {String}
345          */
346         markup : function(o){
347             return createHtml(o);
348         },
349     
350         /**
351          * Applies a style specification to an element
352          * @param {String/HTMLElement} el The element to apply styles to
353          * @param {String/Object/Function} styles A style specification string eg "width:100px", or object in the form {width:"100px"}, or
354          * a function which returns such a specification.
355          */
356         applyStyles : function(el, styles){
357             if(styles){
358                el = Roo.fly(el);
359                if(typeof styles == "string"){
360                    var re = /\s?([a-z\-]*)\:\s?([^;]*);?/gi;
361                    var matches;
362                    while ((matches = re.exec(styles)) != null){
363                        el.setStyle(matches[1], matches[2]);
364                    }
365                }else if (typeof styles == "object"){
366                    for (var style in styles){
367                       el.setStyle(style, styles[style]);
368                    }
369                }else if (typeof styles == "function"){
370                     Roo.DomHelper.applyStyles(el, styles.call());
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} el The context element
379          * @param {String} html The HTML fragmenet
380          * @return {HTMLElement} The new node
381          */
382         insertHtml : function(where, el, html){
383             where = where.toLowerCase();
384             if(el.insertAdjacentHTML){
385                 if(tableRe.test(el.tagName)){
386                     var rs;
387                     if(rs = insertIntoTable(el.tagName.toLowerCase(), where, el, html)){
388                         return rs;
389                     }
390                 }
391                 switch(where){
392                     case "beforebegin":
393                         el.insertAdjacentHTML('BeforeBegin', html);
394                         return el.previousSibling;
395                     case "afterbegin":
396                         el.insertAdjacentHTML('AfterBegin', html);
397                         return el.firstChild;
398                     case "beforeend":
399                         el.insertAdjacentHTML('BeforeEnd', html);
400                         return el.lastChild;
401                     case "afterend":
402                         el.insertAdjacentHTML('AfterEnd', html);
403                         return el.nextSibling;
404                 }
405                 throw 'Illegal insertion point -> "' + where + '"';
406             }
407             var range = el.ownerDocument.createRange();
408             var frag;
409             switch(where){
410                  case "beforebegin":
411                     range.setStartBefore(el);
412                     frag = range.createContextualFragment(html);
413                     el.parentNode.insertBefore(frag, el);
414                     return el.previousSibling;
415                  case "afterbegin":
416                     if(el.firstChild){
417                         range.setStartBefore(el.firstChild);
418                         frag = range.createContextualFragment(html);
419                         el.insertBefore(frag, el.firstChild);
420                         return el.firstChild;
421                     }else{
422                         el.innerHTML = html;
423                         return el.firstChild;
424                     }
425                 case "beforeend":
426                     if(el.lastChild){
427                         range.setStartAfter(el.lastChild);
428                         frag = range.createContextualFragment(html);
429                         el.appendChild(frag);
430                         return el.lastChild;
431                     }else{
432                         el.innerHTML = html;
433                         return el.lastChild;
434                     }
435                 case "afterend":
436                     range.setStartAfter(el);
437                     frag = range.createContextualFragment(html);
438                     el.parentNode.insertBefore(frag, el.nextSibling);
439                     return el.nextSibling;
440                 }
441                 throw 'Illegal insertion point -> "' + where + '"';
442         },
443     
444         /**
445          * Creates new Dom element(s) and inserts them before el
446          * @param {String/HTMLElement/Element} el The context element
447          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
448          * @param {Boolean} returnElement (optional) true to return a Roo.Element
449          * @return {HTMLElement/Roo.Element} The new node
450          */
451         insertBefore : function(el, o, returnElement){
452             return this.doInsert(el, o, returnElement, "beforeBegin");
453         },
454     
455         /**
456          * Creates new Dom element(s) and inserts them after el
457          * @param {String/HTMLElement/Element} el The context element
458          * @param {Object} o The Dom object spec (and children)
459          * @param {Boolean} returnElement (optional) true to return a Roo.Element
460          * @return {HTMLElement/Roo.Element} The new node
461          */
462         insertAfter : function(el, o, returnElement){
463             return this.doInsert(el, o, returnElement, "afterEnd", "nextSibling");
464         },
465     
466         /**
467          * Creates new Dom element(s) and inserts them as the first child of el
468          * @param {String/HTMLElement/Element} el The context element
469          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
470          * @param {Boolean} returnElement (optional) true to return a Roo.Element
471          * @return {HTMLElement/Roo.Element} The new node
472          */
473         insertFirst : function(el, o, returnElement){
474             return this.doInsert(el, o, returnElement, "afterBegin");
475         },
476     
477         // private
478         doInsert : function(el, o, returnElement, pos, sibling){
479             el = Roo.getDom(el);
480             var newNode;
481             if(this.useDom || o.ns){
482                 newNode = createDom(o, null);
483                 el.parentNode.insertBefore(newNode, sibling ? el[sibling] : el);
484             }else{
485                 var html = createHtml(o);
486                 newNode = this.insertHtml(pos, el, html);
487             }
488             return returnElement ? Roo.get(newNode, true) : newNode;
489         },
490     
491         /**
492          * Creates new Dom element(s) and appends them to el
493          * @param {String/HTMLElement/Element} el The context element
494          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
495          * @param {Boolean} returnElement (optional) true to return a Roo.Element
496          * @return {HTMLElement/Roo.Element} The new node
497          */
498         append : function(el, o, returnElement){
499             el = Roo.getDom(el);
500             var newNode;
501             if(this.useDom || o.ns){
502                 newNode = createDom(o, null);
503                 el.appendChild(newNode);
504             }else{
505                 var html = createHtml(o);
506                 newNode = this.insertHtml("beforeEnd", el, html);
507             }
508             return returnElement ? Roo.get(newNode, true) : newNode;
509         },
510     
511         /**
512          * Creates new Dom element(s) and overwrites the contents of el with them
513          * @param {String/HTMLElement/Element} el The context element
514          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
515          * @param {Boolean} returnElement (optional) true to return a Roo.Element
516          * @return {HTMLElement/Roo.Element} The new node
517          */
518         overwrite : function(el, o, returnElement)
519         {
520             el = Roo.getDom(el);
521             if (o.ns) {
522               
523                 while (el.childNodes.length) {
524                     el.removeChild(el.firstChild);
525                 }
526                 createDom(o, el);
527             } else {
528                 el.innerHTML = createHtml(o);   
529             }
530             
531             return returnElement ? Roo.get(el.firstChild, true) : el.firstChild;
532         },
533     
534         /**
535          * Creates a new Roo.DomHelper.Template from the Dom object spec
536          * @param {Object} o The Dom object spec (and children)
537          * @return {Roo.DomHelper.Template} The new template
538          */
539         createTemplate : function(o){
540             var html = createHtml(o);
541             return new Roo.Template(html);
542         },
543          /**
544          * Updates the first element with the spec from the o (replacing if necessary)
545          * This iterates through the children, and updates attributes / children etc..
546          * @param {String/HTMLElement/Element} el The context element
547          * @param {Object/String} o The Dom object spec (and children) or raw HTML blob
548          */
549         
550         update : function(el, o)
551         {
552             updateNode(Roo.getDom(el), createDom(o));
553             
554         }
555         
556         
557     };
558 }();