Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / adapter / prototype-bridge.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 (function(){
8
9 var libFlyweight,
10     version = Prototype.Version.split('.'),
11     mouseEnterSupported = (parseInt(version[0]) >= 2) || (parseInt(version[1]) >= 7) || (parseInt(version[2]) >= 1),
12     mouseCache = {},
13     elContains = function(parent, child) {
14        if(parent && parent.firstChild){
15          while(child) {
16             if(child === parent) {
17                 return true;
18             }
19             child = child.parentNode;
20             if(child && (child.nodeType != 1)) {
21                 child = null;
22             }
23           }
24         }
25         return false;
26     },
27     checkRelatedTarget = function(e) {
28         return !elContains(e.currentTarget, Ext.lib.Event.getRelatedTarget(e));
29     };
30
31 Ext.lib.Dom = {
32     getViewWidth : function(full){
33         return full ? this.getDocumentWidth() : this.getViewportWidth();
34     },
35
36     getViewHeight : function(full){
37         return full ? this.getDocumentHeight() : this.getViewportHeight();
38     },
39
40     getDocumentHeight: function() { // missing from prototype?
41         var scrollHeight = (document.compatMode != "CSS1Compat") ? document.body.scrollHeight : document.documentElement.scrollHeight;
42         return Math.max(scrollHeight, this.getViewportHeight());
43     },
44
45     getDocumentWidth: function() { // missing from prototype?
46         var scrollWidth = (document.compatMode != "CSS1Compat") ? document.body.scrollWidth : document.documentElement.scrollWidth;
47         return Math.max(scrollWidth, this.getViewportWidth());
48     },
49
50     getViewportHeight: function() { // missing from prototype?
51         var height = self.innerHeight;
52         var mode = document.compatMode;
53
54         if ( (mode || Ext.isIE) && !Ext.isOpera ) {
55             height = (mode == "CSS1Compat") ?
56                     document.documentElement.clientHeight : // Standards
57                     document.body.clientHeight; // Quirks
58         }
59
60         return height;
61     },
62
63     getViewportWidth: function() { // missing from prototype?
64         var width = self.innerWidth;  // Safari
65         var mode = document.compatMode;
66
67         if (mode || Ext.isIE) { // IE, Gecko, Opera
68             width = (mode == "CSS1Compat") ?
69                     document.documentElement.clientWidth : // Standards
70                     document.body.clientWidth; // Quirks
71         }
72         return width;
73     },
74
75     isAncestor : function(p, c){ // missing from prototype?
76         var ret = false;
77
78         p = Ext.getDom(p);
79         c = Ext.getDom(c);
80         if (p && c) {
81             if (p.contains) {
82                 return p.contains(c);
83             } else if (p.compareDocumentPosition) {
84                 return !!(p.compareDocumentPosition(c) & 16);
85             } else {
86                 while (c = c.parentNode) {
87                     ret = c == p || ret;
88                 }
89             }
90         }
91         return ret;
92     },
93
94     getRegion : function(el){
95         return Ext.lib.Region.getRegion(el);
96     },
97
98     getY : function(el){
99         return this.getXY(el)[1];
100     },
101
102     getX : function(el){
103         return this.getXY(el)[0];
104     },
105
106     getXY : function(el){ // this initially used Position.cumulativeOffset but it is not accurate enough
107         var p, pe, b, scroll, bd = (document.body || document.documentElement);
108         el = Ext.getDom(el);
109
110         if(el == bd){
111             return [0, 0];
112         }
113
114         if (el.getBoundingClientRect) {
115             b = el.getBoundingClientRect();
116             scroll = fly(document).getScroll();
117             return [Math.round(b.left + scroll.left), Math.round(b.top + scroll.top)];
118         }
119         var x = 0, y = 0;
120
121         p = el;
122
123         var hasAbsolute = fly(el).getStyle("position") == "absolute";
124
125         while (p) {
126
127             x += p.offsetLeft;
128             y += p.offsetTop;
129
130             if (!hasAbsolute && fly(p).getStyle("position") == "absolute") {
131                 hasAbsolute = true;
132             }
133
134             if (Ext.isGecko) {
135                 pe = fly(p);
136
137                 var bt = parseInt(pe.getStyle("borderTopWidth"), 10) || 0;
138                 var bl = parseInt(pe.getStyle("borderLeftWidth"), 10) || 0;
139
140
141                 x += bl;
142                 y += bt;
143
144
145                 if (p != el && pe.getStyle('overflow') != 'visible') {
146                     x += bl;
147                     y += bt;
148                 }
149             }
150             p = p.offsetParent;
151         }
152
153         if (Ext.isSafari && hasAbsolute) {
154             x -= bd.offsetLeft;
155             y -= bd.offsetTop;
156         }
157
158         if (Ext.isGecko && !hasAbsolute) {
159             var dbd = fly(bd);
160             x += parseInt(dbd.getStyle("borderLeftWidth"), 10) || 0;
161             y += parseInt(dbd.getStyle("borderTopWidth"), 10) || 0;
162         }
163
164         p = el.parentNode;
165         while (p && p != bd) {
166             if (!Ext.isOpera || (p.tagName != 'TR' && fly(p).getStyle("display") != "inline")) {
167                 x -= p.scrollLeft;
168                 y -= p.scrollTop;
169             }
170             p = p.parentNode;
171         }
172         return [x, y];
173     },
174
175     setXY : function(el, xy){ // this initially used Position.cumulativeOffset but it is not accurate enough
176         el = Ext.fly(el, '_setXY');
177         el.position();
178         var pts = el.translatePoints(xy);
179         if(xy[0] !== false){
180             el.dom.style.left = pts.left + "px";
181         }
182         if(xy[1] !== false){
183             el.dom.style.top = pts.top + "px";
184         }
185     },
186
187     setX : function(el, x){
188         this.setXY(el, [x, false]);
189     },
190
191     setY : function(el, y){
192         this.setXY(el, [false, y]);
193     }
194 };
195
196 Ext.lib.Event = {
197     getPageX : function(e){
198         return Event.pointerX(e.browserEvent || e);
199     },
200
201     getPageY : function(e){
202         return Event.pointerY(e.browserEvent || e);
203     },
204
205     getXY : function(e){
206         e = e.browserEvent || e;
207         return [Event.pointerX(e), Event.pointerY(e)];
208     },
209
210     getTarget : function(e){
211         return Event.element(e.browserEvent || e);
212     },
213
214     resolveTextNode: Ext.isGecko ? function(node){
215         if(!node){
216             return;
217         }
218         var s = HTMLElement.prototype.toString.call(node);
219         if(s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]'){
220             return;
221         }
222         return node.nodeType == 3 ? node.parentNode : node;
223     } : function(node){
224         return node && node.nodeType == 3 ? node.parentNode : node;
225     },
226
227     getRelatedTarget: function(ev) { // missing from prototype?
228         ev = ev.browserEvent || ev;
229         var t = ev.relatedTarget;
230         if (!t) {
231             if (ev.type == "mouseout") {
232                 t = ev.toElement;
233             } else if (ev.type == "mouseover") {
234                 t = ev.fromElement;
235             }
236         }
237
238         return this.resolveTextNode(t);
239     },
240
241     on : function(el, eventName, fn){
242         if((eventName == 'mouseenter' || eventName == 'mouseleave') && !mouseEnterSupported){
243             var item = mouseCache[el.id] || (mouseCache[el.id] = {});
244             item[eventName] = fn;
245             fn = fn.createInterceptor(checkRelatedTarget);
246             eventName = (eventName == 'mouseenter') ? 'mouseover' : 'mouseout';
247         }
248         Event.observe(el, eventName, fn, false);
249     },
250
251     un : function(el, eventName, fn){
252         if((eventName == 'mouseenter' || eventName == 'mouseleave') && !mouseEnterSupported){
253             var item = mouseCache[el.id],
254                 ev = item && item[eventName];
255
256             if(ev){
257                 fn = ev.fn;
258                 delete item[eventName];
259                 eventName = (eventName == 'mouseenter') ? 'mouseover' : 'mouseout';
260             }
261         }
262         Event.stopObserving(el, eventName, fn, false);
263     },
264
265     purgeElement : function(el){
266         // no equiv?
267     },
268
269     preventDefault : function(e){   // missing from prototype?
270         e = e.browserEvent || e;
271         if(e.preventDefault) {
272             e.preventDefault();
273         } else {
274             e.returnValue = false;
275         }
276     },
277
278     stopPropagation : function(e){   // missing from prototype?
279         e = e.browserEvent || e;
280         if(e.stopPropagation) {
281             e.stopPropagation();
282         } else {
283             e.cancelBubble = true;
284         }
285     },
286
287     stopEvent : function(e){
288         Event.stop(e.browserEvent || e);
289     },
290
291     onAvailable : function(id, fn, scope){  // no equiv
292         var start = new Date(), iid;
293         var f = function(){
294             if(start.getElapsed() > 10000){
295                 clearInterval(iid);
296             }
297             var el = document.getElementById(id);
298             if(el){
299                 clearInterval(iid);
300                 fn.call(scope||window, el);
301             }
302         };
303         iid = setInterval(f, 50);
304     }
305 };
306
307 Ext.lib.Ajax = function(){
308     var createSuccess = function(cb){
309          return cb.success ? function(xhr){
310             cb.success.call(cb.scope||window, createResponse(cb, xhr));
311          } : Ext.emptyFn;
312     };
313     var createFailure = function(cb){
314          return cb.failure ? function(xhr){
315             cb.failure.call(cb.scope||window, createResponse(cb, xhr));
316          } : Ext.emptyFn;
317     };
318     var createResponse = function(cb, xhr){
319         var headerObj = {},
320             headerStr,
321             t,
322             s;
323
324         try {
325             headerStr = xhr.getAllResponseHeaders();
326             Ext.each(headerStr.replace(/\r\n/g, '\n').split('\n'), function(v){
327                 t = v.indexOf(':');
328                 if(t >= 0){
329                     s = v.substr(0, t).toLowerCase();
330                     if(v.charAt(t + 1) == ' '){
331                         ++t;
332                     }
333                     headerObj[s] = v.substr(t + 1);
334                 }
335             });
336         } catch(e) {}
337
338         return {
339             responseText: xhr.responseText,
340             responseXML : xhr.responseXML,
341             argument: cb.argument,
342             status: xhr.status,
343             statusText: xhr.statusText,
344             getResponseHeader : function(header){return headerObj[header.toLowerCase()];},
345             getAllResponseHeaders : function(){return headerStr}
346         };
347     };
348     return {
349         request : function(method, uri, cb, data, options){
350             var o = {
351                 method: method,
352                 parameters: data || '',
353                 timeout: cb.timeout,
354                 onSuccess: createSuccess(cb),
355                 onFailure: createFailure(cb)
356             };
357             if(options){
358                 var hs = options.headers;
359                 if(hs){
360                     o.requestHeaders = hs;
361                 }
362                 if(options.xmlData){
363                     method = (method ? method : (options.method ? options.method : 'POST'));
364                     if (!hs || !hs['Content-Type']){
365                         o.contentType = 'text/xml';
366                     }
367                     o.postBody = options.xmlData;
368                     delete o.parameters;
369                 }
370                 if(options.jsonData){
371                     method = (method ? method : (options.method ? options.method : 'POST'));
372                     if (!hs || !hs['Content-Type']){
373                         o.contentType = 'application/json';
374                     }
375                     o.postBody = typeof options.jsonData == 'object' ? Ext.encode(options.jsonData) : options.jsonData;
376                     delete o.parameters;
377                 }
378             }
379             new Ajax.Request(uri, o);
380         },
381
382         formRequest : function(form, uri, cb, data, isUpload, sslUri){
383             new Ajax.Request(uri, {
384                 method: Ext.getDom(form).method ||'POST',
385                 parameters: Form.serialize(form)+(data?'&'+data:''),
386                 timeout: cb.timeout,
387                 onSuccess: createSuccess(cb),
388                 onFailure: createFailure(cb)
389             });
390         },
391
392         isCallInProgress : function(trans){
393             return false;
394         },
395
396         abort : function(trans){
397             return false;
398         },
399
400         serializeForm : function(form){
401             return Form.serialize(form.dom||form);
402         }
403     };
404 }();
405
406
407 Ext.lib.Anim = function(){
408
409     var easings = {
410         easeOut: function(pos) {
411             return 1-Math.pow(1-pos,2);
412         },
413         easeIn: function(pos) {
414             return 1-Math.pow(1-pos,2);
415         }
416     };
417     var createAnim = function(cb, scope){
418         return {
419             stop : function(skipToLast){
420                 this.effect.cancel();
421             },
422
423             isAnimated : function(){
424                 return this.effect.state == 'running';
425             },
426
427             proxyCallback : function(){
428                 Ext.callback(cb, scope);
429             }
430         };
431     };
432     return {
433         scroll : function(el, args, duration, easing, cb, scope){
434             // not supported so scroll immediately?
435             var anim = createAnim(cb, scope);
436             el = Ext.getDom(el);
437             if(typeof args.scroll.to[0] == 'number'){
438                 el.scrollLeft = args.scroll.to[0];
439             }
440             if(typeof args.scroll.to[1] == 'number'){
441                 el.scrollTop = args.scroll.to[1];
442             }
443             anim.proxyCallback();
444             return anim;
445         },
446
447         motion : function(el, args, duration, easing, cb, scope){
448             return this.run(el, args, duration, easing, cb, scope);
449         },
450
451         color : function(el, args, duration, easing, cb, scope){
452             return this.run(el, args, duration, easing, cb, scope);
453         },
454
455         run : function(el, args, duration, easing, cb, scope, type){
456             var o = {};
457             for(var k in args){
458                 switch(k){   // scriptaculous doesn't support, so convert these
459                     case 'points':
460                         var by, pts, e = Ext.fly(el, '_animrun');
461                         e.position();
462                         if(by = args.points.by){
463                             var xy = e.getXY();
464                             pts = e.translatePoints([xy[0]+by[0], xy[1]+by[1]]);
465                         }else{
466                             pts = e.translatePoints(args.points.to);
467                         }
468                         o.left = pts.left+'px';
469                         o.top = pts.top+'px';
470                     break;
471                     case 'width':
472                         o.width = args.width.to+'px';
473                     break;
474                     case 'height':
475                         o.height = args.height.to+'px';
476                     break;
477                     case 'opacity':
478                         o.opacity = String(args.opacity.to);
479                     break;
480                     default:
481                         o[k] = String(args[k].to);
482                     break;
483                 }
484             }
485             var anim = createAnim(cb, scope);
486             anim.effect = new Effect.Morph(Ext.id(el), {
487                 duration: duration,
488                 afterFinish: anim.proxyCallback,
489                 transition: easings[easing] || Effect.Transitions.linear,
490                 style: o
491             });
492             return anim;
493         }
494     };
495 }();
496
497
498 // all lib flyweight calls use their own flyweight to prevent collisions with developer flyweights
499 function fly(el){
500     if(!libFlyweight){
501         libFlyweight = new Ext.Element.Flyweight();
502     }
503     libFlyweight.dom = el;
504     return libFlyweight;
505 }
506
507 Ext.lib.Region = function(t, r, b, l) {
508     this.top = t;
509     this[1] = t;
510     this.right = r;
511     this.bottom = b;
512     this.left = l;
513     this[0] = l;
514 };
515
516 Ext.lib.Region.prototype = {
517     contains : function(region) {
518         return ( region.left   >= this.left   &&
519                  region.right  <= this.right  &&
520                  region.top    >= this.top    &&
521                  region.bottom <= this.bottom    );
522
523     },
524
525     getArea : function() {
526         return ( (this.bottom - this.top) * (this.right - this.left) );
527     },
528
529     intersect : function(region) {
530         var t = Math.max( this.top,    region.top    );
531         var r = Math.min( this.right,  region.right  );
532         var b = Math.min( this.bottom, region.bottom );
533         var l = Math.max( this.left,   region.left   );
534
535         if (b >= t && r >= l) {
536             return new Ext.lib.Region(t, r, b, l);
537         } else {
538             return null;
539         }
540     },
541     union : function(region) {
542         var t = Math.min( this.top,    region.top    );
543         var r = Math.max( this.right,  region.right  );
544         var b = Math.max( this.bottom, region.bottom );
545         var l = Math.min( this.left,   region.left   );
546
547         return new Ext.lib.Region(t, r, b, l);
548     },
549
550     constrainTo : function(r) {
551             this.top = this.top.constrain(r.top, r.bottom);
552             this.bottom = this.bottom.constrain(r.top, r.bottom);
553             this.left = this.left.constrain(r.left, r.right);
554             this.right = this.right.constrain(r.left, r.right);
555             return this;
556     },
557
558     adjust : function(t, l, b, r){
559         this.top += t;
560         this.left += l;
561         this.right += r;
562         this.bottom += b;
563         return this;
564     }
565 };
566
567 Ext.lib.Region.getRegion = function(el) {
568     var p = Ext.lib.Dom.getXY(el);
569
570     var t = p[1];
571     var r = p[0] + el.offsetWidth;
572     var b = p[1] + el.offsetHeight;
573     var l = p[0];
574
575     return new Ext.lib.Region(t, r, b, l);
576 };
577
578 Ext.lib.Point = function(x, y) {
579    if (Ext.isArray(x)) {
580       y = x[1];
581       x = x[0];
582    }
583     this.x = this.right = this.left = this[0] = x;
584     this.y = this.top = this.bottom = this[1] = y;
585 };
586
587 Ext.lib.Point.prototype = new Ext.lib.Region();
588
589
590 // prevent IE leaks
591 if(Ext.isIE) {
592     function fnCleanUp() {
593         var p = Function.prototype;
594         delete p.createSequence;
595         delete p.defer;
596         delete p.createDelegate;
597         delete p.createCallback;
598         delete p.createInterceptor;
599
600         window.detachEvent("onunload", fnCleanUp);
601     }
602     window.attachEvent("onunload", fnCleanUp);
603 }
604 })();