Roo.js
[roojs1] / Roo.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
15
16 // for old browsers
17 window["undefined"] = window["undefined"];
18
19 /**
20  * @class Roo
21  * Roo core utilities and functions.
22  * @singleton
23  */
24 var Roo = {}; 
25 /**
26  * Copies all the properties of config to obj.
27  * @param {Object} obj The receiver of the properties
28  * @param {Object} config The source of the properties
29  * @param {Object} defaults A different object that will also be applied for default values
30  * @return {Object} returns obj
31  * @member Roo apply
32  */
33
34  
35 Roo.apply = function(o, c, defaults){
36     if(defaults){
37         // no "this" reference for friendly out of scope calls
38         Roo.apply(o, defaults);
39     }
40     if(o && c && typeof c == 'object'){
41         for(var p in c){
42             o[p] = c[p];
43         }
44     }
45     return o;
46 };
47
48
49 (function(){
50     var idSeed = 0;
51     var ua = navigator.userAgent.toLowerCase();
52
53     var isStrict = document.compatMode == "CSS1Compat",
54         isOpera = ua.indexOf("opera") > -1,
55         isSafari = (/webkit|khtml/).test(ua),
56         isIE = ua.indexOf("msie") > -1,
57         isIE7 = ua.indexOf("msie 7") > -1,
58         isGecko = !isSafari && ua.indexOf("gecko") > -1,
59         isBorderBox = isIE && !isStrict,
60         isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
61         isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
62         isLinux = (ua.indexOf("linux") != -1),
63         isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
64         isTouch =  'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
65     // remove css image flicker
66         if(isIE && !isIE7){
67         try{
68             document.execCommand("BackgroundImageCache", false, true);
69         }catch(e){}
70     }
71     
72     Roo.apply(Roo, {
73         /**
74          * True if the browser is in strict mode
75          * @type Boolean
76          */
77         isStrict : isStrict,
78         /**
79          * True if the page is running over SSL
80          * @type Boolean
81          */
82         isSecure : isSecure,
83         /**
84          * True when the document is fully initialized and ready for action
85          * @type Boolean
86          */
87         isReady : false,
88         /**
89          * Turn on debugging output (currently only the factory uses this)
90          * @type Boolean
91          */
92         
93         debug: false,
94
95         /**
96          * True to automatically uncache orphaned Roo.Elements periodically (defaults to true)
97          * @type Boolean
98          */
99         enableGarbageCollector : true,
100
101         /**
102          * True to automatically purge event listeners after uncaching an element (defaults to false).
103          * Note: this only happens if enableGarbageCollector is true.
104          * @type Boolean
105          */
106         enableListenerCollection:false,
107
108         /**
109          * URL to a blank file used by Roo when in secure mode for iframe src and onReady src to prevent
110          * the IE insecure content warning (defaults to javascript:false).
111          * @type String
112          */
113         SSL_SECURE_URL : "javascript:false",
114
115         /**
116          * URL to a 1x1 transparent gif image used by Roo to create inline icons with CSS background images. (Defaults to
117          * "http://Roojs.com/s.gif" and you should change this to a URL on your server).
118          * @type String
119          */
120         BLANK_IMAGE_URL : "http:/"+"/localhost/s.gif",
121
122         emptyFn : function(){},
123         
124         /**
125          * Copies all the properties of config to obj if they don't already exist.
126          * @param {Object} obj The receiver of the properties
127          * @param {Object} config The source of the properties
128          * @return {Object} returns obj
129          */
130         applyIf : function(o, c){
131             if(o && c){
132                 for(var p in c){
133                     if(typeof o[p] == "undefined"){ o[p] = c[p]; }
134                 }
135             }
136             return o;
137         },
138
139         /**
140          * Applies event listeners to elements by selectors when the document is ready.
141          * The event name is specified with an @ suffix.
142 <pre><code>
143 Roo.addBehaviors({
144    // add a listener for click on all anchors in element with id foo
145    '#foo a@click' : function(e, t){
146        // do something
147    },
148
149    // add the same listener to multiple selectors (separated by comma BEFORE the @)
150    '#foo a, #bar span.some-class@mouseover' : function(){
151        // do something
152    }
153 });
154 </code></pre>
155          * @param {Object} obj The list of behaviors to apply
156          */
157         addBehaviors : function(o){
158             if(!Roo.isReady){
159                 Roo.onReady(function(){
160                     Roo.addBehaviors(o);
161                 });
162                 return;
163             }
164             var cache = {}; // simple cache for applying multiple behaviors to same selector does query multiple times
165             for(var b in o){
166                 var parts = b.split('@');
167                 if(parts[1]){ // for Object prototype breakers
168                     var s = parts[0];
169                     if(!cache[s]){
170                         cache[s] = Roo.select(s);
171                     }
172                     cache[s].on(parts[1], o[b]);
173                 }
174             }
175             cache = null;
176         },
177
178         /**
179          * Generates unique ids. If the element already has an id, it is unchanged
180          * @param {String/HTMLElement/Element} el (optional) The element to generate an id for
181          * @param {String} prefix (optional) Id prefix (defaults "Roo-gen")
182          * @return {String} The generated Id.
183          */
184         id : function(el, prefix){
185             prefix = prefix || "roo-gen";
186             el = Roo.getDom(el);
187             var id = prefix + (++idSeed);
188             return el ? (el.id ? el.id : (el.id = id)) : id;
189         },
190          
191        
192         /**
193          * Extends one class with another class and optionally overrides members with the passed literal. This class
194          * also adds the function "override()" to the class that can be used to override
195          * members on an instance.
196          * @param {Object} subclass The class inheriting the functionality
197          * @param {Object} superclass The class being extended
198          * @param {Object} overrides (optional) A literal with members
199          * @method extend
200          */
201         extend : function(){
202             // inline overrides
203             var io = function(o){
204                 for(var m in o){
205                     this[m] = o[m];
206                 }
207             };
208             return function(sb, sp, overrides){
209                 Roo.log('extend!!!!');
210                 Roo.log(sb);
211                 Roo.log(sp);
212                 Roo.log(overrides);
213                 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
214                     overrides = sp;
215                     sp = sb;
216                     sb = function(){sp.apply(this, arguments);};
217                 }
218                 var F = function(){}, sbp, spp = sp.prototype;
219                 F.prototype = spp;
220                 sbp = sb.prototype = new F();
221                 sbp.constructor=sb;
222                 sb.superclass=spp;
223                 
224                 if(spp.constructor == Object.prototype.constructor){
225                     spp.constructor=sp;
226                    
227                 }
228                 
229                 sb.override = function(o){
230                     Roo.override(sb, o);
231                 };
232                 sbp.override = io;
233                 Roo.override(sb, overrides);
234                 return sb;
235             };
236         }(),
237
238         /**
239          * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
240          * Usage:<pre><code>
241 Roo.override(MyClass, {
242     newMethod1: function(){
243         // etc.
244     },
245     newMethod2: function(foo){
246         // etc.
247     }
248 });
249  </code></pre>
250          * @param {Object} origclass The class to override
251          * @param {Object} overrides The list of functions to add to origClass.  This should be specified as an object literal
252          * containing one or more methods.
253          * @method override
254          */
255         override : function(origclass, overrides){
256             if(overrides){
257                 var p = origclass.prototype;
258                 for(var method in overrides){
259                     p[method] = overrides[method];
260                 }
261             }
262         },
263         /**
264          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
265          * <pre><code>
266 Roo.namespace('Company', 'Company.data');
267 Company.Widget = function() { ... }
268 Company.data.CustomStore = function(config) { ... }
269 </code></pre>
270          * @param {String} namespace1
271          * @param {String} namespace2
272          * @param {String} etc
273          * @method namespace
274          */
275         namespace : function(){
276             var a=arguments, o=null, i, j, d, rt;
277             for (i=0; i<a.length; ++i) {
278                 d=a[i].split(".");
279                 rt = d[0];
280                 /** eval:var:o */
281                 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
282                 for (j=1; j<d.length; ++j) {
283                     o[d[j]]=o[d[j]] || {};
284                     o=o[d[j]];
285                 }
286             }
287         },
288         /**
289          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
290          * <pre><code>
291 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
292 Roo.factory(conf, Roo.data);
293 </code></pre>
294          * @param {String} classname
295          * @param {String} namespace (optional)
296          * @method factory
297          */
298          
299         factory : function(c, ns)
300         {
301             // no xtype, no ns or c.xns - or forced off by c.xns
302             if (!c.xtype   || (!ns && !c.xns) ||  (c.xns === false)) { // not enough info...
303                 return c;
304             }
305             ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
306             if (c.constructor == ns[c.xtype]) {// already created...
307                 return c;
308             }
309             if (ns[c.xtype]) {
310                 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
311                 var ret = new ns[c.xtype](c);
312                 ret.xns = false;
313                 return ret;
314             }
315             c.xns = false; // prevent recursion..
316             return c;
317         },
318          /**
319          * Logs to console if it can.
320          *
321          * @param {String|Object} string
322          * @method log
323          */
324         log : function(s)
325         {
326             if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
327                 return; // alerT?
328             }
329             console.log(s);
330             
331         },
332         /**
333          * Takes an object and converts it to an encoded URL. e.g. Roo.urlEncode({foo: 1, bar: 2}); would return "foo=1&bar=2".  Optionally, property values can be arrays, instead of keys and the resulting string that's returned will contain a name/value pair for each array value.
334          * @param {Object} o
335          * @return {String}
336          */
337         urlEncode : function(o){
338             if(!o){
339                 return "";
340             }
341             var buf = [];
342             for(var key in o){
343                 var ov = o[key], k = Roo.encodeURIComponent(key);
344                 var type = typeof ov;
345                 if(type == 'undefined'){
346                     buf.push(k, "=&");
347                 }else if(type != "function" && type != "object"){
348                     buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
349                 }else if(ov instanceof Array){
350                     if (ov.length) {
351                             for(var i = 0, len = ov.length; i < len; i++) {
352                                 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
353                             }
354                         } else {
355                             buf.push(k, "=&");
356                         }
357                 }
358             }
359             buf.pop();
360             return buf.join("");
361         },
362          /**
363          * Safe version of encodeURIComponent
364          * @param {String} data 
365          * @return {String} 
366          */
367         
368         encodeURIComponent : function (data)
369         {
370             try {
371                 return encodeURIComponent(data);
372             } catch(e) {} // should be an uri encode error.
373             
374             if (data == '' || data == null){
375                return '';
376             }
377             // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
378             function nibble_to_hex(nibble){
379                 var chars = '0123456789ABCDEF';
380                 return chars.charAt(nibble);
381             }
382             data = data.toString();
383             var buffer = '';
384             for(var i=0; i<data.length; i++){
385                 var c = data.charCodeAt(i);
386                 var bs = new Array();
387                 if (c > 0x10000){
388                         // 4 bytes
389                     bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
390                     bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
391                     bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
392                     bs[3] = 0x80 | (c & 0x3F);
393                 }else if (c > 0x800){
394                          // 3 bytes
395                     bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
396                     bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
397                     bs[2] = 0x80 | (c & 0x3F);
398                 }else if (c > 0x80){
399                        // 2 bytes
400                     bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
401                     bs[1] = 0x80 | (c & 0x3F);
402                 }else{
403                         // 1 byte
404                     bs[0] = c;
405                 }
406                 for(var j=0; j<bs.length; j++){
407                     var b = bs[j];
408                     var hex = nibble_to_hex((b & 0xF0) >>> 4) 
409                             + nibble_to_hex(b &0x0F);
410                     buffer += '%'+hex;
411                }
412             }
413             return buffer;    
414              
415         },
416
417         /**
418          * Takes an encoded URL and and converts it to an object. e.g. Roo.urlDecode("foo=1&bar=2"); would return {foo: 1, bar: 2} or Roo.urlDecode("foo=1&bar=2&bar=3&bar=4", true); would return {foo: 1, bar: [2, 3, 4]}.
419          * @param {String} string
420          * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
421          * @return {Object} A literal with members
422          */
423         urlDecode : function(string, overwrite){
424             if(!string || !string.length){
425                 return {};
426             }
427             var obj = {};
428             var pairs = string.split('&');
429             var pair, name, value;
430             for(var i = 0, len = pairs.length; i < len; i++){
431                 pair = pairs[i].split('=');
432                 name = decodeURIComponent(pair[0]);
433                 value = decodeURIComponent(pair[1]);
434                 if(overwrite !== true){
435                     if(typeof obj[name] == "undefined"){
436                         obj[name] = value;
437                     }else if(typeof obj[name] == "string"){
438                         obj[name] = [obj[name]];
439                         obj[name].push(value);
440                     }else{
441                         obj[name].push(value);
442                     }
443                 }else{
444                     obj[name] = value;
445                 }
446             }
447             return obj;
448         },
449
450         /**
451          * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
452          * passed array is not really an array, your function is called once with it.
453          * The supplied function is called with (Object item, Number index, Array allItems).
454          * @param {Array/NodeList/Mixed} array
455          * @param {Function} fn
456          * @param {Object} scope
457          */
458         each : function(array, fn, scope){
459             if(typeof array.length == "undefined" || typeof array == "string"){
460                 array = [array];
461             }
462             for(var i = 0, len = array.length; i < len; i++){
463                 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
464             }
465         },
466
467         // deprecated
468         combine : function(){
469             var as = arguments, l = as.length, r = [];
470             for(var i = 0; i < l; i++){
471                 var a = as[i];
472                 if(a instanceof Array){
473                     r = r.concat(a);
474                 }else if(a.length !== undefined && !a.substr){
475                     r = r.concat(Array.prototype.slice.call(a, 0));
476                 }else{
477                     r.push(a);
478                 }
479             }
480             return r;
481         },
482
483         /**
484          * Escapes the passed string for use in a regular expression
485          * @param {String} str
486          * @return {String}
487          */
488         escapeRe : function(s) {
489             return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
490         },
491
492         // internal
493         callback : function(cb, scope, args, delay){
494             if(typeof cb == "function"){
495                 if(delay){
496                     cb.defer(delay, scope, args || []);
497                 }else{
498                     cb.apply(scope, args || []);
499                 }
500             }
501         },
502
503         /**
504          * Return the dom node for the passed string (id), dom node, or Roo.Element
505          * @param {String/HTMLElement/Roo.Element} el
506          * @return HTMLElement
507          */
508         getDom : function(el){
509             if(!el){
510                 return null;
511             }
512             return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
513         },
514
515         /**
516         * Shorthand for {@link Roo.ComponentMgr#get}
517         * @param {String} id
518         * @return Roo.Component
519         */
520         getCmp : function(id){
521             return Roo.ComponentMgr.get(id);
522         },
523          
524         num : function(v, defaultValue){
525             if(typeof v != 'number'){
526                 return defaultValue;
527             }
528             return v;
529         },
530
531         destroy : function(){
532             for(var i = 0, a = arguments, len = a.length; i < len; i++) {
533                 var as = a[i];
534                 if(as){
535                     if(as.dom){
536                         as.removeAllListeners();
537                         as.remove();
538                         continue;
539                     }
540                     if(typeof as.purgeListeners == 'function'){
541                         as.purgeListeners();
542                     }
543                     if(typeof as.destroy == 'function'){
544                         as.destroy();
545                     }
546                 }
547             }
548         },
549
550         // inpired by a similar function in mootools library
551         /**
552          * Returns the type of object that is passed in. If the object passed in is null or undefined it
553          * return false otherwise it returns one of the following values:<ul>
554          * <li><b>string</b>: If the object passed is a string</li>
555          * <li><b>number</b>: If the object passed is a number</li>
556          * <li><b>boolean</b>: If the object passed is a boolean value</li>
557          * <li><b>function</b>: If the object passed is a function reference</li>
558          * <li><b>object</b>: If the object passed is an object</li>
559          * <li><b>array</b>: If the object passed is an array</li>
560          * <li><b>regexp</b>: If the object passed is a regular expression</li>
561          * <li><b>element</b>: If the object passed is a DOM Element</li>
562          * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
563          * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
564          * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
565          * @param {Mixed} object
566          * @return {String}
567          */
568         type : function(o){
569             if(o === undefined || o === null){
570                 return false;
571             }
572             if(o.htmlElement){
573                 return 'element';
574             }
575             var t = typeof o;
576             if(t == 'object' && o.nodeName) {
577                 switch(o.nodeType) {
578                     case 1: return 'element';
579                     case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
580                 }
581             }
582             if(t == 'object' || t == 'function') {
583                 switch(o.constructor) {
584                     case Array: return 'array';
585                     case RegExp: return 'regexp';
586                 }
587                 if(typeof o.length == 'number' && typeof o.item == 'function') {
588                     return 'nodelist';
589                 }
590             }
591             return t;
592         },
593
594         /**
595          * Returns true if the passed value is null, undefined or an empty string (optional).
596          * @param {Mixed} value The value to test
597          * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
598          * @return {Boolean}
599          */
600         isEmpty : function(v, allowBlank){
601             return v === null || v === undefined || (!allowBlank ? v === '' : false);
602         },
603         
604         /** @type Boolean */
605         isOpera : isOpera,
606         /** @type Boolean */
607         isSafari : isSafari,
608         /** @type Boolean */
609         isIE : isIE,
610         /** @type Boolean */
611         isIE7 : isIE7,
612         /** @type Boolean */
613         isGecko : isGecko,
614         /** @type Boolean */
615         isBorderBox : isBorderBox,
616         /** @type Boolean */
617         isWindows : isWindows,
618         /** @type Boolean */
619         isLinux : isLinux,
620         /** @type Boolean */
621         isMac : isMac,
622         /** @type Boolean */
623         isTouch : isTouch,
624
625         /**
626          * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
627          * you may want to set this to true.
628          * @type Boolean
629          */
630         useShims : ((isIE && !isIE7) || (isGecko && isMac)),
631         
632         
633                 
634         /**
635          * Selects a single element as a Roo Element
636          * This is about as close as you can get to jQuery's $('do crazy stuff')
637          * @param {String} selector The selector/xpath query
638          * @param {Node} root (optional) The start of the query (defaults to document).
639          * @return {Roo.Element}
640          */
641         selectNode : function(selector, root) 
642         {
643             var node = Roo.DomQuery.selectNode(selector,root);
644             return node ? Roo.get(node) : new Roo.Element(false);
645         }
646         
647     });
648
649
650 })();
651
652 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
653                 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");