2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('dd-constrain', function(Y) {
12 * The Drag & Drop Utility allows you to create a draggable interface efficiently, buffering you from browser-level abnormalities and enabling you to focus on the interesting logic surrounding your particular implementation. This component enables you to create a variety of standard draggable objects with just a few lines of code and then, using its extensive API, add your own specific implementation logic.
14 * @submodule dd-constrain
17 * Plugin for the dd-drag module to add the constraining methods to it. It supports constraining to a node or viewport. It supports tick based moves and XY axis constraints.
18 * @class DDConstrained
24 var DRAG_NODE = 'dragNode',
25 OFFSET_HEIGHT = 'offsetHeight',
26 OFFSET_WIDTH = 'offsetWidth',
28 TICK_X_ARRAY = 'tickXArray',
29 TICK_Y_ARRAY = 'tickYArray',
39 * @event drag:tickAlignX
40 * @description Fires when this node is aligned with the tickX value.
41 * @param {Event.Facade} event An Event Facade object
42 * @type {Event.Custom}
44 EV_TICK_ALIGN_X = 'drag:tickAlignX',
47 * @event drag:tickAlignY
48 * @description Fires when this node is aligned with the tickY value.
49 * @param {Event.Facade} event An Event Facade object
50 * @type {Event.Custom}
52 EV_TICK_ALIGN_Y = 'drag:tickAlignY',
54 C = function(config) {
55 this._lazyAddAttrs = false;
56 C.superclass.constructor.apply(this, arguments);
59 C.NAME = 'ddConstrained';
66 * @description The Constrained instance will be placed on the Drag instance under the con namespace.
76 * @description Stick the drag movement to the X-Axis. Default: false
84 * @description Stick the drag movement to the Y-Axis
92 * @description The X tick offset the drag node should snap to on each drag move. False for no ticks. Default: false
100 * @description The Y tick offset the drag node should snap to on each drag move. False for no ticks. Default: false
107 * @attribute tickXArray
108 * @description An array of page coordinates to use as X ticks for drag movement.
115 * @attribute tickYArray
116 * @description An array of page coordinates to use as Y ticks for drag movement.
124 * @description CSS style string for the gutter of a region (supports negative values): '5 0' (sets top and bottom to 5px, left and right to 0px), '1 2 3 4' (top 1px, right 2px, bottom 3px, left 4px)
129 setter: function(gutter) {
130 return Y.DD.DDM.cssSizestoObject(gutter);
134 * @attribute constrain
135 * @description Will attempt to constrain the drag node to the boundaries. Arguments:<br>
136 * 'view': Contrain to Viewport<br>
137 * '#selector_string': Constrain to this node<br>
138 * '{Region Object}': An Object Literal containing a valid region (top, right, bottom, left) of page positions
139 * @type {String/Object/Node}
143 setter: function(con) {
144 var node = Y.one(con);
153 * @attribute constrain2region
154 * @description An Object Literal containing a valid region (top, right, bottom, left) of page positions to constrain the drag node to.
158 setter: function(r) {
159 return this.set('constrain', r);
164 * @attribute constrain2node
165 * @description Will attempt to constrain the drag node to the boundaries of this node.
169 setter: function(n) {
170 return this.set('constrain', Y.one(n));
175 * @attribute constrain2view
176 * @description Will attempt to constrain the drag node to the boundaries of the viewport region.
180 setter: function(n) {
181 return this.set('constrain', VIEW);
185 * @attribute cacheRegion
186 * @description Should the region be cached for performace. Default: true
195 _lastTickXFired: null,
196 _lastTickYFired: null,
198 initializer: function() {
199 this._createEvents();
201 this.get(HOST).on('drag:end', Y.bind(this._handleEnd, this));
202 this.get(HOST).on('drag:start', Y.bind(this._handleStart, this));
203 this.get(HOST).after('drag:align', Y.bind(this.align, this));
204 this.get(HOST).after('drag:drag', Y.bind(this.drag, this));
208 * @method _createEvents
209 * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling.
211 _createEvents: function() {
219 Y.each(ev, function(v, k) {
232 * @description Fires on drag:end
234 _handleEnd: function() {
235 this._lastTickYFired = null;
236 this._lastTickXFired = null;
240 * @method _handleStart
241 * @description Fires on drag:start and clears the _regionCache
243 _handleStart: function() {
248 * @property _regionCache
249 * @description Store a cache of the region that we are constraining to
255 * @method _cacheRegion
256 * @description Get's the region and caches it, called from window.resize and when the cache is null
258 _cacheRegion: function() {
259 this._regionCache = this.get('constrain').get('region');
263 * @description Reset the internal region cache.
265 resetCache: function() {
266 this._regionCache = null;
270 * @method _getConstraint
271 * @description Standardizes the 'constraint' attribute
273 _getConstraint: function() {
274 var con = this.get('constrain'),
275 g = this.get('gutter'),
279 if (con instanceof Y.Node) {
280 if (!this._regionCache) {
281 Y.on('resize', Y.bind(this._cacheRegion, this), Y.config.win);
284 region = Y.clone(this._regionCache);
285 if (!this.get('cacheRegion')) {
288 } else if (Y.Lang.isObject(con)) {
289 region = Y.clone(con);
292 if (!con || !region) {
296 region = this.get(HOST).get(DRAG_NODE).get('viewportRegion');
299 Y.each(g, function(i, n) {
300 if ((n == RIGHT) || (n == BOTTOM)) {
311 * @description Get the active region: viewport, node, custom region
312 * @param {Boolean} inc Include the node's height and width
315 getRegion: function(inc) {
316 var r = {}, oh = null, ow = null,
317 host = this.get(HOST);
319 r = this._getConstraint();
322 oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT);
323 ow = host.get(DRAG_NODE).get(OFFSET_WIDTH);
324 r[RIGHT] = r[RIGHT] - ow;
325 r[BOTTOM] = r[BOTTOM] - oh;
331 * @method _checkRegion
332 * @description Check if xy is inside a given region, if not change to it be inside.
333 * @param {Array} _xy The XY to check if it's in the current region, if it isn't inside the region, it will reset the xy array to be inside the region.
334 * @return {Array} The new XY that is inside the region
336 _checkRegion: function(_xy) {
338 r = this.getRegion(),
339 host = this.get(HOST),
340 oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT),
341 ow = host.get(DRAG_NODE).get(OFFSET_WIDTH);
343 if (oxy[1] > (r[BOTTOM] - oh)) {
344 _xy[1] = (r[BOTTOM] - oh);
346 if (r[TOP] > oxy[1]) {
350 if (oxy[0] > (r[RIGHT] - ow)) {
351 _xy[0] = (r[RIGHT] - ow);
353 if (r[LEFT] > oxy[0]) {
361 * @description Checks if the XY passed or the dragNode is inside the active region.
362 * @param {Array} xy Optional XY to check, if not supplied this.get('dragNode').getXY() is used.
363 * @return {Boolean} True if the XY is inside the region, false otherwise.
365 inRegion: function(xy) {
366 xy = xy || this.get(HOST).get(DRAG_NODE).getXY();
368 var _xy = this._checkRegion([xy[0], xy[1]]),
370 if ((xy[0] === _xy[0]) && (xy[1] === _xy[1])) {
377 * @description Modifies the Drag.actXY method from the after drag:align event. This is where the constraining happens.
380 var host = this.get(HOST),
381 _xy = [host.actXY[0], host.actXY[1]],
382 r = this.getRegion(true);
384 if (this.get('stickX')) {
385 _xy[1] = (host.startXY[1] - host.deltaXY[1]);
387 if (this.get('stickY')) {
388 _xy[0] = (host.startXY[0] - host.deltaXY[0]);
392 _xy = this._checkRegion(_xy);
395 _xy = this._checkTicks(_xy, r);
401 * @description Fires after drag:drag. Handle the tickX and tickX align events.
403 drag: function(event) {
404 var host = this.get(HOST),
405 xt = this.get('tickX'),
406 yt = this.get('tickY'),
407 _xy = [host.actXY[0], host.actXY[1]];
409 if ((Y.Lang.isNumber(xt) || this.get(TICK_X_ARRAY)) && (this._lastTickXFired !== _xy[0])) {
411 this._lastTickXFired = _xy[0];
414 if ((Y.Lang.isNumber(yt) || this.get(TICK_Y_ARRAY)) && (this._lastTickYFired !== _xy[1])) {
416 this._lastTickYFired = _xy[1];
421 * @method _checkTicks
422 * @description This method delegates the proper helper method for tick calculations
423 * @param {Array} xy The XY coords for the Drag
424 * @param {Object} r The optional region that we are bound to.
425 * @return {Array} The calced XY coords
427 _checkTicks: function(xy, r) {
428 var host = this.get(HOST),
429 lx = (host.startXY[0] - host.deltaXY[0]),
430 ly = (host.startXY[1] - host.deltaXY[1]),
431 xt = this.get('tickX'),
432 yt = this.get('tickY');
433 if (xt && !this.get(TICK_X_ARRAY)) {
434 xy[0] = DDM._calcTicks(xy[0], lx, xt, r[LEFT], r[RIGHT]);
436 if (yt && !this.get(TICK_Y_ARRAY)) {
437 xy[1] = DDM._calcTicks(xy[1], ly, yt, r[TOP], r[BOTTOM]);
439 if (this.get(TICK_X_ARRAY)) {
440 xy[0] = DDM._calcTickArray(xy[0], this.get(TICK_X_ARRAY), r[LEFT], r[RIGHT]);
442 if (this.get(TICK_Y_ARRAY)) {
443 xy[1] = DDM._calcTickArray(xy[1], this.get(TICK_Y_ARRAY), r[TOP], r[BOTTOM]);
450 * @method _tickAlignX
451 * @description Fires when the actXY[0] reach a new value respecting the tickX gap.
453 _tickAlignX: function() {
454 this.fire(EV_TICK_ALIGN_X);
458 * @method _tickAlignY
459 * @description Fires when the actXY[1] reach a new value respecting the tickY gap.
461 _tickAlignY: function() {
462 this.fire(EV_TICK_ALIGN_Y);
466 Y.namespace('Plugin');
467 Y.extend(C, Y.Base, proto);
468 Y.Plugin.DDConstrained = C;
476 * @description Helper method to calculate the tick offsets for a given position
477 * @param {Number} pos The current X or Y position
478 * @param {Number} start The start X or Y position
479 * @param {Number} tick The X or Y tick increment
480 * @param {Number} off1 The min offset that we can't pass (region)
481 * @param {Number} off2 The max offset that we can't pass (region)
482 * @return {Number} The new position based on the tick calculation
484 _calcTicks: function(pos, start, tick, off1, off2) {
485 var ix = ((pos - start) / tick),
486 min = Math.floor(ix),
488 if ((min !== 0) || (max !== 0)) {
489 if ((ix >= min) && (ix <= max)) {
490 pos = (start + (tick * min));
493 pos = (start + (tick * (min + 1)));
496 pos = (start + (tick * (min - 1)));
507 * @method _calcTickArray
508 * @description This method is used with the tickXArray and tickYArray config options
509 * @param {Number} pos The current X or Y position
510 * @param {Number} ticks The array containing our custom tick positions.
511 * @param {Number} off1 The min offset that we can't pass (region)
512 * @param {Number} off2 The max offset that we can't pass (region)
513 * @return The tick position
515 _calcTickArray: function(pos, ticks, off1, off2) {
516 var i = 0, len = ticks.length, next = 0,
519 if (!ticks || (ticks.length === 0)) {
521 } else if (ticks[0] >= pos) {
524 for (i = 0; i < len; i++) {
526 if (ticks[next] && ticks[next] >= pos) {
527 diff1 = pos - ticks[i];
528 diff2 = ticks[next] - pos;
529 ret = (diff2 > diff1) ? ticks[i] : ticks[next];
535 ret = ticks[len - 1];
543 return ticks[ticks.length - 1];
550 }, '3.3.0' ,{requires:['dd-drag'], skinnable:false});