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