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