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