Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / dom / Element.alignment.js
1 /**
2  * @class Ext.core.Element
3  */
4 Ext.core.Element.addMethods({
5     /**
6      * Gets the x,y coordinates specified by the anchor position on the element.
7      * @param {String} anchor (optional) The specified anchor position (defaults to "c").  See {@link #alignTo}
8      * for details on supported anchor positions.
9      * @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead
10      * of page coordinates
11      * @param {Object} size (optional) An object containing the size to use for calculating anchor position
12      * {width: (target width), height: (target height)} (defaults to the element's current size)
13      * @return {Array} [x, y] An array containing the element's x and y coordinates
14      */
15     getAnchorXY : function(anchor, local, s){
16         //Passing a different size is useful for pre-calculating anchors,
17         //especially for anchored animations that change the el size.
18         anchor = (anchor || "tl").toLowerCase();
19         s = s || {};
20
21         var me = this,
22             vp = me.dom == document.body || me.dom == document,
23             w = s.width || vp ? Ext.core.Element.getViewWidth() : me.getWidth(),
24             h = s.height || vp ? Ext.core.Element.getViewHeight() : me.getHeight(),
25             xy,
26             r = Math.round,
27             o = me.getXY(),
28             scroll = me.getScroll(),
29             extraX = vp ? scroll.left : !local ? o[0] : 0,
30             extraY = vp ? scroll.top : !local ? o[1] : 0,
31             hash = {
32                 c  : [r(w * 0.5), r(h * 0.5)],
33                 t  : [r(w * 0.5), 0],
34                 l  : [0, r(h * 0.5)],
35                 r  : [w, r(h * 0.5)],
36                 b  : [r(w * 0.5), h],
37                 tl : [0, 0],
38                 bl : [0, h],
39                 br : [w, h],
40                 tr : [w, 0]
41             };
42
43         xy = hash[anchor];
44         return [xy[0] + extraX, xy[1] + extraY];
45     },
46
47     /**
48      * Anchors an element to another element and realigns it when the window is resized.
49      * @param {Mixed} element The element to align to.
50      * @param {String} position The position to align to.
51      * @param {Array} offsets (optional) Offset the positioning by [x, y]
52      * @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
53      * @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
54      * is a number, it is used as the buffer delay (defaults to 50ms).
55      * @param {Function} callback The function to call after the animation finishes
56      * @return {Ext.core.Element} this
57      */
58     anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
59         var me = this,
60             dom = me.dom,
61             scroll = !Ext.isEmpty(monitorScroll),
62             action = function(){
63                 Ext.fly(dom).alignTo(el, alignment, offsets, animate);
64                 Ext.callback(callback, Ext.fly(dom));
65             },
66             anchor = this.getAnchor();
67
68         // previous listener anchor, remove it
69         this.removeAnchor();
70         Ext.apply(anchor, {
71             fn: action,
72             scroll: scroll
73         });
74
75         Ext.EventManager.onWindowResize(action, null);
76
77         if(scroll){
78             Ext.EventManager.on(window, 'scroll', action, null,
79                 {buffer: !isNaN(monitorScroll) ? monitorScroll : 50});
80         }
81         action.call(me); // align immediately
82         return me;
83     },
84
85     /**
86      * Remove any anchor to this element. See {@link #anchorTo}.
87      * @return {Ext.core.Element} this
88      */
89     removeAnchor : function(){
90         var me = this,
91             anchor = this.getAnchor();
92
93         if(anchor && anchor.fn){
94             Ext.EventManager.removeResizeListener(anchor.fn);
95             if(anchor.scroll){
96                 Ext.EventManager.un(window, 'scroll', anchor.fn);
97             }
98             delete anchor.fn;
99         }
100         return me;
101     },
102
103     // private
104     getAnchor : function(){
105         var data = Ext.core.Element.data,
106             dom = this.dom;
107             if (!dom) {
108                 return;
109             }
110             var anchor = data(dom, '_anchor');
111
112         if(!anchor){
113             anchor = data(dom, '_anchor', {});
114         }
115         return anchor;
116     },
117
118     getAlignVector: function(el, spec, offset) {
119         var me = this,
120             side = {t:"top", l:"left", r:"right", b: "bottom"},
121             thisRegion = me.getRegion(),
122             elRegion;
123
124         el = Ext.get(el);
125         if(!el || !el.dom){
126             //<debug>
127             Ext.Error.raise({
128                 sourceClass: 'Ext.core.Element',
129                 sourceMethod: 'getAlignVector',
130                 msg: 'Attempted to align an element that doesn\'t exist'
131             });
132             //</debug>
133         }
134
135         elRegion = el.getRegion();
136     },
137
138     /**
139      * Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
140      * supported position values.
141      * @param {Mixed} element The element to align to.
142      * @param {String} position (optional, defaults to "tl-bl?") The position to align to.
143      * @param {Array} offsets (optional) Offset the positioning by [x, y]
144      * @return {Array} [x, y]
145      */
146     getAlignToXY : function(el, p, o){
147         el = Ext.get(el);
148
149         if(!el || !el.dom){
150             //<debug>
151             Ext.Error.raise({
152                 sourceClass: 'Ext.core.Element',
153                 sourceMethod: 'getAlignToXY',
154                 msg: 'Attempted to align an element that doesn\'t exist'
155             });
156             //</debug>
157         }
158
159         o = o || [0,0];
160         p = (!p || p == "?" ? "tl-bl?" : (!(/-/).test(p) && p !== "" ? "tl-" + p : p || "tl-bl")).toLowerCase();
161
162         var me = this,
163             d = me.dom,
164             a1,
165             a2,
166             x,
167             y,
168             //constrain the aligned el to viewport if necessary
169             w,
170             h,
171             r,
172             dw = Ext.core.Element.getViewWidth() -10, // 10px of margin for ie
173             dh = Ext.core.Element.getViewHeight()-10, // 10px of margin for ie
174             p1y,
175             p1x,
176             p2y,
177             p2x,
178             swapY,
179             swapX,
180             doc = document,
181             docElement = doc.documentElement,
182             docBody = doc.body,
183             scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0)+5,
184             scrollY = (docElement.scrollTop || docBody.scrollTop || 0)+5,
185             c = false, //constrain to viewport
186             p1 = "",
187             p2 = "",
188             m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
189
190         if(!m){
191             //<debug>
192             Ext.Error.raise({
193                 sourceClass: 'Ext.core.Element',
194                 sourceMethod: 'getAlignToXY',
195                 el: el,
196                 position: p,
197                 offset: o,
198                 msg: 'Attemmpted to align an element with an invalid position: "' + p + '"'
199             });
200             //</debug>
201         }
202
203         p1 = m[1];
204         p2 = m[2];
205         c = !!m[3];
206
207         //Subtract the aligned el's internal xy from the target's offset xy
208         //plus custom offset to get the aligned el's new offset xy
209         a1 = me.getAnchorXY(p1, true);
210         a2 = el.getAnchorXY(p2, false);
211
212         x = a2[0] - a1[0] + o[0];
213         y = a2[1] - a1[1] + o[1];
214
215         if(c){
216            w = me.getWidth();
217            h = me.getHeight();
218            r = el.getRegion();
219            //If we are at a viewport boundary and the aligned el is anchored on a target border that is
220            //perpendicular to the vp border, allow the aligned el to slide on that border,
221            //otherwise swap the aligned el to the opposite border of the target.
222            p1y = p1.charAt(0);
223            p1x = p1.charAt(p1.length-1);
224            p2y = p2.charAt(0);
225            p2x = p2.charAt(p2.length-1);
226            swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
227            swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
228
229
230            if (x + w > dw + scrollX) {
231                 x = swapX ? r.left-w : dw+scrollX-w;
232            }
233            if (x < scrollX) {
234                x = swapX ? r.right : scrollX;
235            }
236            if (y + h > dh + scrollY) {
237                 y = swapY ? r.top-h : dh+scrollY-h;
238             }
239            if (y < scrollY){
240                y = swapY ? r.bottom : scrollY;
241            }
242         }
243         return [x,y];
244     },
245
246     /**
247      * Aligns this element with another element relative to the specified anchor points. If the other element is the
248      * document it aligns it to the viewport.
249      * The position parameter is optional, and can be specified in any one of the following formats:
250      * <ul>
251      *   <li><b>Blank</b>: Defaults to aligning the element's top-left corner to the target's bottom-left corner ("tl-bl").</li>
252      *   <li><b>One anchor (deprecated)</b>: The passed anchor position is used as the target element's anchor point.
253      *       The element being aligned will position its top-left corner (tl) to that point.  <i>This method has been
254      *       deprecated in favor of the newer two anchor syntax below</i>.</li>
255      *   <li><b>Two anchors</b>: If two values from the table below are passed separated by a dash, the first value is used as the
256      *       element's anchor point, and the second value is used as the target's anchor point.</li>
257      * </ul>
258      * In addition to the anchor points, the position parameter also supports the "?" character.  If "?" is passed at the end of
259      * the position string, the element will attempt to align as specified, but the position will be adjusted to constrain to
260      * the viewport if necessary.  Note that the element being aligned might be swapped to align to a different position than
261      * that specified in order to enforce the viewport constraints.
262      * Following are all of the supported anchor positions:
263 <pre>
264 Value  Description
265 -----  -----------------------------
266 tl     The top left corner (default)
267 t      The center of the top edge
268 tr     The top right corner
269 l      The center of the left edge
270 c      In the center of the element
271 r      The center of the right edge
272 bl     The bottom left corner
273 b      The center of the bottom edge
274 br     The bottom right corner
275 </pre>
276 Example Usage:
277 <pre><code>
278 // align el to other-el using the default positioning ("tl-bl", non-constrained)
279 el.alignTo("other-el");
280
281 // align the top left corner of el with the top right corner of other-el (constrained to viewport)
282 el.alignTo("other-el", "tr?");
283
284 // align the bottom right corner of el with the center left edge of other-el
285 el.alignTo("other-el", "br-l?");
286
287 // align the center of el with the bottom left corner of other-el and
288 // adjust the x position by -6 pixels (and the y position by 0)
289 el.alignTo("other-el", "c-bl", [-6, 0]);
290 </code></pre>
291      * @param {Mixed} element The element to align to.
292      * @param {String} position (optional, defaults to "tl-bl?") The position to align to.
293      * @param {Array} offsets (optional) Offset the positioning by [x, y]
294      * @param {Boolean/Object} animate (optional) true for the default animation or a standard Element animation config object
295      * @return {Ext.core.Element} this
296      */
297     alignTo : function(element, position, offsets, animate){
298         var me = this;
299         return me.setXY(me.getAlignToXY(element, position, offsets),
300                         me.anim && !!animate ? me.anim(animate) : false);
301     },
302
303     // private ==>  used outside of core
304     adjustForConstraints : function(xy, parent) {
305         var vector = this.getConstrainVector(parent, xy);
306         if (vector) {
307             xy[0] += vector[0];
308             xy[1] += vector[1];
309         }
310         return xy;
311     },
312
313     /**
314      * <p>Returns the <code>[X, Y]</code> vector by which this element must be translated to make a best attempt
315      * to constrain within the passed constraint. Returns <code>false</code> is this element does not need to be moved.</p>
316      * <p>Priority is given to constraining the top and left within the constraint.</p>
317      * <p>The constraint may either be an existing element into which this element is to be constrained, or
318      * an {@link Ext.util.Region Region} into which this element is to be constrained.</p>
319      * @param constrainTo {Mixed} The Element or {@link Ext.util.Region Region} into which this element is to be constrained.
320      * @param proposedPosition {Array} A proposed <code>[X, Y]</code> position to test for validity and to produce a vector for instead
321      * of using this Element's current position;
322      * @returns {Array} <b>If</b> this element <i>needs</i> to be translated, an <code>[X, Y]</code>
323      * vector by which this element must be translated. Otherwise, <code>false</code>.
324      */
325     getConstrainVector: function(constrainTo, proposedPosition) {
326         if (!(constrainTo instanceof Ext.util.Region)) {
327             constrainTo = Ext.get(constrainTo).getViewRegion();
328         }
329         var thisRegion = this.getRegion(),
330             vector = [0, 0],
331             shadowSize = this.shadow && this.shadow.offset,
332             overflowed = false;
333
334         // Shift this region to occupy the proposed position
335         if (proposedPosition) {
336             thisRegion.translateBy(proposedPosition[0] - thisRegion.x, proposedPosition[1] - thisRegion.y);
337         }
338
339         // Reduce the constrain region to allow for shadow
340         // TODO: Rewrite the Shadow class. When that's done, get the extra for each side from the Shadow.
341         if (shadowSize) {
342             constrainTo.adjust(0, -shadowSize, -shadowSize, shadowSize);
343         }
344
345         // Constrain the X coordinate by however much this Element overflows
346         if (thisRegion.right > constrainTo.right) {
347             overflowed = true;
348             vector[0] = (constrainTo.right - thisRegion.right);    // overflowed the right
349         }
350         if (thisRegion.left + vector[0] < constrainTo.left) {
351             overflowed = true;
352             vector[0] = (constrainTo.left - thisRegion.left);      // overflowed the left
353         }
354
355         // Constrain the Y coordinate by however much this Element overflows
356         if (thisRegion.bottom > constrainTo.bottom) {
357             overflowed = true;
358             vector[1] = (constrainTo.bottom - thisRegion.bottom);  // overflowed the bottom
359         }
360         if (thisRegion.top + vector[1] < constrainTo.top) {
361             overflowed = true;
362             vector[1] = (constrainTo.top - thisRegion.top);        // overflowed the top
363         }
364         return overflowed ? vector : false;
365     },
366
367     /**
368     * Calculates the x, y to center this element on the screen
369     * @return {Array} The x, y values [x, y]
370     */
371     getCenterXY : function(){
372         return this.getAlignToXY(document, 'c-c');
373     },
374
375     /**
376     * Centers the Element in either the viewport, or another Element.
377     * @param {Mixed} centerIn (optional) The element in which to center the element.
378     */
379     center : function(centerIn){
380         return this.alignTo(centerIn || document, 'c-c');
381     }
382 });