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                 if(typeof sp == 'object'){ // eg. prototype, rather than function constructor..
210                     overrides = sp;
211                     sp = sb;
212                     sb = function(){sp.apply(this, arguments);};
213                 }
214                 var F = function(){}, sbp, spp = sp.prototype;
215                 F.prototype = spp;
216                 sbp = sb.prototype = new F();
217                 sbp.constructor=sb;
218                 sb.superclass=spp;
219                 
220                 if(spp.constructor == Object.prototype.constructor){
221                     spp.constructor=sp;
222                    
223                 }
224                 
225                 sb.override = function(o){
226                     Roo.override(sb, o);
227                 };
228                 sbp.override = io;
229                 Roo.override(sb, overrides);
230                 return sb;
231             };
232         }(),
233
234         /**
235          * Adds a list of functions to the prototype of an existing class, overwriting any existing methods with the same name.
236          * Usage:<pre><code>
237 Roo.override(MyClass, {
238     newMethod1: function(){
239         // etc.
240     },
241     newMethod2: function(foo){
242         // etc.
243     }
244 });
245  </code></pre>
246          * @param {Object} origclass The class to override
247          * @param {Object} overrides The list of functions to add to origClass.  This should be specified as an object literal
248          * containing one or more methods.
249          * @method override
250          */
251         override : function(origclass, overrides){
252             if(overrides){
253                 var p = origclass.prototype;
254                 for(var method in overrides){
255                     p[method] = overrides[method];
256                 }
257             }
258         },
259         /**
260          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
261          * <pre><code>
262 Roo.namespace('Company', 'Company.data');
263 Company.Widget = function() { ... }
264 Company.data.CustomStore = function(config) { ... }
265 </code></pre>
266          * @param {String} namespace1
267          * @param {String} namespace2
268          * @param {String} etc
269          * @method namespace
270          */
271         namespace : function(){
272             var a=arguments, o=null, i, j, d, rt;
273             for (i=0; i<a.length; ++i) {
274                 d=a[i].split(".");
275                 rt = d[0];
276                 /** eval:var:o */
277                 eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
278                 for (j=1; j<d.length; ++j) {
279                     o[d[j]]=o[d[j]] || {};
280                     o=o[d[j]];
281                 }
282             }
283         },
284         /**
285          * Creates namespaces to be used for scoping variables and classes so that they are not global.  Usage:
286          * <pre><code>
287 Roo.factory({ xns: Roo.data, xtype : 'Store', .....});
288 Roo.factory(conf, Roo.data);
289 </code></pre>
290          * @param {String} classname
291          * @param {String} namespace (optional)
292          * @method factory
293          */
294          
295         factory : function(c, ns)
296         {
297             // no xtype, no ns or c.xns - or forced off by c.xns
298             if (!c.xtype   || (!ns && !c.xns) ||  (c.xns === false)) { // not enough info...
299                 return c;
300             }
301             ns = c.xns ? c.xns : ns; // if c.xns is set, then use that..
302             Roo.log('ns');
303             Roo.log(ns);
304             if (c.constructor == ns[c.xtype]) {// already created...
305                 return c;
306             }
307             if (ns[c.xtype]) {
308                 Roo.log("Roo.Factory(" + c.xtype + ")");
309                 if (Roo.debug) Roo.log("Roo.Factory(" + c.xtype + ")");
310                 var ret = new ns[c.xtype](c);
311                 ret.xns = false;
312                 return ret;
313             }
314             c.xns = false; // prevent recursion..
315             return c;
316         },
317          /**
318          * Logs to console if it can.
319          *
320          * @param {String|Object} string
321          * @method log
322          */
323         log : function(s)
324         {
325             if ((typeof(console) == 'undefined') || (typeof(console.log) == 'undefined')) {
326                 return; // alerT?
327             }
328             console.log(s);
329             
330         },
331         /**
332          * 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.
333          * @param {Object} o
334          * @return {String}
335          */
336         urlEncode : function(o){
337             if(!o){
338                 return "";
339             }
340             var buf = [];
341             for(var key in o){
342                 var ov = o[key], k = Roo.encodeURIComponent(key);
343                 var type = typeof ov;
344                 if(type == 'undefined'){
345                     buf.push(k, "=&");
346                 }else if(type != "function" && type != "object"){
347                     buf.push(k, "=", Roo.encodeURIComponent(ov), "&");
348                 }else if(ov instanceof Array){
349                     if (ov.length) {
350                             for(var i = 0, len = ov.length; i < len; i++) {
351                                 buf.push(k, "=", Roo.encodeURIComponent(ov[i] === undefined ? '' : ov[i]), "&");
352                             }
353                         } else {
354                             buf.push(k, "=&");
355                         }
356                 }
357             }
358             buf.pop();
359             return buf.join("");
360         },
361          /**
362          * Safe version of encodeURIComponent
363          * @param {String} data 
364          * @return {String} 
365          */
366         
367         encodeURIComponent : function (data)
368         {
369             try {
370                 return encodeURIComponent(data);
371             } catch(e) {} // should be an uri encode error.
372             
373             if (data == '' || data == null){
374                return '';
375             }
376             // http://stackoverflow.com/questions/2596483/unicode-and-uri-encoding-decoding-and-escaping-in-javascript
377             function nibble_to_hex(nibble){
378                 var chars = '0123456789ABCDEF';
379                 return chars.charAt(nibble);
380             }
381             data = data.toString();
382             var buffer = '';
383             for(var i=0; i<data.length; i++){
384                 var c = data.charCodeAt(i);
385                 var bs = new Array();
386                 if (c > 0x10000){
387                         // 4 bytes
388                     bs[0] = 0xF0 | ((c & 0x1C0000) >>> 18);
389                     bs[1] = 0x80 | ((c & 0x3F000) >>> 12);
390                     bs[2] = 0x80 | ((c & 0xFC0) >>> 6);
391                     bs[3] = 0x80 | (c & 0x3F);
392                 }else if (c > 0x800){
393                          // 3 bytes
394                     bs[0] = 0xE0 | ((c & 0xF000) >>> 12);
395                     bs[1] = 0x80 | ((c & 0xFC0) >>> 6);
396                     bs[2] = 0x80 | (c & 0x3F);
397                 }else if (c > 0x80){
398                        // 2 bytes
399                     bs[0] = 0xC0 | ((c & 0x7C0) >>> 6);
400                     bs[1] = 0x80 | (c & 0x3F);
401                 }else{
402                         // 1 byte
403                     bs[0] = c;
404                 }
405                 for(var j=0; j<bs.length; j++){
406                     var b = bs[j];
407                     var hex = nibble_to_hex((b & 0xF0) >>> 4) 
408                             + nibble_to_hex(b &0x0F);
409                     buffer += '%'+hex;
410                }
411             }
412             return buffer;    
413              
414         },
415
416         /**
417          * 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]}.
418          * @param {String} string
419          * @param {Boolean} overwrite (optional) Items of the same name will overwrite previous values instead of creating an an array (Defaults to false).
420          * @return {Object} A literal with members
421          */
422         urlDecode : function(string, overwrite){
423             if(!string || !string.length){
424                 return {};
425             }
426             var obj = {};
427             var pairs = string.split('&');
428             var pair, name, value;
429             for(var i = 0, len = pairs.length; i < len; i++){
430                 pair = pairs[i].split('=');
431                 name = decodeURIComponent(pair[0]);
432                 value = decodeURIComponent(pair[1]);
433                 if(overwrite !== true){
434                     if(typeof obj[name] == "undefined"){
435                         obj[name] = value;
436                     }else if(typeof obj[name] == "string"){
437                         obj[name] = [obj[name]];
438                         obj[name].push(value);
439                     }else{
440                         obj[name].push(value);
441                     }
442                 }else{
443                     obj[name] = value;
444                 }
445             }
446             return obj;
447         },
448
449         /**
450          * Iterates an array calling the passed function with each item, stopping if your function returns false. If the
451          * passed array is not really an array, your function is called once with it.
452          * The supplied function is called with (Object item, Number index, Array allItems).
453          * @param {Array/NodeList/Mixed} array
454          * @param {Function} fn
455          * @param {Object} scope
456          */
457         each : function(array, fn, scope){
458             if(typeof array.length == "undefined" || typeof array == "string"){
459                 array = [array];
460             }
461             for(var i = 0, len = array.length; i < len; i++){
462                 if(fn.call(scope || array[i], array[i], i, array) === false){ return i; };
463             }
464         },
465
466         // deprecated
467         combine : function(){
468             var as = arguments, l = as.length, r = [];
469             for(var i = 0; i < l; i++){
470                 var a = as[i];
471                 if(a instanceof Array){
472                     r = r.concat(a);
473                 }else if(a.length !== undefined && !a.substr){
474                     r = r.concat(Array.prototype.slice.call(a, 0));
475                 }else{
476                     r.push(a);
477                 }
478             }
479             return r;
480         },
481
482         /**
483          * Escapes the passed string for use in a regular expression
484          * @param {String} str
485          * @return {String}
486          */
487         escapeRe : function(s) {
488             return s.replace(/([.*+?^${}()|[\]\/\\])/g, "\\$1");
489         },
490
491         // internal
492         callback : function(cb, scope, args, delay){
493             if(typeof cb == "function"){
494                 if(delay){
495                     cb.defer(delay, scope, args || []);
496                 }else{
497                     cb.apply(scope, args || []);
498                 }
499             }
500         },
501
502         /**
503          * Return the dom node for the passed string (id), dom node, or Roo.Element
504          * @param {String/HTMLElement/Roo.Element} el
505          * @return HTMLElement
506          */
507         getDom : function(el){
508             if(!el){
509                 return null;
510             }
511             return el.dom ? el.dom : (typeof el == 'string' ? document.getElementById(el) : el);
512         },
513
514         /**
515         * Shorthand for {@link Roo.ComponentMgr#get}
516         * @param {String} id
517         * @return Roo.Component
518         */
519         getCmp : function(id){
520             return Roo.ComponentMgr.get(id);
521         },
522          
523         num : function(v, defaultValue){
524             if(typeof v != 'number'){
525                 return defaultValue;
526             }
527             return v;
528         },
529
530         destroy : function(){
531             for(var i = 0, a = arguments, len = a.length; i < len; i++) {
532                 var as = a[i];
533                 if(as){
534                     if(as.dom){
535                         as.removeAllListeners();
536                         as.remove();
537                         continue;
538                     }
539                     if(typeof as.purgeListeners == 'function'){
540                         as.purgeListeners();
541                     }
542                     if(typeof as.destroy == 'function'){
543                         as.destroy();
544                     }
545                 }
546             }
547         },
548
549         // inpired by a similar function in mootools library
550         /**
551          * Returns the type of object that is passed in. If the object passed in is null or undefined it
552          * return false otherwise it returns one of the following values:<ul>
553          * <li><b>string</b>: If the object passed is a string</li>
554          * <li><b>number</b>: If the object passed is a number</li>
555          * <li><b>boolean</b>: If the object passed is a boolean value</li>
556          * <li><b>function</b>: If the object passed is a function reference</li>
557          * <li><b>object</b>: If the object passed is an object</li>
558          * <li><b>array</b>: If the object passed is an array</li>
559          * <li><b>regexp</b>: If the object passed is a regular expression</li>
560          * <li><b>element</b>: If the object passed is a DOM Element</li>
561          * <li><b>nodelist</b>: If the object passed is a DOM NodeList</li>
562          * <li><b>textnode</b>: If the object passed is a DOM text node and contains something other than whitespace</li>
563          * <li><b>whitespace</b>: If the object passed is a DOM text node and contains only whitespace</li>
564          * @param {Mixed} object
565          * @return {String}
566          */
567         type : function(o){
568             if(o === undefined || o === null){
569                 return false;
570             }
571             if(o.htmlElement){
572                 return 'element';
573             }
574             var t = typeof o;
575             if(t == 'object' && o.nodeName) {
576                 switch(o.nodeType) {
577                     case 1: return 'element';
578                     case 3: return (/\S/).test(o.nodeValue) ? 'textnode' : 'whitespace';
579                 }
580             }
581             if(t == 'object' || t == 'function') {
582                 switch(o.constructor) {
583                     case Array: return 'array';
584                     case RegExp: return 'regexp';
585                 }
586                 if(typeof o.length == 'number' && typeof o.item == 'function') {
587                     return 'nodelist';
588                 }
589             }
590             return t;
591         },
592
593         /**
594          * Returns true if the passed value is null, undefined or an empty string (optional).
595          * @param {Mixed} value The value to test
596          * @param {Boolean} allowBlank (optional) Pass true if an empty string is not considered empty
597          * @return {Boolean}
598          */
599         isEmpty : function(v, allowBlank){
600             return v === null || v === undefined || (!allowBlank ? v === '' : false);
601         },
602         
603         /** @type Boolean */
604         isOpera : isOpera,
605         /** @type Boolean */
606         isSafari : isSafari,
607         /** @type Boolean */
608         isIE : isIE,
609         /** @type Boolean */
610         isIE7 : isIE7,
611         /** @type Boolean */
612         isGecko : isGecko,
613         /** @type Boolean */
614         isBorderBox : isBorderBox,
615         /** @type Boolean */
616         isWindows : isWindows,
617         /** @type Boolean */
618         isLinux : isLinux,
619         /** @type Boolean */
620         isMac : isMac,
621         /** @type Boolean */
622         isTouch : isTouch,
623
624         /**
625          * By default, Ext intelligently decides whether floating elements should be shimmed. If you are using flash,
626          * you may want to set this to true.
627          * @type Boolean
628          */
629         useShims : ((isIE && !isIE7) || (isGecko && isMac)),
630         
631         
632                 
633         /**
634          * Selects a single element as a Roo Element
635          * This is about as close as you can get to jQuery's $('do crazy stuff')
636          * @param {String} selector The selector/xpath query
637          * @param {Node} root (optional) The start of the query (defaults to document).
638          * @return {Roo.Element}
639          */
640         selectNode : function(selector, root) 
641         {
642             var node = Roo.DomQuery.selectNode(selector,root);
643             return node ? Roo.get(node) : new Roo.Element(false);
644         }
645         
646     });
647
648
649 })();
650
651 Roo.namespace("Roo", "Roo.util", "Roo.grid", "Roo.dd", "Roo.tree", "Roo.data",
652                 "Roo.form", "Roo.menu", "Roo.state", "Roo.lib", "Roo.layout", "Roo.app", "Roo.ux");