MDL-32843 import YUI 3.5.1
[moodle.git] / lib / yui / 3.5.1 / build / dd-constrain / dd-constrain-debug.js
blob318a3b21a286e2948124b47a31df216787da72be
1 /*
2 YUI 3.5.1 (build 22)
3 Copyright 2012 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
6 */
7 YUI.add('dd-constrain', function(Y) {
10         /**
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.
12          * @module dd
13      * @main dd
14          * @submodule dd-constrain
15          */
16         /**
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
19          * @extends Base
20          * @constructor
21          * @namespace Plugin
22          */
24         var DRAG_NODE = 'dragNode',
25             OFFSET_HEIGHT = 'offsetHeight',
26             OFFSET_WIDTH = 'offsetWidth',
27             HOST = 'host',
28             TICK_X_ARRAY = 'tickXArray',
29             TICK_Y_ARRAY = 'tickYArray',
30             DDM = Y.DD.DDM,
31             TOP = 'top',
32             RIGHT = 'right',
33             BOTTOM = 'bottom',
34             LEFT = 'left',
35             VIEW = 'view',
36             proto = null,
38                 /**
39             * @event drag:tickAlignX
40             * @description Fires when this node is aligned with the tickX value.
41             * @param {EventFacade} event An Event Facade object
42             * @type {CustomEvent}
43             */
44             EV_TICK_ALIGN_X = 'drag:tickAlignX',
46                 /**
47             * @event drag:tickAlignY
48             * @description Fires when this node is aligned with the tickY value.
49             * @param {EventFacade} event An Event Facade object
50             * @type {CustomEvent}
51             */
52             EV_TICK_ALIGN_Y = 'drag:tickAlignY',
54             C = function(config) {
55                 this._lazyAddAttrs = false;
56                 C.superclass.constructor.apply(this, arguments);
57             };
59         C.NAME = 'ddConstrained';
60         /**
61         * @property NS
62         * @default con
63         * @readonly
64         * @protected
65         * @static
66         * @description The Constrained instance will be placed on the Drag instance under the con namespace.
67         * @type {String}
69         C.NS = 'con';
71         C.ATTRS = {
72             host: {
73             },
74             /**
75             * @attribute stickX
76             * @description Stick the drag movement to the X-Axis. Default: false
77             * @type Boolean
78             */
79             stickX: {
80                 value: false
81             },
82             /**
83             * @attribute stickY
84             * @description Stick the drag movement to the Y-Axis
85             * @type Boolean
86             */
87             stickY: {
88                 value: false
89             },
90             /**
91             * @attribute tickX
92             * @description The X tick offset the drag node should snap to on each drag move. False for no ticks. Default: false
93             * @type Number/false
94             */
95             tickX: {
96                 value: false
97             },
98             /**
99             * @attribute tickY
100             * @description The Y tick offset the drag node should snap to on each drag move. False for no ticks. Default: false
101             * @type Number/false
102             */
103             tickY: {
104                 value: false
105             },
106             /**
107             * @attribute tickXArray
108             * @description An array of page coordinates to use as X ticks for drag movement.
109             * @type Array
110             */
111             tickXArray: {
112                 value: false
113             },
114             /**
115             * @attribute tickYArray
116             * @description An array of page coordinates to use as Y ticks for drag movement.
117             * @type Array
118             */
119             tickYArray: {
120                 value: false
121             },
122             /**
123             * @attribute gutter
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)
125             * @type String
126             */
127             gutter: {
128                 value: '0',
129                 setter: function(gutter) {
130                     return Y.DD.DDM.cssSizestoObject(gutter);
131                 }
132             },
133             /**
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}
140             */
141             constrain: {
142                 value: VIEW,
143                 setter: function(con) {
144                     var node = Y.one(con);
145                     if (node) {
146                         con = node;
147                     }
148                     return con;
149                 }
150             },
151             /**
152             * @deprecated
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.
155             * @type Object
156             */
157             constrain2region: {
158                 setter: function(r) {
159                     return this.set('constrain', r);
160                 }
161             },
162             /**
163             * @deprecated
164             * @attribute constrain2node
165             * @description Will attempt to constrain the drag node to the boundaries of this node.
166             * @type Object
167             */
168             constrain2node: {
169                 setter: function(n) {
170                     return this.set('constrain', Y.one(n));
171                 }
172             },
173             /**
174             * @deprecated
175             * @attribute constrain2view
176             * @description Will attempt to constrain the drag node to the boundaries of the viewport region.
177             * @type Object
178             */
179             constrain2view: {
180                 setter: function(n) {
181                     return this.set('constrain', VIEW);
182                 }
183             },
184             /**
185             * @attribute cacheRegion
186             * @description Should the region be cached for performace. Default: true
187             * @type Boolean
188             */
189             cacheRegion: {
190                 value: true
191             }
192         };
194         proto = {
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));
205             },
206         destructor: function() {
207             if (this._cacheHandle) {
208                 this._cacheHandle.detach();
209             }
210             this._cacheHandle = null;
211         },
212             /**
213             * @private
214             * @method _createEvents
215             * @description This method creates all the events for this Event Target and publishes them so we get Event Bubbling.
216             */
217                 _createEvents: function() {
218                         var instance = this;
220                         var ev = [
221                                 EV_TICK_ALIGN_X,
222                                 EV_TICK_ALIGN_Y
223                         ];
225                         Y.each(ev, function(v, k) {
226                     this.publish(v, {
227                         type: v,
228                         emitFacade: true,
229                         bubbles: true,
230                         queuable: false,
231                         prefix: 'drag'
232                     });
233                 }, this);
234                 },
235                 /**
236             * @private
237             * @method _handleEnd
238             * @description Fires on drag:end
239             */
240             _handleEnd: function() {
241                         this._lastTickYFired = null;
242                         this._lastTickXFired = null;
243             },
244             /**
245             * @private
246             * @method _handleStart
247             * @description Fires on drag:start and clears the _regionCache
248             */
249             _handleStart: function() {
250                 this.resetCache();
251             },
252             /**
253             * @private
254             * @property _regionCache
255             * @description Store a cache of the region that we are constraining to
256             * @type Object
257             */
258             _regionCache: null,
259         /**
260         * Event handle for window resize event.
261         * @private
262         * @property _cacheHandle
263         * @type {Event}
264         */
265         _cacheHandle: null,
266             /**
267             * @private
268             * @method _cacheRegion
269             * @description Get's the region and caches it, called from window.resize and when the cache is null
270             */
271             _cacheRegion: function() {
272                 this._regionCache = this.get('constrain').get('region');
273             },
274             /**
275             * @method resetCache
276             * @description Reset the internal region cache.
277             */
278             resetCache: function() {
279                 this._regionCache = null;
280             },
281             /**
282             * @private
283             * @method _getConstraint
284             * @description Standardizes the 'constraint' attribute
285             */
286             _getConstraint: function() {
287                 var con = this.get('constrain'),
288                     g = this.get('gutter'),
289                     region;
291                 if (con) {
292                     if (con instanceof Y.Node) {
293                         if (!this._regionCache) {
294                             this._cacheHandle = Y.on('resize', Y.bind(this._cacheRegion, this), Y.config.win);
295                             this._cacheRegion();
296                         }
297                         region = Y.clone(this._regionCache);
298                         if (!this.get('cacheRegion')) {
299                             this.resetCache();
300                         }
301                     } else if (Y.Lang.isObject(con)) {
302                         region = Y.clone(con);
303                     }
304                 }
305                 if (!con || !region) {
306                     con = VIEW;
307                 }
308                 if (con === VIEW) {
309                     region = this.get(HOST).get(DRAG_NODE).get('viewportRegion');
310                 }
312                 Y.each(g, function(i, n) {
313                     if ((n == RIGHT) || (n == BOTTOM)) {
314                         region[n] -= i;
315                     } else {
316                         region[n] += i;
317                     }
318                 });
319                 return region;
320             },
322             /**
323             * @method getRegion
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.
327             */
328             getRegion: function(inc) {
329                 var r = {}, oh = null, ow = null,
330                     host = this.get(HOST);
332                 r = this._getConstraint();
334                 if (inc) {
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;
339                 }
340                 return r;
341             },
342             /**
343             * @private
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
348             */
349             _checkRegion: function(_xy) {
350                 var oxy = _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);
358                     }
359                     if (r[TOP] > oxy[1]) {
360                         _xy[1] = r[TOP];
362                     }
363                     if (oxy[0] > (r[RIGHT] - ow)) {
364                         _xy[0] = (r[RIGHT] - ow);
365                     }
366                     if (r[LEFT] > oxy[0]) {
367                         _xy[0] = r[LEFT];
368                     }
370                 return _xy;
371             },
372             /**
373             * @method inRegion
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.
377             */
378             inRegion: function(xy) {
379                 xy = xy || this.get(HOST).get(DRAG_NODE).getXY();
381                 var _xy = this._checkRegion([xy[0], xy[1]]),
382                     inside = false;
383                     if ((xy[0] === _xy[0]) && (xy[1] === _xy[1])) {
384                         inside = true;
385                     }
386                 return inside;
387             },
388             /**
389             * @method align
390             * @description Modifies the Drag.actXY method from the after drag:align event. This is where the constraining happens.
391             */
392             align: function() {
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]);
399                 }
400                 if (this.get('stickY')) {
401                     _xy[0] = (host.startXY[0] - host.deltaXY[0]);
402                 }
404                 if (r) {
405                     _xy = this._checkRegion(_xy);
406                 }
408                 _xy = this._checkTicks(_xy, r);
410                 host.actXY = _xy;
411             },
412             /**
413             * @method drag
414             * @description Fires after drag:drag. Handle the tickX and tickX align events.
415             */
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])) {
423                                 this._tickAlignX();
424                                 this._lastTickXFired = _xy[0];
425                         }
427                         if ((Y.Lang.isNumber(yt) || this.get(TICK_Y_ARRAY)) && (this._lastTickYFired !== _xy[1])) {
428                                 this._tickAlignY();
429                                 this._lastTickYFired = _xy[1];
430                         }
431                 },
432             /**
433             * @private
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
439             */
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]);
448                     }
449                     if (yt && !this.get(TICK_Y_ARRAY)) {
450                         xy[1] = DDM._calcTicks(xy[1], ly, yt, r[TOP], r[BOTTOM]);
451                     }
452                     if (this.get(TICK_X_ARRAY)) {
453                         xy[0] = DDM._calcTickArray(xy[0], this.get(TICK_X_ARRAY), r[LEFT], r[RIGHT]);
454                     }
455                     if (this.get(TICK_Y_ARRAY)) {
456                         xy[1] = DDM._calcTickArray(xy[1], this.get(TICK_Y_ARRAY), r[TOP], r[BOTTOM]);
457                     }
459                 return xy;
460             },
461             /**
462             * @private
463             * @method _tickAlignX
464             * @description Fires when the actXY[0] reach a new value respecting the tickX gap.
465             */
466             _tickAlignX: function() {
467                 this.fire(EV_TICK_ALIGN_X);
468             },
469             /**
470             * @private
471             * @method _tickAlignY
472             * @description Fires when the actXY[1] reach a new value respecting the tickY gap.
473             */
474             _tickAlignY: function() {
475                 this.fire(EV_TICK_ALIGN_Y);
476             }
477         };
479         Y.namespace('Plugin');
480         Y.extend(C, Y.Base, proto);
481         Y.Plugin.DDConstrained = C;
483         Y.mix(DDM, {
484             /**
485             * @for DDM
486             * @namespace DD
487             * @private
488             * @method _calcTicks
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
496             */
497             _calcTicks: function(pos, start, tick, off1, off2) {
498                 var ix = ((pos - start) / tick),
499                     min = Math.floor(ix),
500                     max = Math.ceil(ix);
501                     if ((min !== 0) || (max !== 0)) {
502                         if ((ix >= min) && (ix <= max)) {
503                             pos = (start + (tick * min));
504                             if (off1 && off2) {
505                                 if (pos < off1) {
506                                     pos = (start + (tick * (min + 1)));
507                                 }
508                                 if (pos > off2) {
509                                     pos = (start + (tick * (min - 1)));
510                                 }
511                             }
512                         }
513                     }
514                     return pos;
515             },
516             /**
517             * @for DDM
518             * @namespace DD
519             * @private
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
527             */
528             _calcTickArray: function(pos, ticks, off1, off2) {
529                 var i = 0, len = ticks.length, next = 0,
530                     diff1, diff2, ret;
532                 if (!ticks || (ticks.length === 0)) {
533                     return pos;
534                 } else if (ticks[0] >= pos) {
535                     return ticks[0];
536                 } else {
537                     for (i = 0; i < len; i++) {
538                         next = (i + 1);
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];
543                             if (off1 && off2) {
544                                 if (ret > off2) {
545                                     if (ticks[i]) {
546                                         ret = ticks[i];
547                                     } else {
548                                         ret = ticks[len - 1];
549                                     }
550                                 }
551                             }
552                             return ret;
553                         }
555                     }
556                     return ticks[ticks.length - 1];
557                 }
558             }
559         });
563 }, '3.5.1' ,{skinnable:false, requires:['dd-drag']});