Roo/Resizable.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         Roo.log('in11?');
167         this.dd = this.dynamic ?
168             this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
169         //this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
170     }
171
172     // public events
173     this.addEvents({
174         /**
175          * @event beforeresize
176          * Fired before resize is allowed. Set enabled to false to cancel resize.
177          * @param {Roo.Resizable} this
178          * @param {Roo.EventObject} e The mousedown event
179          */
180         "beforeresize" : true,
181         /**
182          * @event resize
183          * Fired after a resize.
184          * @param {Roo.Resizable} this
185          * @param {Number} width The new width
186          * @param {Number} height The new height
187          * @param {Roo.EventObject} e The mouseup event
188          */
189         "resize" : true
190     });
191
192     if(this.width !== null && this.height !== null){
193         this.resizeTo(this.width, this.height);
194     }else{
195         this.updateChildSize();
196     }
197     if(Roo.isIE){
198         this.el.dom.style.zoom = 1;
199     }
200     Roo.Resizable.superclass.constructor.call(this);
201 };
202
203 Roo.extend(Roo.Resizable, Roo.util.Observable, {
204         resizeChild : false,
205         adjustments : [0, 0],
206         minWidth : 5,
207         minHeight : 5,
208         maxWidth : 10000,
209         maxHeight : 10000,
210         enabled : true,
211         animate : false,
212         duration : .35,
213         dynamic : false,
214         handles : false,
215         multiDirectional : false,
216         disableTrackOver : false,
217         easing : 'easeOutStrong',
218         widthIncrement : 0,
219         heightIncrement : 0,
220         pinned : false,
221         width : null,
222         height : null,
223         preserveRatio : false,
224         transparent: false,
225         minX: 0,
226         minY: 0,
227         draggable: false,
228
229         /**
230          * @cfg {String/HTMLElement/Element} constrainTo Constrain the resize to a particular element
231          */
232         constrainTo: undefined,
233         /**
234          * @cfg {Roo.lib.Region} resizeRegion Constrain the resize to a particular region
235          */
236         resizeRegion: undefined,
237
238
239     /**
240      * Perform a manual resize
241      * @param {Number} width
242      * @param {Number} height
243      */
244     resizeTo : function(width, height){
245         this.el.setSize(width, height);
246         this.updateChildSize();
247         this.fireEvent("resize", this, width, height, null);
248     },
249
250     // private
251     startSizing : function(e, handle){
252         this.fireEvent("beforeresize", this, e);
253         if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
254
255             if(!this.overlay){
256                 this.overlay = this.el.createProxy({tag: "div", cls: "x-resizable-overlay", html: "&#160;"});
257                 this.overlay.unselectable();
258                 this.overlay.enableDisplayMode("block");
259                 this.overlay.on("mousemove", this.onMouseMove, this);
260                 this.overlay.on("mouseup", this.onMouseUp, this);
261             }
262             this.overlay.setStyle("cursor", handle.el.getStyle("cursor"));
263
264             this.resizing = true;
265             this.startBox = this.el.getBox();
266             this.startPoint = e.getXY();
267             this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
268                             (this.startBox.y + this.startBox.height) - this.startPoint[1]];
269
270             this.overlay.setSize(Roo.lib.Dom.getViewWidth(true), Roo.lib.Dom.getViewHeight(true));
271             this.overlay.show();
272
273             if(this.constrainTo) {
274                 var ct = Roo.get(this.constrainTo);
275                 this.resizeRegion = ct.getRegion().adjust(
276                     ct.getFrameWidth('t'),
277                     ct.getFrameWidth('l'),
278                     -ct.getFrameWidth('b'),
279                     -ct.getFrameWidth('r')
280                 );
281             }
282
283             this.proxy.setStyle('visibility', 'hidden'); // workaround display none
284             this.proxy.show();
285             this.proxy.setBox(this.startBox);
286             if(!this.dynamic){
287                 this.proxy.setStyle('visibility', 'visible');
288             }
289         }
290     },
291
292     // private
293     onMouseDown : function(handle, e){
294         if(this.enabled){
295             e.stopEvent();
296             this.activeHandle = handle;
297             this.startSizing(e, handle);
298         }
299     },
300
301     // private
302     onMouseUp : function(e){
303         var size = this.resizeElement();
304         this.resizing = false;
305         this.handleOut();
306         this.overlay.hide();
307         this.proxy.hide();
308         this.fireEvent("resize", this, size.width, size.height, e);
309     },
310
311     // private
312     updateChildSize : function(){
313         
314         if(this.resizeChild){
315             Roo.log('in?');
316             var el = this.el;
317             var child = this.resizeChild;
318             var adj = this.adjustments;
319             if(el.dom.offsetWidth){
320                 var b = el.getSize(true);
321                 child.setSize(b.width+adj[0], b.height+adj[1]);
322             }
323             // Second call here for IE
324             // The first call enables instant resizing and
325             // the second call corrects scroll bars if they
326             // exist
327             if(Roo.isIE){
328                 setTimeout(function(){
329                     if(el.dom.offsetWidth){
330                         var b = el.getSize(true);
331                         child.setSize(b.width+adj[0], b.height+adj[1]);
332                     }
333                 }, 10);
334             }
335         }
336     },
337
338     // private
339     snap : function(value, inc, min){
340         if(!inc || !value) return value;
341         var newValue = value;
342         var m = value % inc;
343         if(m > 0){
344             if(m > (inc/2)){
345                 newValue = value + (inc-m);
346             }else{
347                 newValue = value - m;
348             }
349         }
350         return Math.max(min, newValue);
351     },
352
353     // private
354     resizeElement : function(){
355         var box = this.proxy.getBox();
356         if(this.updateBox){
357             this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
358         }else{
359             this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
360         }
361         this.updateChildSize();
362         if(!this.dynamic){
363             this.proxy.hide();
364         }
365         return box;
366     },
367
368     // private
369     constrain : function(v, diff, m, mx){
370         if(v - diff < m){
371             diff = v - m;
372         }else if(v - diff > mx){
373             diff = mx - v;
374         }
375         return diff;
376     },
377
378     // private
379     onMouseMove : function(e){
380         if(this.enabled){
381             try{// try catch so if something goes wrong the user doesn't get hung
382
383             if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
384                 return;
385             }
386
387             //var curXY = this.startPoint;
388             var curSize = this.curSize || this.startBox;
389             var x = this.startBox.x, y = this.startBox.y;
390             var ox = x, oy = y;
391             var w = curSize.width, h = curSize.height;
392             var ow = w, oh = h;
393             var mw = this.minWidth, mh = this.minHeight;
394             var mxw = this.maxWidth, mxh = this.maxHeight;
395             var wi = this.widthIncrement;
396             var hi = this.heightIncrement;
397
398             var eventXY = e.getXY();
399             var diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0]));
400             var diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1]));
401
402             var pos = this.activeHandle.position;
403
404             switch(pos){
405                 case "east":
406                     w += diffX;
407                     w = Math.min(Math.max(mw, w), mxw);
408                     break;
409              
410                 case "south":
411                     h += diffY;
412                     h = Math.min(Math.max(mh, h), mxh);
413                     break;
414                 case "southeast":
415                     w += diffX;
416                     h += diffY;
417                     w = Math.min(Math.max(mw, w), mxw);
418                     h = Math.min(Math.max(mh, h), mxh);
419                     break;
420                 case "north":
421                     diffY = this.constrain(h, diffY, mh, mxh);
422                     y += diffY;
423                     h -= diffY;
424                     break;
425                 case "hdrag":
426                     
427                     if (wi) {
428                         var adiffX = Math.abs(diffX);
429                         var sub = (adiffX % wi); // how much 
430                         if (sub > (wi/2)) { // far enough to snap
431                             diffX = (diffX > 0) ? diffX-sub + wi : diffX+sub - wi;
432                         } else {
433                             // remove difference.. 
434                             diffX = (diffX > 0) ? diffX-sub : diffX+sub;
435                         }
436                     }
437                     x += diffX;
438                     x = Math.max(this.minX, x);
439                     break;
440                 case "west":
441                     diffX = this.constrain(w, diffX, mw, mxw);
442                     x += diffX;
443                     w -= diffX;
444                     break;
445                 case "northeast":
446                     w += diffX;
447                     w = Math.min(Math.max(mw, w), mxw);
448                     diffY = this.constrain(h, diffY, mh, mxh);
449                     y += diffY;
450                     h -= diffY;
451                     break;
452                 case "northwest":
453                     diffX = this.constrain(w, diffX, mw, mxw);
454                     diffY = this.constrain(h, diffY, mh, mxh);
455                     y += diffY;
456                     h -= diffY;
457                     x += diffX;
458                     w -= diffX;
459                     break;
460                case "southwest":
461                     diffX = this.constrain(w, diffX, mw, mxw);
462                     h += diffY;
463                     h = Math.min(Math.max(mh, h), mxh);
464                     x += diffX;
465                     w -= diffX;
466                     break;
467             }
468
469             var sw = this.snap(w, wi, mw);
470             var sh = this.snap(h, hi, mh);
471             if(sw != w || sh != h){
472                 switch(pos){
473                     case "northeast":
474                         y -= sh - h;
475                     break;
476                     case "north":
477                         y -= sh - h;
478                         break;
479                     case "southwest":
480                         x -= sw - w;
481                     break;
482                     case "west":
483                         x -= sw - w;
484                         break;
485                     case "northwest":
486                         x -= sw - w;
487                         y -= sh - h;
488                     break;
489                 }
490                 w = sw;
491                 h = sh;
492             }
493
494             if(this.preserveRatio){
495                 switch(pos){
496                     case "southeast":
497                     case "east":
498                         h = oh * (w/ow);
499                         h = Math.min(Math.max(mh, h), mxh);
500                         w = ow * (h/oh);
501                        break;
502                     case "south":
503                         w = ow * (h/oh);
504                         w = Math.min(Math.max(mw, w), mxw);
505                         h = oh * (w/ow);
506                         break;
507                     case "northeast":
508                         w = ow * (h/oh);
509                         w = Math.min(Math.max(mw, w), mxw);
510                         h = oh * (w/ow);
511                     break;
512                     case "north":
513                         var tw = w;
514                         w = ow * (h/oh);
515                         w = Math.min(Math.max(mw, w), mxw);
516                         h = oh * (w/ow);
517                         x += (tw - w) / 2;
518                         break;
519                     case "southwest":
520                         h = oh * (w/ow);
521                         h = Math.min(Math.max(mh, h), mxh);
522                         var tw = w;
523                         w = ow * (h/oh);
524                         x += tw - w;
525                         break;
526                     case "west":
527                         var th = h;
528                         h = oh * (w/ow);
529                         h = Math.min(Math.max(mh, h), mxh);
530                         y += (th - h) / 2;
531                         var tw = w;
532                         w = ow * (h/oh);
533                         x += tw - w;
534                        break;
535                     case "northwest":
536                         var tw = w;
537                         var th = h;
538                         h = oh * (w/ow);
539                         h = Math.min(Math.max(mh, h), mxh);
540                         w = ow * (h/oh);
541                         y += th - h;
542                         x += tw - w;
543                        break;
544
545                 }
546             }
547             if (pos == 'hdrag') {
548                 w = ow;
549             }
550             this.proxy.setBounds(x, y, w, h);
551             if(this.dynamic){
552                 this.resizeElement();
553             }
554             }catch(e){}
555         }
556     },
557
558     // private
559     handleOver : function(){
560         if(this.enabled){
561             this.el.addClass("x-resizable-over");
562         }
563     },
564
565     // private
566     handleOut : function(){
567         if(!this.resizing){
568             this.el.removeClass("x-resizable-over");
569         }
570     },
571
572     /**
573      * Returns the element this component is bound to.
574      * @return {Roo.Element}
575      */
576     getEl : function(){
577         return this.el;
578     },
579
580     /**
581      * Returns the resizeChild element (or null).
582      * @return {Roo.Element}
583      */
584     getResizeChild : function(){
585         return this.resizeChild;
586     },
587     groupHandler : function()
588     {
589         
590     },
591     /**
592      * Destroys this resizable. If the element was wrapped and
593      * removeEl is not true then the element remains.
594      * @param {Boolean} removeEl (optional) true to remove the element from the DOM
595      */
596     destroy : function(removeEl){
597         this.proxy.remove();
598         if(this.overlay){
599             this.overlay.removeAllListeners();
600             this.overlay.remove();
601         }
602         var ps = Roo.Resizable.positions;
603         for(var k in ps){
604             if(typeof ps[k] != "function" && this[ps[k]]){
605                 var h = this[ps[k]];
606                 h.el.removeAllListeners();
607                 h.el.remove();
608             }
609         }
610         if(removeEl){
611             this.el.update("");
612             this.el.remove();
613         }
614     }
615 });
616
617 // private
618 // hash to map config positions to true positions
619 Roo.Resizable.positions = {
620     n: "north", s: "south", e: "east", w: "west", se: "southeast", sw: "southwest", nw: "northwest", ne: "northeast", 
621     hd: "hdrag"
622 };
623
624 // private
625 Roo.Resizable.Handle = function(rz, pos, disableTrackOver, transparent){
626     if(!this.tpl){
627         // only initialize the template if resizable is used
628         var tpl = Roo.DomHelper.createTemplate(
629             {tag: "div", cls: "x-resizable-handle x-resizable-handle-{0}"}
630         );
631         tpl.compile();
632         Roo.Resizable.Handle.prototype.tpl = tpl;
633     }
634     this.position = pos;
635     this.rz = rz;
636     // show north drag fro topdra
637     var handlepos = pos == 'hdrag' ? 'north' : pos;
638     
639     this.el = this.tpl.append(rz.el.dom, [handlepos], true);
640     if (pos == 'hdrag') {
641         this.el.setStyle('cursor', 'pointer');
642     }
643     this.el.unselectable();
644     if(transparent){
645         this.el.setOpacity(0);
646     }
647     this.el.on("mousedown", this.onMouseDown, this);
648     if(!disableTrackOver){
649         this.el.on("mouseover", this.onMouseOver, this);
650         this.el.on("mouseout", this.onMouseOut, this);
651     }
652 };
653
654 // private
655 Roo.Resizable.Handle.prototype = {
656     afterResize : function(rz){
657         // do nothing
658     },
659     // private
660     onMouseDown : function(e){
661         this.rz.onMouseDown(this, e);
662     },
663     // private
664     onMouseOver : function(e){
665         this.rz.handleOver(this, e);
666     },
667     // private
668     onMouseOut : function(e){
669         this.rz.handleOut(this, e);
670     }
671 };