3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
7 YUI.add('dd-constrain', function(Y) {
11 * 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 {EventFacade} event An Event Facade object
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 {EventFacade} event An Event Facade object
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));
206 destructor: function() {
207 if (this._cacheHandle) {
208 this._cacheHandle.detach();
210 this._cacheHandle = null;
214 * @method _createEvents
215 * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling.
217 _createEvents: function() {
225 Y.each(ev, function(v, k) {
238 * @description Fires on drag:end
240 _handleEnd: function() {
241 this._lastTickYFired = null;
242 this._lastTickXFired = null;
246 * @method _handleStart
247 * @description Fires on drag:start and clears the _regionCache
249 _handleStart: function() {
254 * @property _regionCache
255 * @description Store a cache of the region that we are constraining to
260 * Event handle for window resize event.
262 * @property _cacheHandle
268 * @method _cacheRegion
269 * @description Get's the region and caches it, called from window.resize and when the cache is null
271 _cacheRegion: function() {
272 this._regionCache = this.get('constrain').get('region');
276 * @description Reset the internal region cache.
278 resetCache: function() {
279 this._regionCache = null;
283 * @method _getConstraint
284 * @description Standardizes the 'constraint' attribute
286 _getConstraint: function() {
287 var con = this.get('constrain'),
288 g = this.get('gutter'),
292 if (con instanceof Y.Node) {
293 if (!this._regionCache) {
294 this._cacheHandle = Y.on('resize', Y.bind(this._cacheRegion, this), Y.config.win);
297 region = Y.clone(this._regionCache);
298 if (!this.get('cacheRegion')) {
301 } else if (Y.Lang.isObject(con)) {
302 region = Y.clone(con);
305 if (!con || !region) {
309 region = this.get(HOST).get(DRAG_NODE).get('viewportRegion');
312 Y.each(g, function(i, n) {
313 if ((n == RIGHT) || (n == BOTTOM)) {
324 * @description Get the active region: viewport, node, custom region
325 * @param {Boolean} inc Include the node's height and width
326 * @return {Object} The active region.
328 getRegion: function(inc) {
329 var r = {}, oh = null, ow = null,
330 host = this.get(HOST);
332 r = this._getConstraint();
335 oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT);
336 ow = host.get(DRAG_NODE).get(OFFSET_WIDTH);
337 r[RIGHT] = r[RIGHT] - ow;
338 r[BOTTOM] = r[BOTTOM] - oh;
344 * @method _checkRegion
345 * @description Check if xy is inside a given region, if not change to it be inside.
346 * @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.
347 * @return {Array} The new XY that is inside the region
349 _checkRegion: function(_xy) {
351 r = this.getRegion(),
352 host = this.get(HOST),
353 oh = host.get(DRAG_NODE).get(OFFSET_HEIGHT),
354 ow = host.get(DRAG_NODE).get(OFFSET_WIDTH);
356 if (oxy[1] > (r[BOTTOM] - oh)) {
357 _xy[1] = (r[BOTTOM] - oh);
359 if (r[TOP] > oxy[1]) {
363 if (oxy[0] > (r[RIGHT] - ow)) {
364 _xy[0] = (r[RIGHT] - ow);
366 if (r[LEFT] > oxy[0]) {
374 * @description Checks if the XY passed or the dragNode is inside the active region.
375 * @param {Array} xy Optional XY to check, if not supplied this.get('dragNode').getXY() is used.
376 * @return {Boolean} True if the XY is inside the region, false otherwise.
378 inRegion: function(xy) {
379 xy = xy || this.get(HOST).get(DRAG_NODE).getXY();
381 var _xy = this._checkRegion([xy[0], xy[1]]),
383 if ((xy[0] === _xy[0]) && (xy[1] === _xy[1])) {
390 * @description Modifies the Drag.actXY method from the after drag:align event. This is where the constraining happens.
393 var host = this.get(HOST),
394 _xy = [host.actXY[0], host.actXY[1]],
395 r = this.getRegion(true);
397 if (this.get('stickX')) {
398 _xy[1] = (host.startXY[1] - host.deltaXY[1]);
400 if (this.get('stickY')) {
401 _xy[0] = (host.startXY[0] - host.deltaXY[0]);
405 _xy = this._checkRegion(_xy);
408 _xy = this._checkTicks(_xy, r);
414 * @description Fires after drag:drag. Handle the tickX and tickX align events.
416 drag: function(event) {
417 var host = this.get(HOST),
418 xt = this.get('tickX'),
419 yt = this.get('tickY'),
420 _xy = [host.actXY[0], host.actXY[1]];
422 if ((Y.Lang.isNumber(xt) || this.get(TICK_X_ARRAY)) && (this._lastTickXFired !== _xy[0])) {
424 this._lastTickXFired = _xy[0];
427 if ((Y.Lang.isNumber(yt) || this.get(TICK_Y_ARRAY)) && (this._lastTickYFired !== _xy[1])) {
429 this._lastTickYFired = _xy[1];
434 * @method _checkTicks
435 * @description This method delegates the proper helper method for tick calculations
436 * @param {Array} xy The XY coords for the Drag
437 * @param {Object} r The optional region that we are bound to.
438 * @return {Array} The calced XY coords
440 _checkTicks: function(xy, r) {
441 var host = this.get(HOST),
442 lx = (host.startXY[0] - host.deltaXY[0]),
443 ly = (host.startXY[1] - host.deltaXY[1]),
444 xt = this.get('tickX'),
445 yt = this.get('tickY');
446 if (xt && !this.get(TICK_X_ARRAY)) {
447 xy[0] = DDM._calcTicks(xy[0], lx, xt, r[LEFT], r[RIGHT]);
449 if (yt && !this.get(TICK_Y_ARRAY)) {
450 xy[1] = DDM._calcTicks(xy[1], ly, yt, r[TOP], r[BOTTOM]);
452 if (this.get(TICK_X_ARRAY)) {
453 xy[0] = DDM._calcTickArray(xy[0], this.get(TICK_X_ARRAY), r[LEFT], r[RIGHT]);
455 if (this.get(TICK_Y_ARRAY)) {
456 xy[1] = DDM._calcTickArray(xy[1], this.get(TICK_Y_ARRAY), r[TOP], r[BOTTOM]);
463 * @method _tickAlignX
464 * @description Fires when the actXY[0] reach a new value respecting the tickX gap.
466 _tickAlignX: function() {
467 this.fire(EV_TICK_ALIGN_X);
471 * @method _tickAlignY
472 * @description Fires when the actXY[1] reach a new value respecting the tickY gap.
474 _tickAlignY: function() {
475 this.fire(EV_TICK_ALIGN_Y);
479 Y.namespace('Plugin');
480 Y.extend(C, Y.Base, proto);
481 Y.Plugin.DDConstrained = C;
489 * @description Helper method to calculate the tick offsets for a given position
490 * @param {Number} pos The current X or Y position
491 * @param {Number} start The start X or Y position
492 * @param {Number} tick The X or Y tick increment
493 * @param {Number} off1 The min offset that we can't pass (region)
494 * @param {Number} off2 The max offset that we can't pass (region)
495 * @return {Number} The new position based on the tick calculation
497 _calcTicks: function(pos, start, tick, off1, off2) {
498 var ix = ((pos - start) / tick),
499 min = Math.floor(ix),
501 if ((min !== 0) || (max !== 0)) {
502 if ((ix >= min) && (ix <= max)) {
503 pos = (start + (tick * min));
506 pos = (start + (tick * (min + 1)));
509 pos = (start + (tick * (min - 1)));
520 * @method _calcTickArray
521 * @description This method is used with the tickXArray and tickYArray config options
522 * @param {Number} pos The current X or Y position
523 * @param {Number} ticks The array containing our custom tick positions.
524 * @param {Number} off1 The min offset that we can't pass (region)
525 * @param {Number} off2 The max offset that we can't pass (region)
526 * @return The tick position
528 _calcTickArray: function(pos, ticks, off1, off2) {
529 var i = 0, len = ticks.length, next = 0,
532 if (!ticks || (ticks.length === 0)) {
534 } else if (ticks[0] >= pos) {
537 for (i = 0; i < len; i++) {
539 if (ticks[next] && ticks[next] >= pos) {
540 diff1 = pos - ticks[i];
541 diff2 = ticks[next] - pos;
542 ret = (diff2 > diff1) ? ticks[i] : ticks[next];
548 ret = ticks[len - 1];
556 return ticks[ticks.length - 1];
563 }, '3.5.1' ,{skinnable:false, requires:['dd-drag']});