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