Roo/form/ComboBoxArray.js
[roojs1] / Roo / Resizable.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  * @class Roo.Resizable
14  * @extends Roo.util.Observable
15  * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
16  * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
17  * the textarea in a div and set "resizeChild" to true (or to the id of the element), <b>or</b> set wrap:true in your config and
18  * the element will be wrapped for you automatically.</p>
19  * <p>Here is the list of valid resize handles:</p>
20  * <pre>
21 Value   Description
22 ------  -------------------
23  'n'     north
24  's'     south
25  'e'     east
26  'w'     west
27  'nw'    northwest
28  'sw'    southwest
29  'se'    southeast
30  'ne'    northeast
31  'hd'    horizontal drag
32  'all'   all
33 </pre>
34  * <p>Here's an example showing the creation of a typical Resizable:</p>
35  * <pre><code>
36 var resizer = new Roo.Resizable("element-id", {
37     handles: 'all',
38     minWidth: 200,
39     minHeight: 100,
40     maxWidth: 500,
41     maxHeight: 400,
42     pinned: true
43 });
44 resizer.on("resize", myHandler);
45 </code></pre>
46  * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
47  * resizer.east.setDisplayed(false);</p>
48  * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
49  * @cfg {Array/String} adjustments String "auto" or an array [width, height] with values to be <b>added</b> to the
50  * resize operation's new size (defaults to [0, 0])
51  * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
52  * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
53  * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
54  * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
55  * @cfg {Boolean} enabled False to disable resizing (defaults to true)
56  * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
57  * @cfg {Number} width The width of the element in pixels (defaults to null)
58  * @cfg {Number} height The height of the element in pixels (defaults to null)
59  * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
60  * @cfg {Number} duration Animation duration if animate = true (defaults to .35)
61  * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
62  * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined)
63  * @cfg {Boolean} multiDirectional <b>Deprecated</b>.  The old style of adding multi-direction resize handles, deprecated
64  * in favor of the handles config option (defaults to false)
65  * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
66  * @cfg {String} easing Animation easing if animate = true (defaults to 'easingOutStrong')
67  * @cfg {Number} widthIncrement The increment to snap the width resize in pixels (dynamic must be true, defaults to 0)
68  * @cfg {Number} heightIncrement The increment to snap the height resize in pixels (dynamic must be true, defaults to 0)
69  * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
70  * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
71  * @cfg {Boolean} preserveRatio True to preserve the original ratio between height and width during resize (defaults to false)
72  * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
73  * @cfg {Number} minX The minimum allowed page X for the element (only used for west resizing, defaults to 0)
74  * @cfg {Number} minY The minimum allowed page Y for the element (only used for north resizing, defaults to 0)
75  * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
76  * @constructor
77  * Create a new resizable component
78  * @param {String/HTMLElement/Roo.Element} el The id or element to resize
79  * @param {Object} config configuration options
80   */
81 Roo.Resizable = function(el, config)
82 {
83     this.el = Roo.get(el);
84
85     if(config && config.wrap){
86         config.resizeChild = this.el;
87         this.el = this.el.wrap(typeof config.wrap == "object" ? config.wrap : {cls:"xresizable-wrap"});
88         this.el.id = this.el.dom.id = config.resizeChild.id + "-rzwrap";
89         this.el.setStyle("overflow", "hidden");
90         this.el.setPositioning(config.resizeChild.getPositioning());
91         config.resizeChild.clearPositioning();
92         if(!config.width || !config.height){
93             var csize = config.resizeChild.getSize();
94             this.el.setSize(csize.width, csize.height);
95         }
96         if(config.pinned && !config.adjustments){
97             config.adjustments = "auto";
98         }
99     }
100
101     this.proxy = this.el.createProxy({tag: "div", cls: "x-resizable-proxy", id: this.el.id + "-rzproxy"});
102     this.proxy.unselectable();
103     this.proxy.enableDisplayMode('block');
104
105     Roo.apply(this, config);
106
107     if(this.pinned){
108         this.disableTrackOver = true;
109         this.el.addClass("x-resizable-pinned");
110     }
111     // if the element isn't positioned, make it relative
112     var position = this.el.getStyle("position");
113     if(position != "absolute" && position != "fixed"){
114         this.el.setStyle("position", "relative");
115     }
116     if(!this.handles){ // no handles passed, must be legacy style
117         this.handles = 's,e,se';
118         if(this.multiDirectional){
119             this.handles += ',n,w';
120         }
121     }
122     if(this.handles == "all"){
123         this.handles = "n s e w ne nw se sw";
124     }
125     var hs = this.handles.split(/\s*?[,;]\s*?| /);
126     var ps = Roo.Resizable.positions;
127     for(var i = 0, len = hs.length; i < len; i++){
128         if(hs[i] && ps[hs[i]]){
129             var pos = ps[hs[i]];
130             this[pos] = new Roo.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent);
131         }
132     }
133     // legacy
134     this.corner = this.southeast;
135     
136     // updateBox = the box can move..
137     if(this.handles.indexOf("n") != -1 || this.handles.indexOf("w") != -1 || this.handles.indexOf("hd") != -1) {
138         this.updateBox = true;
139     }
140
141     this.activeHandle = null;
142
143     if(this.resizeChild){
144         if(typeof this.resizeChild == "boolean"){
145             this.resizeChild = Roo.get(this.el.dom.firstChild, true);
146         }else{
147             this.resizeChild = Roo.get(this.resizeChild, true);
148         }
149     }
150     
151     if(this.adjustments == "auto"){
152         var rc = this.resizeChild;
153         var hw = this.west, he = this.east, hn = this.north, hs = this.south;
154         if(rc && (hw || hn)){
155             rc.position("relative");
156             rc.setLeft(hw ? hw.el.getWidth() : 0);
157             rc.setTop(hn ? hn.el.getHeight() : 0);
158         }
159         this.adjustments = [
160             (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
161             (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
162         ];
163     }
164
165     if(this.draggable){
166         this.dd = this.dynamic ?
167             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
168         this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
169     }
170
171     // public events
172     this.addEvents({
173         /**
174          * @event beforeresize
175          * Fired before resize is allowed. Set enabled to false to cancel resize.
176          * @param {Roo.Resizable} this
177          * @param {Roo.EventObject} e The mousedown event
178          */
179         "beforeresize" : true,
180         /**
181          * @event resizing
182          * Fired a resizing.
183          * @param {Roo.Resizable} this
184          * @param {Number} x The new x position
185          * @param {Number} y The new y position
186          * @param {Number} w The new w width
187          * @param {Number} h The new h hight
188          * @param {Roo.EventObject} e The mouseup event
189          */
190         "resizing" : true,
191         /**
192          * @event resize
193          * Fired after a resize.
194          * @param {Roo.Resizable} this
195          * @param {Number} width The new width
196          * @param {Number} height The new height
197          * @param {Roo.EventObject} e The mouseup event
198          */
199         "resize" : true
200     });
201
202     if(this.width !== null && this.height !== null){
203         this.resizeTo(this.width, this.height);
204     }else{
205         this.updateChildSize();
206     }
207     if(Roo.isIE){
208         this.el.dom.style.zoom = 1;
209     }
210     Roo.Resizable.superclass.constructor.call(this);
211 };
212
213 Roo.extend(Roo.Resizable, Roo.util.Observable, {
214         resizeChild : false,
215         adjustments : [0, 0],
216         minWidth : 5,
217         minHeight : 5,
218         maxWidth : 10000,
219         maxHeight : 10000,
220         enabled : true,
221         animate : false,
222         duration : .35,
223         dynamic : false,
224         handles : false,
225         multiDirectional : false,
226         disableTrackOver : false,
227         easing : 'easeOutStrong',
228         widthIncrement : 0,
229         heightIncrement : 0,
230         pinned : false,
231         width : null,
232         height : null,
233         preserveRatio : false,
234         transparent: false,
235         minX: 0,
236         minY: 0,
237         draggable: false,
238
239         /**
240          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
241          */
242         constrainTo: undefined,
243         /**
244          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
245          */
246         resizeRegion: undefined,
247
248
249     /**
250      * Perform a manual resize
251      * @param {Number} width
252      * @param {Number} height
253      */
254     resizeTo : function(width, height){
255         this.el.setSize(width, height);
256         this.updateChildSize();
257         this.fireEvent("resize", this, width, height, null);
258     },
259
260     // private
261     startSizing : function(e, handle){
262         this.fireEvent("beforeresize", this, e);
263         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
264
265             if(!this.overlay){
266                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
267                 this.overlay.unselectable();
268                 this.overlay.enableDisplayMode("block");
269                 this.overlay.on("mousemove", this.onMouseMove, this);
270                 this.overlay.on("mouseup", this.onMouseUp, this);
271             }
272             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
273
274             this.resizing = true;
275             this.startBox = this.el.getBox();
276             this.startPoint = e.getXY();
277             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
278                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
279
280             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
281             this.overlay.show();
282
283             if(this.constrainTo) {
284                 var ct = Roo.get(this.constrainTo);
285                 this.resizeRegion = ct.getRegion().adjust(
286                     ct.getFrameWidth('t'),
287                     ct.getFrameWidth('l'),
288                     -ct.getFrameWidth('b'),
289                     -ct.getFrameWidth('r')
290                 );
291             }
292
293             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
294             this.proxy.show();
295             this.proxy.setBox(this.startBox);
296             if(!this.dynamic){
297                 this.proxy.setStyle('visibility', 'visible');
298             }
299         }
300     },
301
302     // private
303     onMouseDown : function(handle, e){
304         if(this.enabled){
305             e.stopEvent();
306             this.activeHandle = handle;
307             this.startSizing(e, handle);
308         }
309     },
310
311     // private
312     onMouseUp : function(e){
313         var size = this.resizeElement();
314         this.resizing = false;
315         this.handleOut();
316         this.overlay.hide();
317         this.proxy.hide();
318         this.fireEvent("resize", this, size.width, size.height, e);
319     },
320
321     // private
322     updateChildSize : function(){
323         
324         if(this.resizeChild){
325             var el = this.el;
326             var child = this.resizeChild;
327             var adj = this.adjustments;
328             if(el.dom.offsetWidth){
329                 var b = el.getSize(true);
330                 child.setSize(b.width+adj[0], b.height+adj[1]);
331             }
332             // Second call here for IE
333             // The first call enables instant resizing and
334             // the second call corrects scroll bars if they
335             // exist
336             if(Roo.isIE){
337                 setTimeout(function(){
338                     if(el.dom.offsetWidth){
339                         var b = el.getSize(true);
340                         child.setSize(b.width+adj[0], b.height+adj[1]);
341                     }
342                 }, 10);
343             }
344         }
345     },
346
347     // private
348     snap : function(value, inc, min){
349         if(!inc || !value) return value;
350         var newValue = value;
351         var m = value % inc;
352         if(m > 0){
353             if(m > (inc/2)){
354                 newValue = value + (inc-m);
355             }else{
356                 newValue = value - m;
357             }
358         }
359         return Math.max(min, newValue);
360     },
361
362     // private
363     resizeElement : function(){
364         var box = this.proxy.getBox();
365         if(this.updateBox){
366             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
367         }else{
368             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
369         }
370         this.updateChildSize();
371         if(!this.dynamic){
372             this.proxy.hide();
373         }
374         return box;
375     },
376
377     // private
378     constrain : function(v, diff, m, mx){
379         if(v - diff < m){
380             diff = v - m;
381         }else if(v - diff > mx){
382             diff = mx - v;
383         }
384         return diff;
385     },
386
387     // private
388     onMouseMove : function(e){
389         
390         if(this.enabled){
391             try{// try catch so if something goes wrong the user doesn't get hung
392
393             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
394                 return;
395             }
396
397             //var curXY = this.startPoint;
398             var curSize = this.curSize || this.startBox;
399             var x = this.startBox.x, y = this.startBox.y;
400             var ox = x, oy = y;
401             var w = curSize.width, h = curSize.height;
402             var ow = w, oh = h;
403             var mw = this.minWidth, mh = this.minHeight;
404             var mxw = this.maxWidth, mxh = this.maxHeight;
405             var wi = this.widthIncrement;
406             var hi = this.heightIncrement;
407
408             var eventXY = e.getXY();
409             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
410             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
411
412             var pos = this.activeHandle.position;
413
414             switch(pos){
415                 case "east":
416                     w += diffX;
417                     w = Math.min(Math.max(mw, w), mxw);
418                     break;
419              
420                 case "south":
421                     h += diffY;
422                     h = Math.min(Math.max(mh, h), mxh);
423                     break;
424                 case "southeast":
425                     w += diffX;
426                     h += diffY;
427                     w = Math.min(Math.max(mw, w), mxw);
428                     h = Math.min(Math.max(mh, h), mxh);
429                     break;
430                 case "north":
431                     diffY = this.constrain(h, diffY, mh, mxh);
432                     y += diffY;
433                     h -= diffY;
434                     break;
435                 case "hdrag":
436                     
437                     if (wi) {
438                         var adiffX = Math.abs(diffX);
439                         var sub = (adiffX % wi); // how much 
440                         if (sub > (wi/2)) { // far enough to snap
441                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
442                         } else {
443                             // remove difference.. 
444                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
445                         }
446                     }
447                     x += diffX;
448                     x = Math.max(this.minX, x);
449                     break;
450                 case "west":
451                     diffX = this.constrain(w, diffX, mw, mxw);
452                     x += diffX;
453                     w -= diffX;
454                     break;
455                 case "northeast":
456                     w += diffX;
457                     w = Math.min(Math.max(mw, w), mxw);
458                     diffY = this.constrain(h, diffY, mh, mxh);
459                     y += diffY;
460                     h -= diffY;
461                     break;
462                 case "northwest":
463                     diffX = this.constrain(w, diffX, mw, mxw);
464                     diffY = this.constrain(h, diffY, mh, mxh);
465                     y += diffY;
466                     h -= diffY;
467                     x += diffX;
468                     w -= diffX;
469                     break;
470                case "southwest":
471                     diffX = this.constrain(w, diffX, mw, mxw);
472                     h += diffY;
473                     h = Math.min(Math.max(mh, h), mxh);
474                     x += diffX;
475                     w -= diffX;
476                     break;
477             }
478
479             var sw = this.snap(w, wi, mw);
480             var sh = this.snap(h, hi, mh);
481             if(sw != w || sh != h){
482                 switch(pos){
483                     case "northeast":
484                         y -= sh - h;
485                     break;
486                     case "north":
487                         y -= sh - h;
488                         break;
489                     case "southwest":
490                         x -= sw - w;
491                     break;
492                     case "west":
493                         x -= sw - w;
494                         break;
495                     case "northwest":
496                         x -= sw - w;
497                         y -= sh - h;
498                     break;
499                 }
500                 w = sw;
501                 h = sh;
502             }
503
504             if(this.preserveRatio){
505                 switch(pos){
506                     case "southeast":
507                     case "east":
508                         h = oh * (w/ow);
509                         h = Math.min(Math.max(mh, h), mxh);
510                         w = ow * (h/oh);
511                        break;
512                     case "south":
513                         w = ow * (h/oh);
514                         w = Math.min(Math.max(mw, w), mxw);
515                         h = oh * (w/ow);
516                         break;
517                     case "northeast":
518                         w = ow * (h/oh);
519                         w = Math.min(Math.max(mw, w), mxw);
520                         h = oh * (w/ow);
521                     break;
522                     case "north":
523                         var tw = w;
524                         w = ow * (h/oh);
525                         w = Math.min(Math.max(mw, w), mxw);
526                         h = oh * (w/ow);
527                         x += (tw - w) / 2;
528                         break;
529                     case "southwest":
530                         h = oh * (w/ow);
531                         h = Math.min(Math.max(mh, h), mxh);
532                         var tw = w;
533                         w = ow * (h/oh);
534                         x += tw - w;
535                         break;
536                     case "west":
537                         var th = h;
538                         h = oh * (w/ow);
539                         h = Math.min(Math.max(mh, h), mxh);
540                         y += (th - h) / 2;
541                         var tw = w;
542                         w = ow * (h/oh);
543                         x += tw - w;
544                        break;
545                     case "northwest":
546                         var tw = w;
547                         var th = h;
548                         h = oh * (w/ow);
549                         h = Math.min(Math.max(mh, h), mxh);
550                         w = ow * (h/oh);
551                         y += th - h;
552                         x += tw - w;
553                        break;
554
555                 }
556             }
557             if (pos == 'hdrag') {
558                 w = ow;
559             }
560             this.proxy.setBounds(x, y, w, h);
561             if(this.dynamic){
562                 this.resizeElement();
563             }
564             }catch(e){}
565         }
566         this.fireEvent("resizing", this, x, y, w, h, e);
567     },
568
569     // private
570     handleOver : function(){
571         if(this.enabled){
572             this.el.addClass("x-resizable-over");
573         }
574     },
575
576     // private
577     handleOut : function(){
578         if(!this.resizing){
579             this.el.removeClass("x-resizable-over");
580         }
581     },
582
583     /**
584      * Returns the element this component is bound to.
585      * @return {Roo.Element}
586      */
587     getEl : function(){
588         return this.el;
589     },
590
591     /**
592      * Returns the resizeChild element (or null).
593      * @return {Roo.Element}
594      */
595     getResizeChild : function(){
596         return this.resizeChild;
597     },
598     groupHandler : function()
599     {
600         
601     },
602     /**
603      * Destroys this resizable. If the element was wrapped and
604      * removeEl is not true then the element remains.
605      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
606      */
607     destroy : function(removeEl){
608         this.proxy.remove();
609         if(this.overlay){
610             this.overlay.removeAllListeners();
611             this.overlay.remove();
612         }
613         var ps = Roo.Resizable.positions;
614         for(var k in ps){
615             if(typeof ps[k] != "function" && this[ps[k]]){
616                 var h = this[ps[k]];
617                 h.el.removeAllListeners();
618                 h.el.remove();
619             }
620         }
621         if(removeEl){
622             this.el.update("");
623             this.el.remove();
624         }
625     }
626 });
627
628 // private
629 // hash to map config positions to true positions
630 Roo.Resizable.positions = {
631     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
632     hd: "hdrag"
633 };
634
635 // private
636 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
637     if(!this.tpl){
638         // only initialize the template if resizable is used
639         var tpl = Roo.DomHelper.createTemplate(
640             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
641         );
642         tpl.compile();
643         Roo.Resizable.Handle.prototype.tpl = tpl;
644     }
645     this.position = pos;
646     this.rz = rz;
647     // show north drag fro topdra
648     var handlepos = pos == 'hdrag' ? 'north' : pos;
649     
650     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
651     if (pos == 'hdrag') {
652         this.el.setStyle('cursor', 'pointer');
653     }
654     this.el.unselectable();
655     if(transparent){
656         this.el.setOpacity(0);
657     }
658     this.el.on("mousedown", this.onMouseDown, this);
659     if(!disableTrackOver){
660         this.el.on("mouseover", this.onMouseOver, this);
661         this.el.on("mouseout", this.onMouseOut, this);
662     }
663 };
664
665 // private
666 Roo.Resizable.Handle.prototype = {
667     afterResize : function(rz){
668         Roo.log('after?');
669         // do nothing
670     },
671     // private
672     onMouseDown : function(e){
673         this.rz.onMouseDown(this, e);
674     },
675     // private
676     onMouseOver : function(e){
677         this.rz.handleOver(this, e);
678     },
679     // private
680     onMouseOut : function(e){
681         this.rz.handleOut(this, e);
682     }
683 };