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