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