2 Copyright (c) 2009, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
8 * The drag and drop utility provides a framework for building drag and drop
9 * applications. In addition to enabling drag and drop for specific elements,
10 * the drag and drop elements are tracked by the manager class, and the
11 * interactions between the various elements are tracked during the drag and
12 * the implementing code is notified about these important moments.
14 * @title Drag and Drop
15 * @requires yahoo,dom,event
16 * @namespace YAHOO.util
19 // Only load the library once. Rewriting the manager class would orphan
20 // existing drag and drop instances.
21 if (!YAHOO.util.DragDropMgr) {
24 * DragDropMgr is a singleton that tracks the element interaction for
25 * all DragDrop items in the window. Generally, you will not call
26 * this class directly, but it does have helper methods that could
27 * be useful in your DragDrop implementations.
31 YAHOO.util.DragDropMgr = function() {
33 var Event = YAHOO.util.Event,
38 * This property is used to turn on global use of the shim element on all DragDrop instances, defaults to false for backcompat. (Use: YAHOO.util.DDM.useShim = true)
45 * This property is used to determine if the shim is active over the screen, default false.
47 * @property _shimActive
53 * This property is used when useShim is set on a DragDrop object to store the current state of DDM.useShim so it can be reset when a drag operation is done.
55 * @property _shimState
61 * This property is used when useShim is set to true, it will set the opacity on the shim to .5 for debugging. Use: (YAHOO.util.DDM._debugShim = true;)
63 * @property _debugShim
69 * This method will create a shim element (giving it the id of yui-ddm-shim), it also attaches the mousemove and mouseup listeners to it and attaches a scroll listener on the window
74 _createShim: function() {
75 YAHOO.log('Creating Shim Element', 'info', 'DragDropMgr');
76 var s = document.createElement('div');
77 s.id = 'yui-ddm-shim';
78 if (document.body.firstChild) {
79 document.body.insertBefore(s, document.body.firstChild);
81 document.body.appendChild(s);
83 s.style.display = 'none';
84 s.style.backgroundColor = 'red';
85 s.style.position = 'absolute';
86 s.style.zIndex = '99999';
87 Dom.setStyle(s, 'opacity', '0');
89 Event.on(s, "mouseup", this.handleMouseUp, this, true);
90 Event.on(s, "mousemove", this.handleMouseMove, this, true);
91 Event.on(window, 'scroll', this._sizeShim, this, true);
94 * This method will size the shim, called from activate and on window scroll event
99 _sizeShim: function() {
100 if (this._shimActive) {
101 YAHOO.log('Sizing Shim', 'info', 'DragDropMgr');
103 s.style.height = Dom.getDocumentHeight() + 'px';
104 s.style.width = Dom.getDocumentWidth() + 'px';
110 * This method will create the shim element if needed, then show the shim element, size the element and set the _shimActive property to true
112 * @method _activateShim
115 _activateShim: function() {
117 YAHOO.log('Activating Shim', 'info', 'DragDropMgr');
121 this._shimActive = true;
124 if (this._debugShim) {
127 Dom.setStyle(s, 'opacity', o);
129 s.style.display = 'block';
133 * This method will hide the shim element and set the _shimActive property to false
135 * @method _deactivateShim
138 _deactivateShim: function() {
139 YAHOO.log('Deactivating Shim', 'info', 'DragDropMgr');
140 this._shim.style.display = 'none';
141 this._shimActive = false;
144 * The HTML element created to use as a shim over the document to track mouse movements
152 * Two dimensional Array of registered DragDrop objects. The first
153 * dimension is the DragDrop item group, the second the DragDrop
156 * @type {string: string}
163 * Array of element ids defined as drag handles. Used to determine
164 * if the element that generated the mousedown event is actually the
165 * handle and not the html element itself.
166 * @property handleIds
167 * @type {string: string}
174 * the DragDrop object that is currently being dragged
175 * @property dragCurrent
183 * the DragDrop object(s) that are being hovered over
184 * @property dragOvers
192 * the X distance between the cursor and the object being dragged
201 * the Y distance between the cursor and the object being dragged
210 * Flag to determine if we should prevent the default behavior of the
211 * events we define. By default this is true, but this can be set to
212 * false if you need the default behavior (not recommended)
213 * @property preventDefault
217 preventDefault: true,
220 * Flag to determine if we should stop the propagation of the events
221 * we generate. This is true by default but you may want to set it to
222 * false if the html element contains other features that require the
224 * @property stopPropagation
228 stopPropagation: true,
231 * Internal flag that is set to true when drag and drop has been
233 * @property initialized
240 * All drag and drop can be disabled.
248 * Provides additional information about the the current set of
249 * interactions. Can be accessed from the event handlers. It
250 * contains the following properties:
252 * out: onDragOut interactions
253 * enter: onDragEnter interactions
254 * over: onDragOver interactions
255 * drop: onDragDrop interactions
256 * point: The location of the cursor
257 * draggedRegion: The location of dragged element at the time
259 * sourceRegion: The location of the source elemtn at the time
262 * @property interactionInfo
266 interactionInfo: null,
269 * Called the first time an element is registered.
275 this.initialized = true;
279 * In point mode, drag and drop interaction is defined by the
280 * location of the cursor during the drag/drop
289 * In intersect mode, drag and drop interaction is defined by the
290 * cursor position or the amount of overlap of two or more drag and
292 * @property INTERSECT
300 * In intersect mode, drag and drop interaction is defined only by the
301 * overlap of two or more drag and drop objects.
302 * @property STRICT_INTERSECT
310 * The current drag and drop mode. Default: POINT
318 * Runs method on all drag and drop objects
323 _execOnAll: function(sMethod, args) {
324 for (var i in this.ids) {
325 for (var j in this.ids[i]) {
326 var oDD = this.ids[i][j];
327 if (! this.isTypeOfDD(oDD)) {
330 oDD[sMethod].apply(oDD, args);
336 * Drag and drop initialization. Sets up the global event handlers
341 _onLoad: function() {
345 YAHOO.log("DragDropMgr onload", "info", "DragDropMgr");
346 Event.on(document, "mouseup", this.handleMouseUp, this, true);
347 Event.on(document, "mousemove", this.handleMouseMove, this, true);
348 Event.on(window, "unload", this._onUnload, this, true);
349 Event.on(window, "resize", this._onResize, this, true);
350 // Event.on(window, "mouseout", this._test);
355 * Reset constraints on all drag and drop objs
360 _onResize: function(e) {
361 YAHOO.log("window resize", "info", "DragDropMgr");
362 this._execOnAll("resetConstraints", []);
366 * Lock all drag and drop functionality
370 lock: function() { this.locked = true; },
373 * Unlock all drag and drop functionality
377 unlock: function() { this.locked = false; },
380 * Is drag and drop locked?
382 * @return {boolean} True if drag and drop is locked, false otherwise.
385 isLocked: function() { return this.locked; },
388 * Location cache that is set for all drag drop objects when a drag is
389 * initiated, cleared when the drag is finished.
390 * @property locationCache
397 * Set useCache to false if you want to force object the lookup of each
398 * drag and drop linked element constantly during a drag.
406 * The number of pixels that the mouse needs to move after the
407 * mousedown before the drag is initiated. Default=3;
408 * @property clickPixelThresh
415 * The number of milliseconds after the mousedown event to initiate the
416 * drag if we don't get a mouseup event. Default=1000
417 * @property clickTimeThresh
421 clickTimeThresh: 1000,
424 * Flag that indicates that either the drag pixel threshold or the
425 * mousdown time threshold has been met
426 * @property dragThreshMet
431 dragThreshMet: false,
434 * Timeout used for the click time threshold
435 * @property clickTimeout
443 * The X position of the mousedown event stored for later use when a
444 * drag threshold is met.
453 * The Y position of the mousedown event stored for later use when a
454 * drag threshold is met.
463 * Flag to determine if the drag event was fired from the click timeout and
464 * not the mouse move threshold.
465 * @property fromTimeout
473 * Each DragDrop instance must be registered with the DragDropMgr.
474 * This is executed in DragDrop.init()
475 * @method regDragDrop
476 * @param {DragDrop} oDD the DragDrop object to register
477 * @param {String} sGroup the name of the group this element belongs to
480 regDragDrop: function(oDD, sGroup) {
481 if (!this.initialized) { this.init(); }
483 if (!this.ids[sGroup]) {
484 this.ids[sGroup] = {};
486 this.ids[sGroup][oDD.id] = oDD;
490 * Removes the supplied dd instance from the supplied group. Executed
491 * by DragDrop.removeFromGroup, so don't call this function directly.
492 * @method removeDDFromGroup
496 removeDDFromGroup: function(oDD, sGroup) {
497 if (!this.ids[sGroup]) {
498 this.ids[sGroup] = {};
501 var obj = this.ids[sGroup];
502 if (obj && obj[oDD.id]) {
508 * Unregisters a drag and drop item. This is executed in
509 * DragDrop.unreg, use that method instead of calling this directly.
514 _remove: function(oDD) {
515 for (var g in oDD.groups) {
517 var item = this.ids[g];
518 if (item && item[oDD.id]) {
524 delete this.handleIds[oDD.id];
528 * Each DragDrop handle element must be registered. This is done
529 * automatically when executing DragDrop.setHandleElId()
531 * @param {String} sDDId the DragDrop id this element is a handle for
532 * @param {String} sHandleId the id of the element that is the drag
536 regHandle: function(sDDId, sHandleId) {
537 if (!this.handleIds[sDDId]) {
538 this.handleIds[sDDId] = {};
540 this.handleIds[sDDId][sHandleId] = sHandleId;
544 * Utility function to determine if a given element has been
545 * registered as a drag drop item.
547 * @param {String} id the element id to check
548 * @return {boolean} true if this element is a DragDrop item,
552 isDragDrop: function(id) {
553 return ( this.getDDById(id) ) ? true : false;
557 * Returns the drag and drop instances that are in all groups the
558 * passed in instance belongs to.
560 * @param {DragDrop} p_oDD the obj to get related data for
561 * @param {boolean} bTargetsOnly if true, only return targetable objs
562 * @return {DragDrop[]} the related instances
565 getRelated: function(p_oDD, bTargetsOnly) {
567 for (var i in p_oDD.groups) {
568 for (var j in this.ids[i]) {
569 var dd = this.ids[i][j];
570 if (! this.isTypeOfDD(dd)) {
573 if (!bTargetsOnly || dd.isTarget) {
574 oDDs[oDDs.length] = dd;
583 * Returns true if the specified dd target is a legal target for
584 * the specifice drag obj
585 * @method isLegalTarget
586 * @param {DragDrop} the drag obj
587 * @param {DragDrop} the target
588 * @return {boolean} true if the target is a legal target for the
592 isLegalTarget: function (oDD, oTargetDD) {
593 var targets = this.getRelated(oDD, true);
594 for (var i=0, len=targets.length;i<len;++i) {
595 if (targets[i].id == oTargetDD.id) {
604 * My goal is to be able to transparently determine if an object is
605 * typeof DragDrop, and the exact subclass of DragDrop. typeof
606 * returns "object", oDD.constructor.toString() always returns
607 * "DragDrop" and not the name of the subclass. So for now it just
608 * evaluates a well-known variable in DragDrop.
610 * @param {Object} the object to evaluate
611 * @return {boolean} true if typeof oDD = DragDrop
614 isTypeOfDD: function (oDD) {
615 return (oDD && oDD.__ygDragDrop);
619 * Utility function to determine if a given element has been
620 * registered as a drag drop handle for the given Drag Drop object.
622 * @param {String} id the element id to check
623 * @return {boolean} true if this element is a DragDrop handle, false
627 isHandle: function(sDDId, sHandleId) {
628 return ( this.handleIds[sDDId] &&
629 this.handleIds[sDDId][sHandleId] );
633 * Returns the DragDrop instance for a given id
635 * @param {String} id the id of the DragDrop object
636 * @return {DragDrop} the drag drop object, null if it is not found
639 getDDById: function(id) {
640 for (var i in this.ids) {
641 if (this.ids[i][id]) {
642 return this.ids[i][id];
649 * Fired after a registered DragDrop object gets the mousedown event.
650 * Sets up the events required to track the object being dragged
651 * @method handleMouseDown
652 * @param {Event} e the event
653 * @param oDD the DragDrop object being dragged
657 handleMouseDown: function(e, oDD) {
658 //this._activateShim();
660 this.currentTarget = YAHOO.util.Event.getTarget(e);
662 this.dragCurrent = oDD;
664 var el = oDD.getEl();
666 // track start position
667 this.startX = YAHOO.util.Event.getPageX(e);
668 this.startY = YAHOO.util.Event.getPageY(e);
670 this.deltaX = this.startX - el.offsetLeft;
671 this.deltaY = this.startY - el.offsetTop;
673 this.dragThreshMet = false;
675 this.clickTimeout = setTimeout(
677 var DDM = YAHOO.util.DDM;
678 DDM.startDrag(DDM.startX, DDM.startY);
679 DDM.fromTimeout = true;
681 this.clickTimeThresh );
685 * Fired when either the drag pixel threshold or the mousedown hold
686 * time threshold has been met.
688 * @param x {int} the X position of the original mousedown
689 * @param y {int} the Y position of the original mousedown
692 startDrag: function(x, y) {
693 if (this.dragCurrent && this.dragCurrent.useShim) {
694 this._shimState = this.useShim;
697 this._activateShim();
698 YAHOO.log("firing drag start events", "info", "DragDropMgr");
699 clearTimeout(this.clickTimeout);
700 var dc = this.dragCurrent;
701 if (dc && dc.events.b4StartDrag) {
702 dc.b4StartDrag(x, y);
703 dc.fireEvent('b4StartDragEvent', { x: x, y: y });
705 if (dc && dc.events.startDrag) {
707 dc.fireEvent('startDragEvent', { x: x, y: y });
709 this.dragThreshMet = true;
713 * Internal function to handle the mouseup event. Will be invoked
714 * from the context of the document.
715 * @method handleMouseUp
716 * @param {Event} e the event
720 handleMouseUp: function(e) {
721 if (this.dragCurrent) {
722 clearTimeout(this.clickTimeout);
724 if (this.dragThreshMet) {
725 YAHOO.log("mouseup detected - completing drag", "info", "DragDropMgr");
726 if (this.fromTimeout) {
727 YAHOO.log('fromTimeout is true (mouse didn\'t move), call handleMouseMove so we can get the dragOver event', 'info', 'DragDropMgr');
728 this.fromTimeout = false;
729 this.handleMouseMove(e);
731 this.fromTimeout = false;
732 this.fireEvents(e, true);
734 YAHOO.log("drag threshold not met", "info", "DragDropMgr");
744 * Utility to stop event propagation and event default, if these
745 * features are turned on.
747 * @param {Event} e the event as returned by this.getEvent()
750 stopEvent: function(e) {
751 if (this.stopPropagation) {
752 YAHOO.util.Event.stopPropagation(e);
755 if (this.preventDefault) {
756 YAHOO.util.Event.preventDefault(e);
761 * Ends the current drag, cleans up the state, and fires the endDrag
762 * and mouseUp events. Called internally when a mouseup is detected
763 * during the drag. Can be fired manually during the drag by passing
764 * either another event (such as the mousemove event received in onDrag)
765 * or a fake event with pageX and pageY defined (so that endDrag and
766 * onMouseUp have usable position data.). Alternatively, pass true
767 * for the silent parameter so that the endDrag and onMouseUp events
768 * are skipped (so no event data is needed.)
771 * @param {Event} e the mouseup event, another event (or a fake event)
772 * with pageX and pageY defined, or nothing if the
773 * silent parameter is true
774 * @param {boolean} silent skips the enddrag and mouseup events if true
777 stopDrag: function(e, silent) {
778 // YAHOO.log("mouseup - removing event handlers");
779 var dc = this.dragCurrent;
780 // Fire the drag end event for the item that was dragged
782 if (this.dragThreshMet) {
783 YAHOO.log("firing endDrag events", "info", "DragDropMgr");
784 if (dc.events.b4EndDrag) {
786 dc.fireEvent('b4EndDragEvent', { e: e });
788 if (dc.events.endDrag) {
790 dc.fireEvent('endDragEvent', { e: e });
793 if (dc.events.mouseUp) {
794 YAHOO.log("firing dragdrop onMouseUp event", "info", "DragDropMgr");
796 dc.fireEvent('mouseUpEvent', { e: e });
800 if (this._shimActive) {
801 this._deactivateShim();
802 if (this.dragCurrent && this.dragCurrent.useShim) {
803 this.useShim = this._shimState;
804 this._shimState = false;
808 this.dragCurrent = null;
813 * Internal function to handle the mousemove event. Will be invoked
814 * from the context of the html element.
816 * @TODO figure out what we can do about mouse events lost when the
817 * user drags objects beyond the window boundary. Currently we can
818 * detect this in internet explorer by verifying that the mouse is
819 * down during the mousemove event. Firefox doesn't give us the
820 * button state on the mousemove event.
821 * @method handleMouseMove
822 * @param {Event} e the event
826 handleMouseMove: function(e) {
827 //YAHOO.log("handlemousemove");
829 var dc = this.dragCurrent;
831 // YAHOO.log("no current drag obj");
833 // var button = e.which || e.button;
834 // YAHOO.log("which: " + e.which + ", button: "+ e.button);
836 // check for IE mouseup outside of page boundary
837 if (YAHOO.util.Event.isIE && !e.button) {
838 YAHOO.log("button failure", "info", "DragDropMgr");
840 return this.handleMouseUp(e);
842 if (e.clientX < 0 || e.clientY < 0) {
843 //This will stop the element from leaving the viewport in FF, Opera & Safari
845 //YAHOO.log("Either clientX or clientY is negative, stop the event.", "info", "DragDropMgr");
851 if (!this.dragThreshMet) {
852 var diffX = Math.abs(this.startX - YAHOO.util.Event.getPageX(e));
853 var diffY = Math.abs(this.startY - YAHOO.util.Event.getPageY(e));
854 // YAHOO.log("diffX: " + diffX + "diffY: " + diffY);
855 if (diffX > this.clickPixelThresh ||
856 diffY > this.clickPixelThresh) {
857 YAHOO.log("pixel threshold met", "info", "DragDropMgr");
858 this.startDrag(this.startX, this.startY);
862 if (this.dragThreshMet) {
863 if (dc && dc.events.b4Drag) {
865 dc.fireEvent('b4DragEvent', { e: e});
867 if (dc && dc.events.drag) {
869 dc.fireEvent('dragEvent', { e: e});
872 this.fireEvents(e, false);
881 * Iterates over all of the DragDrop elements to find ones we are
882 * hovering over or dropping on
884 * @param {Event} e the event
885 * @param {boolean} isDrop is this a drop op or a mouseover op?
889 fireEvents: function(e, isDrop) {
890 var dc = this.dragCurrent;
892 // If the user did the mouse up outside of the window, we could
893 // get here even though we have ended the drag.
894 // If the config option dragOnly is true, bail out and don't fire the events
895 if (!dc || dc.isLocked() || dc.dragOnly) {
899 var x = YAHOO.util.Event.getPageX(e),
900 y = YAHOO.util.Event.getPageY(e),
901 pt = new YAHOO.util.Point(x,y),
902 pos = dc.getTargetCoord(pt.x, pt.y),
904 events = ['out', 'over', 'drop', 'enter'],
905 curRegion = new YAHOO.util.Region( pos.y,
906 pos.x + el.offsetWidth,
907 pos.y + el.offsetHeight,
910 oldOvers = [], // cache the previous dragOver array
921 // Check to see if the object(s) we were hovering over is no longer
922 // being hovered over so we can fire the onDragOut event
923 for (var i in this.dragOvers) {
925 var ddo = this.dragOvers[i];
927 if (! this.isTypeOfDD(ddo)) {
930 if (! this.isOverTarget(pt, ddo, this.mode, curRegion)) {
931 data.outEvts.push( ddo );
935 delete this.dragOvers[i];
938 for (var sGroup in dc.groups) {
939 // YAHOO.log("Processing group " + sGroup);
941 if ("string" != typeof sGroup) {
945 for (i in this.ids[sGroup]) {
946 var oDD = this.ids[sGroup][i];
947 if (! this.isTypeOfDD(oDD)) {
951 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
952 if (this.isOverTarget(pt, oDD, this.mode, curRegion)) {
953 inGroupsObj[sGroup] = true;
954 // look for drop interactions
956 data.dropEvts.push( oDD );
957 // look for drag enter and drag over interactions
960 // initial drag over: dragEnter fires
961 if (!oldOvers[oDD.id]) {
962 data.enterEvts.push( oDD );
963 // subsequent drag overs: dragOver fires
965 data.overEvts.push( oDD );
968 this.dragOvers[oDD.id] = oDD;
975 this.interactionInfo = {
977 enter: data.enterEvts,
981 draggedRegion: curRegion,
982 sourceRegion: this.locationCache[dc.id],
987 for (var inG in inGroupsObj) {
991 // notify about a drop that did not find a target
992 if (isDrop && !data.dropEvts.length) {
993 YAHOO.log(dc.id + " dropped, but not on a target", "info", "DragDropMgr");
994 this.interactionInfo.validDrop = false;
995 if (dc.events.invalidDrop) {
997 dc.fireEvent('invalidDropEvent', { e: e });
1000 for (i = 0; i < events.length; i++) {
1002 if (data[events[i] + 'Evts']) {
1003 tmp = data[events[i] + 'Evts'];
1005 if (tmp && tmp.length) {
1006 var type = events[i].charAt(0).toUpperCase() + events[i].substr(1),
1007 ev = 'onDrag' + type,
1008 b4 = 'b4Drag' + type,
1009 cev = 'drag' + type + 'Event',
1010 check = 'drag' + type;
1012 YAHOO.log(dc.id + ' ' + ev + ': ' + tmp, "info", "DragDropMgr");
1013 if (dc.events[b4]) {
1014 dc[b4](e, tmp, inGroups);
1015 dc.fireEvent(b4 + 'Event', { event: e, info: tmp, group: inGroups });
1018 if (dc.events[check]) {
1019 dc[ev](e, tmp, inGroups);
1020 dc.fireEvent(cev, { event: e, info: tmp, group: inGroups });
1023 for (var b = 0, len = tmp.length; b < len; ++b) {
1024 YAHOO.log(dc.id + ' ' + ev + ': ' + tmp[b].id, "info", "DragDropMgr");
1025 if (dc.events[b4]) {
1026 dc[b4](e, tmp[b].id, inGroups[0]);
1027 dc.fireEvent(b4 + 'Event', { event: e, info: tmp[b].id, group: inGroups[0] });
1029 if (dc.events[check]) {
1030 dc[ev](e, tmp[b].id, inGroups[0]);
1031 dc.fireEvent(cev, { event: e, info: tmp[b].id, group: inGroups[0] });
1040 * Helper function for getting the best match from the list of drag
1041 * and drop objects returned by the drag and drop events when we are
1042 * in INTERSECT mode. It returns either the first object that the
1043 * cursor is over, or the object that has the greatest overlap with
1044 * the dragged element.
1045 * @method getBestMatch
1046 * @param {DragDrop[]} dds The array of drag and drop objects
1048 * @return {DragDrop} The best single match
1051 getBestMatch: function(dds) {
1054 var len = dds.length;
1059 // Loop through the targeted items
1060 for (var i=0; i<len; ++i) {
1062 // If the cursor is over the object, it wins. If the
1063 // cursor is over multiple matches, the first one we come
1065 if (this.mode == this.INTERSECT && dd.cursorIsOver) {
1068 // Otherwise the object with the most overlap wins
1070 if (!winner || !winner.overlap || (dd.overlap &&
1071 winner.overlap.getArea() < dd.overlap.getArea())) {
1082 * Refreshes the cache of the top-left and bottom-right points of the
1083 * drag and drop objects in the specified group(s). This is in the
1084 * format that is stored in the drag and drop instance, so typical
1087 * YAHOO.util.DragDropMgr.refreshCache(ddinstance.groups);
1091 * YAHOO.util.DragDropMgr.refreshCache({group1:true, group2:true});
1093 * @TODO this really should be an indexed array. Alternatively this
1094 * method could accept both.
1095 * @method refreshCache
1096 * @param {Object} groups an associative array of groups to refresh
1099 refreshCache: function(groups) {
1100 YAHOO.log("refreshing element location cache", "info", "DragDropMgr");
1102 // refresh everything if group array is not provided
1103 var g = groups || this.ids;
1105 for (var sGroup in g) {
1106 if ("string" != typeof sGroup) {
1109 for (var i in this.ids[sGroup]) {
1110 var oDD = this.ids[sGroup][i];
1112 if (this.isTypeOfDD(oDD)) {
1113 var loc = this.getLocation(oDD);
1115 this.locationCache[oDD.id] = loc;
1117 delete this.locationCache[oDD.id];
1118 YAHOO.log("Could not get the loc for " + oDD.id, "warn", "DragDropMgr");
1126 * This checks to make sure an element exists and is in the DOM. The
1127 * main purpose is to handle cases where innerHTML is used to remove
1128 * drag and drop objects from the DOM. IE provides an 'unspecified
1129 * error' when trying to access the offsetParent of such an element
1131 * @param {HTMLElement} el the element to check
1132 * @return {boolean} true if the element looks usable
1135 verifyEl: function(el) {
1138 var parent = el.offsetParent;
1144 YAHOO.log("detected problem with an element", "info", "DragDropMgr");
1151 * Returns a Region object containing the drag and drop element's position
1152 * and size, including the padding configured for it
1153 * @method getLocation
1154 * @param {DragDrop} oDD the drag and drop object to get the
1156 * @return {YAHOO.util.Region} a Region object representing the total area
1157 * the element occupies, including any padding
1158 * the instance is configured for.
1161 getLocation: function(oDD) {
1162 if (! this.isTypeOfDD(oDD)) {
1163 YAHOO.log(oDD + " is not a DD obj", "info", "DragDropMgr");
1167 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
1170 pos= YAHOO.util.Dom.getXY(el);
1174 YAHOO.log("getXY failed", "info", "DragDropMgr");
1179 x2 = x1 + el.offsetWidth;
1181 y2 = y1 + el.offsetHeight;
1183 t = y1 - oDD.padding[0];
1184 r = x2 + oDD.padding[1];
1185 b = y2 + oDD.padding[2];
1186 l = x1 - oDD.padding[3];
1188 return new YAHOO.util.Region( t, r, b, l );
1192 * Checks the cursor location to see if it over the target
1193 * @method isOverTarget
1194 * @param {YAHOO.util.Point} pt The point to evaluate
1195 * @param {DragDrop} oTarget the DragDrop object we are inspecting
1196 * @param {boolean} intersect true if we are in intersect mode
1197 * @param {YAHOO.util.Region} pre-cached location of the dragged element
1198 * @return {boolean} true if the mouse is over the target
1202 isOverTarget: function(pt, oTarget, intersect, curRegion) {
1203 // use cache if available
1204 var loc = this.locationCache[oTarget.id];
1205 if (!loc || !this.useCache) {
1206 YAHOO.log("cache not populated", "info", "DragDropMgr");
1207 loc = this.getLocation(oTarget);
1208 this.locationCache[oTarget.id] = loc;
1210 YAHOO.log("cache: " + loc, "info", "DragDropMgr");
1214 YAHOO.log("could not get the location of the element", "info", "DragDropMgr");
1218 //YAHOO.log("loc: " + loc + ", pt: " + pt);
1219 oTarget.cursorIsOver = loc.contains( pt );
1221 // DragDrop is using this as a sanity check for the initial mousedown
1222 // in this case we are done. In POINT mode, if the drag obj has no
1223 // contraints, we are done. Otherwise we need to evaluate the
1224 // region the target as occupies to determine if the dragged element
1225 // overlaps with it.
1227 var dc = this.dragCurrent;
1228 if (!dc || (!intersect && !dc.constrainX && !dc.constrainY)) {
1230 //if (oTarget.cursorIsOver) {
1231 //YAHOO.log("over " + oTarget + ", " + loc + ", " + pt, "warn");
1233 return oTarget.cursorIsOver;
1236 oTarget.overlap = null;
1239 // Get the current location of the drag element, this is the
1240 // location of the mouse event less the delta that represents
1241 // where the original mousedown happened on the element. We
1242 // need to consider constraints and ticks as well.
1245 var pos = dc.getTargetCoord(pt.x, pt.y);
1246 var el = dc.getDragEl();
1247 curRegion = new YAHOO.util.Region( pos.y,
1248 pos.x + el.offsetWidth,
1249 pos.y + el.offsetHeight,
1253 var overlap = curRegion.intersect(loc);
1256 oTarget.overlap = overlap;
1257 return (intersect) ? true : oTarget.cursorIsOver;
1264 * unload event handler
1269 _onUnload: function(e, me) {
1274 * Cleans up the drag and drop events and objects.
1279 unregAll: function() {
1280 YAHOO.log("unregister all", "info", "DragDropMgr");
1282 if (this.dragCurrent) {
1284 this.dragCurrent = null;
1287 this._execOnAll("unreg", []);
1289 //for (var i in this.elementCache) {
1290 //delete this.elementCache[i];
1292 //this.elementCache = {};
1298 * A cache of DOM elements
1299 * @property elementCache
1302 * @deprecated elements are not cached now
1307 * Get the wrapper for the DOM element specified
1308 * @method getElWrapper
1309 * @param {String} id the id of the element to get
1310 * @return {YAHOO.util.DDM.ElementWrapper} the wrapped element
1312 * @deprecated This wrapper isn't that useful
1315 getElWrapper: function(id) {
1316 var oWrapper = this.elementCache[id];
1317 if (!oWrapper || !oWrapper.el) {
1318 oWrapper = this.elementCache[id] =
1319 new this.ElementWrapper(YAHOO.util.Dom.get(id));
1325 * Returns the actual DOM element
1326 * @method getElement
1327 * @param {String} id the id of the elment to get
1328 * @return {Object} The element
1329 * @deprecated use YAHOO.util.Dom.get instead
1332 getElement: function(id) {
1333 return YAHOO.util.Dom.get(id);
1337 * Returns the style property for the DOM element (i.e.,
1338 * document.getElById(id).style)
1340 * @param {String} id the id of the elment to get
1341 * @return {Object} The style property of the element
1342 * @deprecated use YAHOO.util.Dom instead
1345 getCss: function(id) {
1346 var el = YAHOO.util.Dom.get(id);
1347 return (el) ? el.style : null;
1351 * Inner class for cached elements
1352 * @class DragDropMgr.ElementWrapper
1357 ElementWrapper: function(el) {
1362 this.el = el || null;
1367 this.id = this.el && el.id;
1369 * A reference to the style property
1372 this.css = this.el && el.style;
1376 * Returns the X position of an html element
1378 * @param el the element for which to get the position
1379 * @return {int} the X coordinate
1381 * @deprecated use YAHOO.util.Dom.getX instead
1384 getPosX: function(el) {
1385 return YAHOO.util.Dom.getX(el);
1389 * Returns the Y position of an html element
1391 * @param el the element for which to get the position
1392 * @return {int} the Y coordinate
1393 * @deprecated use YAHOO.util.Dom.getY instead
1396 getPosY: function(el) {
1397 return YAHOO.util.Dom.getY(el);
1401 * Swap two nodes. In IE, we use the native method, for others we
1402 * emulate the IE behavior
1404 * @param n1 the first node to swap
1405 * @param n2 the other node to swap
1408 swapNode: function(n1, n2) {
1412 var p = n2.parentNode;
1413 var s = n2.nextSibling;
1416 p.insertBefore(n1, n2);
1417 } else if (n2 == n1.nextSibling) {
1418 p.insertBefore(n2, n1);
1420 n1.parentNode.replaceChild(n2, n1);
1421 p.insertBefore(n1, s);
1427 * Returns the current scroll position
1432 getScroll: function () {
1433 var t, l, dde=document.documentElement, db=document.body;
1434 if (dde && (dde.scrollTop || dde.scrollLeft)) {
1441 YAHOO.log("could not get scroll property", "info", "DragDropMgr");
1443 return { top: t, left: l };
1447 * Returns the specified element style property
1449 * @param {HTMLElement} el the element
1450 * @param {string} styleProp the style property
1451 * @return {string} The value of the style property
1452 * @deprecated use YAHOO.util.Dom.getStyle
1455 getStyle: function(el, styleProp) {
1456 return YAHOO.util.Dom.getStyle(el, styleProp);
1460 * Gets the scrollTop
1461 * @method getScrollTop
1462 * @return {int} the document's scrollTop
1465 getScrollTop: function () { return this.getScroll().top; },
1468 * Gets the scrollLeft
1469 * @method getScrollLeft
1470 * @return {int} the document's scrollTop
1473 getScrollLeft: function () { return this.getScroll().left; },
1476 * Sets the x/y position of an element to the location of the
1479 * @param {HTMLElement} moveEl The element to move
1480 * @param {HTMLElement} targetEl The position reference element
1483 moveToEl: function (moveEl, targetEl) {
1484 var aCoord = YAHOO.util.Dom.getXY(targetEl);
1485 YAHOO.log("moveToEl: " + aCoord, "info", "DragDropMgr");
1486 YAHOO.util.Dom.setXY(moveEl, aCoord);
1490 * Gets the client height
1491 * @method getClientHeight
1492 * @return {int} client height in px
1493 * @deprecated use YAHOO.util.Dom.getViewportHeight instead
1496 getClientHeight: function() {
1497 return YAHOO.util.Dom.getViewportHeight();
1501 * Gets the client width
1502 * @method getClientWidth
1503 * @return {int} client width in px
1504 * @deprecated use YAHOO.util.Dom.getViewportWidth instead
1507 getClientWidth: function() {
1508 return YAHOO.util.Dom.getViewportWidth();
1512 * Numeric array sort function
1513 * @method numericSort
1516 numericSort: function(a, b) { return (a - b); },
1520 * @property _timeoutCount
1527 * Trying to make the load order less important. Without this we get
1528 * an error if this file is loaded before the Event Utility.
1529 * @method _addListeners
1533 _addListeners: function() {
1534 var DDM = YAHOO.util.DDM;
1535 if ( YAHOO.util.Event && document ) {
1538 if (DDM._timeoutCount > 2000) {
1539 YAHOO.log("DragDrop requires the Event Utility", "error", "DragDropMgr");
1541 setTimeout(DDM._addListeners, 10);
1542 if (document && document.body) {
1543 DDM._timeoutCount += 1;
1550 * Recursively searches the immediate parent and all child nodes for
1551 * the handle element in order to determine wheter or not it was
1553 * @method handleWasClicked
1554 * @param node the html element to inspect
1557 handleWasClicked: function(node, id) {
1558 if (this.isHandle(id, node.id)) {
1559 YAHOO.log("clicked node is a handle", "info", "DragDropMgr");
1562 // check to see if this is a text node child of the one we want
1563 var p = node.parentNode;
1564 // YAHOO.log("p: " + p);
1567 if (this.isHandle(id, p.id)) {
1570 YAHOO.log(p.id + " is not a handle", "info", "DragDropMgr");
1583 // shorter alias, save a few bytes
1584 YAHOO.util.DDM = YAHOO.util.DragDropMgr;
1585 YAHOO.util.DDM._addListeners();
1591 var Event=YAHOO.util.Event;
1592 var Dom=YAHOO.util.Dom;
1595 * Defines the interface and base operation of items that that can be
1596 * dragged or can be drop targets. It was designed to be extended, overriding
1597 * the event handlers for startDrag, onDrag, onDragOver, onDragOut.
1598 * Up to three html elements can be associated with a DragDrop instance:
1600 * <li>linked element: the element that is passed into the constructor.
1601 * This is the element which defines the boundaries for interaction with
1602 * other DragDrop objects.</li>
1603 * <li>handle element(s): The drag operation only occurs if the element that
1604 * was clicked matches a handle element. By default this is the linked
1605 * element, but there are times that you will want only a portion of the
1606 * linked element to initiate the drag operation, and the setHandleElId()
1607 * method provides a way to define this.</li>
1608 * <li>drag element: this represents an the element that would be moved along
1609 * with the cursor during a drag operation. By default, this is the linked
1610 * element itself as in {@link YAHOO.util.DD}. setDragElId() lets you define
1611 * a separate element that would be moved, as in {@link YAHOO.util.DDProxy}
1614 * This class should not be instantiated until the onload event to ensure that
1615 * the associated elements are available.
1616 * The following would define a DragDrop obj that would interact with any
1617 * other DragDrop obj in the "group1" group:
1619 * dd = new YAHOO.util.DragDrop("div1", "group1");
1621 * Since none of the event handlers have been implemented, nothing would
1622 * actually happen if you were to run the code above. Normally you would
1623 * override this class or one of the default implementations, but you can
1624 * also override the methods you want on an instance of the class...
1626 * dd.onDragDrop = function(e, id) {
1627 * alert("dd was dropped on " + id);
1630 * @namespace YAHOO.util
1633 * @param {String} id of the element that is linked to this instance
1634 * @param {String} sGroup the group of related DragDrop objects
1635 * @param {object} config an object containing configurable attributes
1636 * Valid properties for DragDrop:
1637 * padding, isTarget, maintainOffset, primaryButtonOnly,
1639 YAHOO.util.DragDrop = function(id, sGroup, config) {
1641 this.init(id, sGroup, config);
1645 YAHOO.util.DragDrop.prototype = {
1647 * An Object Literal containing the events that we will be using: mouseDown, b4MouseDown, mouseUp, b4StartDrag, startDrag, b4EndDrag, endDrag, mouseUp, drag, b4Drag, invalidDrop, b4DragOut, dragOut, dragEnter, b4DragOver, dragOver, b4DragDrop, dragDrop
1648 * By setting any of these to false, then event will not be fired.
1655 * @description Shortcut for EventProvider.subscribe, see <a href="YAHOO.util.EventProvider.html#subscribe">YAHOO.util.EventProvider.subscribe</a>
1658 this.subscribe.apply(this, arguments);
1661 * The id of the element associated with this object. This is what we
1662 * refer to as the "linked element" because the size and position of
1663 * this element is used to determine when the drag and drop objects have
1671 * Configuration attributes passed into the constructor
1678 * The id of the element that will be dragged. By default this is same
1679 * as the linked element , but could be changed to another element. Ex:
1680 * YAHOO.util.DDProxy
1681 * @property dragElId
1688 * the id of the element that initiates the drag operation. By default
1689 * this is the linked element, but could be changed to be a child of this
1690 * element. This lets us do things like only starting the drag when the
1691 * header element within the linked html element is clicked.
1692 * @property handleElId
1699 * An associative array of HTML tags that will be ignored if clicked.
1700 * @property invalidHandleTypes
1701 * @type {string: string}
1703 invalidHandleTypes: null,
1706 * An associative array of ids for elements that will be ignored if clicked
1707 * @property invalidHandleIds
1708 * @type {string: string}
1710 invalidHandleIds: null,
1713 * An indexted array of css class names for elements that will be ignored
1715 * @property invalidHandleClasses
1718 invalidHandleClasses: null,
1721 * The linked element's absolute X position at the time the drag was
1723 * @property startPageX
1730 * The linked element's absolute X position at the time the drag was
1732 * @property startPageY
1739 * The group defines a logical collection of DragDrop objects that are
1740 * related. Instances only get events when interacting with other
1741 * DragDrop object in the same group. This lets us define multiple
1742 * groups using a single DragDrop subclass if we want.
1744 * @type {string: string}
1749 * Individual drag/drop instances can be locked. This will prevent
1750 * onmousedown start drag.
1758 * Lock this instance
1761 lock: function() { this.locked = true; },
1764 * Unlock this instace
1767 unlock: function() { this.locked = false; },
1770 * By default, all instances can be a drop target. This can be disabled by
1771 * setting isTarget to false.
1772 * @property isTarget
1778 * The padding configured for this drag and drop object for calculating
1779 * the drop zone intersection with this object.
1785 * If this flag is true, do not fire drop events. The element is a drag only element (for movement not dropping)
1786 * @property dragOnly
1792 * If this flag is true, a shim will be placed over the screen/viewable area to track mouse events. Should help with dragging elements over iframes and other controls.
1799 * Cached reference to the linked element
1806 * Internal typeof flag
1807 * @property __ygDragDrop
1813 * Set to true when horizontal contraints are applied
1814 * @property constrainX
1821 * Set to true when vertical contraints are applied
1822 * @property constrainY
1829 * The left constraint
1837 * The right constraint
1854 * The down constraint
1862 * The difference between the click position and the source element's location
1870 * The difference between the click position and the source element's location
1878 * Maintain offsets when we resetconstraints. Set to true when you want
1879 * the position of the element relative to its parent to stay the same
1880 * when the page changes
1882 * @property maintainOffset
1885 maintainOffset: false,
1888 * Array of pixel locations the element will snap to if we specified a
1889 * horizontal graduation/interval. This array is generated automatically
1890 * when you define a tick interval.
1897 * Array of pixel locations the element will snap to if we specified a
1898 * vertical graduation/interval. This array is generated automatically
1899 * when you define a tick interval.
1906 * By default the drag and drop instance will only respond to the primary
1907 * button click (left button for a right-handed mouse). Set to true to
1908 * allow drag and drop to start with any mouse click that is propogated
1910 * @property primaryButtonOnly
1913 primaryButtonOnly: true,
1916 * The availabe property is false until the linked dom element is accessible.
1917 * @property available
1923 * By default, drags can only be initiated if the mousedown occurs in the
1924 * region the linked element is. This is done in part to work around a
1925 * bug in some browsers that mis-report the mousedown if the previous
1926 * mouseup happened outside of the window. This property is set to true
1927 * if outer handles are defined.
1929 * @property hasOuterHandles
1933 hasOuterHandles: false,
1936 * Property that is assigned to a drag and drop object when testing to
1937 * see if it is being targeted by another dd object. This property
1938 * can be used in intersect mode to help determine the focus of
1939 * the mouse interaction. DDM.getBestMatch uses this property first to
1940 * determine the closest match in INTERSECT mode when multiple targets
1941 * are part of the same interaction.
1942 * @property cursorIsOver
1945 cursorIsOver: false,
1948 * Property that is assigned to a drag and drop object when testing to
1949 * see if it is being targeted by another dd object. This is a region
1950 * that represents the area the draggable element overlaps this target.
1951 * DDM.getBestMatch uses this property to compare the size of the overlap
1952 * to that of other targets in order to determine the closest match in
1953 * INTERSECT mode when multiple targets are part of the same interaction.
1955 * @type YAHOO.util.Region
1960 * Code that executes immediately before the startDrag event
1961 * @method b4StartDrag
1964 b4StartDrag: function(x, y) { },
1967 * Abstract method called after a drag/drop object is clicked
1968 * and the drag or mousedown time thresholds have beeen met.
1970 * @param {int} X click location
1971 * @param {int} Y click location
1973 startDrag: function(x, y) { /* override this */ },
1976 * Code that executes immediately before the onDrag event
1980 b4Drag: function(e) { },
1983 * Abstract method called during the onMouseMove event while dragging an
1986 * @param {Event} e the mousemove event
1988 onDrag: function(e) { /* override this */ },
1991 * Abstract method called when this element fist begins hovering over
1992 * another DragDrop obj
1993 * @method onDragEnter
1994 * @param {Event} e the mousemove event
1995 * @param {String|DragDrop[]} id In POINT mode, the element
1996 * id this is hovering over. In INTERSECT mode, an array of one or more
1997 * dragdrop items being hovered over.
1999 onDragEnter: function(e, id) { /* override this */ },
2002 * Code that executes immediately before the onDragOver event
2003 * @method b4DragOver
2006 b4DragOver: function(e) { },
2009 * Abstract method called when this element is hovering over another
2011 * @method onDragOver
2012 * @param {Event} e the mousemove event
2013 * @param {String|DragDrop[]} id In POINT mode, the element
2014 * id this is hovering over. In INTERSECT mode, an array of dd items
2015 * being hovered over.
2017 onDragOver: function(e, id) { /* override this */ },
2020 * Code that executes immediately before the onDragOut event
2024 b4DragOut: function(e) { },
2027 * Abstract method called when we are no longer hovering over an element
2029 * @param {Event} e the mousemove event
2030 * @param {String|DragDrop[]} id In POINT mode, the element
2031 * id this was hovering over. In INTERSECT mode, an array of dd items
2032 * that the mouse is no longer over.
2034 onDragOut: function(e, id) { /* override this */ },
2037 * Code that executes immediately before the onDragDrop event
2038 * @method b4DragDrop
2041 b4DragDrop: function(e) { },
2044 * Abstract method called when this item is dropped on another DragDrop
2046 * @method onDragDrop
2047 * @param {Event} e the mouseup event
2048 * @param {String|DragDrop[]} id In POINT mode, the element
2049 * id this was dropped on. In INTERSECT mode, an array of dd items this
2052 onDragDrop: function(e, id) { /* override this */ },
2055 * Abstract method called when this item is dropped on an area with no
2057 * @method onInvalidDrop
2058 * @param {Event} e the mouseup event
2060 onInvalidDrop: function(e) { /* override this */ },
2063 * Code that executes immediately before the endDrag event
2067 b4EndDrag: function(e) { },
2070 * Fired when we are done dragging the object
2072 * @param {Event} e the mouseup event
2074 endDrag: function(e) { /* override this */ },
2077 * Code executed immediately before the onMouseDown event
2078 * @method b4MouseDown
2079 * @param {Event} e the mousedown event
2082 b4MouseDown: function(e) { },
2085 * Event handler that fires when a drag/drop obj gets a mousedown
2086 * @method onMouseDown
2087 * @param {Event} e the mousedown event
2089 onMouseDown: function(e) { /* override this */ },
2092 * Event handler that fires when a drag/drop obj gets a mouseup
2094 * @param {Event} e the mouseup event
2096 onMouseUp: function(e) { /* override this */ },
2099 * Override the onAvailable method to do what is needed after the initial
2100 * position was determined.
2101 * @method onAvailable
2103 onAvailable: function () {
2104 //this.logger.log("onAvailable (base)");
2108 * Returns a reference to the linked element
2110 * @return {HTMLElement} the html element
2113 if (!this._domRef) {
2114 this._domRef = Dom.get(this.id);
2117 return this._domRef;
2121 * Returns a reference to the actual element to drag. By default this is
2122 * the same as the html element, but it can be assigned to another
2123 * element. An example of this can be found in YAHOO.util.DDProxy
2125 * @return {HTMLElement} the html element
2127 getDragEl: function() {
2128 return Dom.get(this.dragElId);
2132 * Sets up the DragDrop object. Must be called in the constructor of any
2133 * YAHOO.util.DragDrop subclass
2135 * @param id the id of the linked element
2136 * @param {String} sGroup the group of related items
2137 * @param {object} config configuration attributes
2139 init: function(id, sGroup, config) {
2140 this.initTarget(id, sGroup, config);
2141 Event.on(this._domRef || this.id, "mousedown",
2142 this.handleMouseDown, this, true);
2144 // Event.on(this.id, "selectstart", Event.preventDefault);
2145 for (var i in this.events) {
2146 this.createEvent(i + 'Event');
2152 * Initializes Targeting functionality only... the object does not
2153 * get a mousedown handler.
2154 * @method initTarget
2155 * @param id the id of the linked element
2156 * @param {String} sGroup the group of related items
2157 * @param {object} config configuration attributes
2159 initTarget: function(id, sGroup, config) {
2161 // configuration attributes
2162 this.config = config || {};
2166 // create a local reference to the drag and drop manager
2167 this.DDM = YAHOO.util.DDM;
2169 // initialize the groups object
2172 // assume that we have an element reference instead of an id if the
2173 // parameter is not a string
2174 if (typeof id !== "string") {
2175 YAHOO.log("id is not a string, assuming it is an HTMLElement");
2177 id = Dom.generateId(id);
2183 // add to an interaction group
2184 this.addToGroup((sGroup) ? sGroup : "default");
2186 // We don't want to register this as the handle with the manager
2187 // so we just set the id rather than calling the setter.
2188 this.handleElId = id;
2190 Event.onAvailable(id, this.handleOnAvailable, this, true);
2192 // create a logger instance
2193 this.logger = (YAHOO.widget.LogWriter) ?
2194 new YAHOO.widget.LogWriter(this.toString()) : YAHOO;
2196 // the linked element is the element that gets dragged by default
2197 this.setDragElId(id);
2199 // by default, clicked anchors will not start drag operations.
2200 // @TODO what else should be here? Probably form fields.
2201 this.invalidHandleTypes = { A: "A" };
2202 this.invalidHandleIds = {};
2203 this.invalidHandleClasses = [];
2209 * Applies the configuration parameters that were passed into the constructor.
2210 * This is supposed to happen at each level through the inheritance chain. So
2211 * a DDProxy implentation will execute apply config on DDProxy, DD, and
2212 * DragDrop in order to get all of the parameters that are available in
2214 * @method applyConfig
2216 applyConfig: function() {
2237 if (this.config.events) {
2238 for (var i in this.config.events) {
2239 if (this.config.events[i] === false) {
2240 this.events[i] = false;
2246 // configurable properties:
2247 // padding, isTarget, maintainOffset, primaryButtonOnly
2248 this.padding = this.config.padding || [0, 0, 0, 0];
2249 this.isTarget = (this.config.isTarget !== false);
2250 this.maintainOffset = (this.config.maintainOffset);
2251 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
2252 this.dragOnly = ((this.config.dragOnly === true) ? true : false);
2253 this.useShim = ((this.config.useShim === true) ? true : false);
2257 * Executed when the linked element is available
2258 * @method handleOnAvailable
2261 handleOnAvailable: function() {
2262 //this.logger.log("handleOnAvailable");
2263 this.available = true;
2264 this.resetConstraints();
2269 * Configures the padding for the target zone in px. Effectively expands
2270 * (or reduces) the virtual object size for targeting calculations.
2271 * Supports css-style shorthand; if only one parameter is passed, all sides
2272 * will have that padding, and if only two are passed, the top and bottom
2273 * will have the first param, the left and right the second.
2274 * @method setPadding
2275 * @param {int} iTop Top pad
2276 * @param {int} iRight Right pad
2277 * @param {int} iBot Bot pad
2278 * @param {int} iLeft Left pad
2280 setPadding: function(iTop, iRight, iBot, iLeft) {
2281 // this.padding = [iLeft, iRight, iTop, iBot];
2282 if (!iRight && 0 !== iRight) {
2283 this.padding = [iTop, iTop, iTop, iTop];
2284 } else if (!iBot && 0 !== iBot) {
2285 this.padding = [iTop, iRight, iTop, iRight];
2287 this.padding = [iTop, iRight, iBot, iLeft];
2292 * Stores the initial placement of the linked element.
2293 * @method setInitialPosition
2294 * @param {int} diffX the X offset, default 0
2295 * @param {int} diffY the Y offset, default 0
2298 setInitPosition: function(diffX, diffY) {
2299 var el = this.getEl();
2301 if (!this.DDM.verifyEl(el)) {
2302 if (el && el.style && (el.style.display == 'none')) {
2303 this.logger.log(this.id + " can not get initial position, element style is display: none");
2305 this.logger.log(this.id + " element is broken");
2310 var dx = diffX || 0;
2311 var dy = diffY || 0;
2313 var p = Dom.getXY( el );
2315 this.initPageX = p[0] - dx;
2316 this.initPageY = p[1] - dy;
2318 this.lastPageX = p[0];
2319 this.lastPageY = p[1];
2321 this.logger.log(this.id + " initial position: " + this.initPageX +
2322 ", " + this.initPageY);
2325 this.setStartPosition(p);
2329 * Sets the start position of the element. This is set when the obj
2330 * is initialized, the reset when a drag is started.
2331 * @method setStartPosition
2332 * @param pos current position (from previous lookup)
2335 setStartPosition: function(pos) {
2336 var p = pos || Dom.getXY(this.getEl());
2338 this.deltaSetXY = null;
2340 this.startPageX = p[0];
2341 this.startPageY = p[1];
2345 * Add this instance to a group of related drag/drop objects. All
2346 * instances belong to at least one group, and can belong to as many
2348 * @method addToGroup
2349 * @param sGroup {string} the name of the group
2351 addToGroup: function(sGroup) {
2352 this.groups[sGroup] = true;
2353 this.DDM.regDragDrop(this, sGroup);
2357 * Remove's this instance from the supplied interaction group
2358 * @method removeFromGroup
2359 * @param {string} sGroup The group to drop
2361 removeFromGroup: function(sGroup) {
2362 this.logger.log("Removing from group: " + sGroup);
2363 if (this.groups[sGroup]) {
2364 delete this.groups[sGroup];
2367 this.DDM.removeDDFromGroup(this, sGroup);
2371 * Allows you to specify that an element other than the linked element
2372 * will be moved with the cursor during a drag
2373 * @method setDragElId
2374 * @param id {string} the id of the element that will be used to initiate the drag
2376 setDragElId: function(id) {
2381 * Allows you to specify a child of the linked element that should be
2382 * used to initiate the drag operation. An example of this would be if
2383 * you have a content div with text and links. Clicking anywhere in the
2384 * content area would normally start the drag operation. Use this method
2385 * to specify that an element inside of the content div is the element
2386 * that starts the drag operation.
2387 * @method setHandleElId
2388 * @param id {string} the id of the element that will be used to
2389 * initiate the drag.
2391 setHandleElId: function(id) {
2392 if (typeof id !== "string") {
2393 YAHOO.log("id is not a string, assuming it is an HTMLElement");
2394 id = Dom.generateId(id);
2396 this.handleElId = id;
2397 this.DDM.regHandle(this.id, id);
2401 * Allows you to set an element outside of the linked element as a drag
2403 * @method setOuterHandleElId
2404 * @param id the id of the element that will be used to initiate the drag
2406 setOuterHandleElId: function(id) {
2407 if (typeof id !== "string") {
2408 YAHOO.log("id is not a string, assuming it is an HTMLElement");
2409 id = Dom.generateId(id);
2411 this.logger.log("Adding outer handle event: " + id);
2412 Event.on(id, "mousedown",
2413 this.handleMouseDown, this, true);
2414 this.setHandleElId(id);
2416 this.hasOuterHandles = true;
2420 * Remove all drag and drop hooks for this element
2424 this.logger.log("DragDrop obj cleanup " + this.id);
2425 Event.removeListener(this.id, "mousedown",
2426 this.handleMouseDown);
2427 this._domRef = null;
2428 this.DDM._remove(this);
2432 * Returns true if this instance is locked, or the drag drop mgr is locked
2433 * (meaning that all drag/drop is disabled on the page.)
2435 * @return {boolean} true if this obj or all drag/drop is locked, else
2438 isLocked: function() {
2439 return (this.DDM.isLocked() || this.locked);
2443 * Fired when this object is clicked
2444 * @method handleMouseDown
2446 * @param {YAHOO.util.DragDrop} oDD the clicked dd object (this dd obj)
2449 handleMouseDown: function(e, oDD) {
2451 var button = e.which || e.button;
2452 this.logger.log("button: " + button);
2454 if (this.primaryButtonOnly && button > 1) {
2455 this.logger.log("Mousedown was not produced by the primary button");
2459 if (this.isLocked()) {
2460 this.logger.log("Drag and drop is disabled, aborting");
2464 this.logger.log("mousedown " + this.id);
2466 this.logger.log("firing onMouseDown events");
2468 // firing the mousedown events prior to calculating positions
2469 var b4Return = this.b4MouseDown(e),
2472 if (this.events.b4MouseDown) {
2473 b4Return2 = this.fireEvent('b4MouseDownEvent', e);
2475 var mDownReturn = this.onMouseDown(e),
2476 mDownReturn2 = true;
2477 if (this.events.mouseDown) {
2478 mDownReturn2 = this.fireEvent('mouseDownEvent', e);
2481 if ((b4Return === false) || (mDownReturn === false) || (b4Return2 === false) || (mDownReturn2 === false)) {
2482 this.logger.log('b4MouseDown or onMouseDown returned false, exiting drag');
2486 this.DDM.refreshCache(this.groups);
2488 // setTimeout( function() { self.DDM.refreshCache(self.groups); }, 0);
2490 // Only process the event if we really clicked within the linked
2491 // element. The reason we make this check is that in the case that
2492 // another element was moved between the clicked element and the
2493 // cursor in the time between the mousedown and mouseup events. When
2494 // this happens, the element gets the next mousedown event
2495 // regardless of where on the screen it happened.
2496 var pt = new YAHOO.util.Point(Event.getPageX(e), Event.getPageY(e));
2497 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
2498 this.logger.log("Click was not over the element: " + this.id);
2500 if (this.clickValidator(e)) {
2502 this.logger.log("click was a valid handle");
2504 // set the initial element position
2505 this.setStartPosition();
2507 // start tracking mousemove distance and mousedown time to
2508 // determine when to start the actual drag
2509 this.DDM.handleMouseDown(e, this);
2511 // this mousedown is mine
2512 this.DDM.stopEvent(e);
2515 this.logger.log("clickValidator returned false, drag not initiated");
2522 * @method clickValidator
2523 * @description Method validates that the clicked element
2524 * was indeed the handle or a valid child of the handle
2527 clickValidator: function(e) {
2528 var target = YAHOO.util.Event.getTarget(e);
2529 return ( this.isValidHandleChild(target) &&
2530 (this.id == this.handleElId ||
2531 this.DDM.handleWasClicked(target, this.id)) );
2535 * Finds the location the element should be placed if we want to move
2536 * it to where the mouse location less the click offset would place us.
2537 * @method getTargetCoord
2538 * @param {int} iPageX the X coordinate of the click
2539 * @param {int} iPageY the Y coordinate of the click
2540 * @return an object that contains the coordinates (Object.x and Object.y)
2543 getTargetCoord: function(iPageX, iPageY) {
2545 // this.logger.log("getTargetCoord: " + iPageX + ", " + iPageY);
2547 var x = iPageX - this.deltaX;
2548 var y = iPageY - this.deltaY;
2550 if (this.constrainX) {
2551 if (x < this.minX) { x = this.minX; }
2552 if (x > this.maxX) { x = this.maxX; }
2555 if (this.constrainY) {
2556 if (y < this.minY) { y = this.minY; }
2557 if (y > this.maxY) { y = this.maxY; }
2560 x = this.getTick(x, this.xTicks);
2561 y = this.getTick(y, this.yTicks);
2563 // this.logger.log("getTargetCoord " +
2564 // " iPageX: " + iPageX +
2565 // " iPageY: " + iPageY +
2566 // " x: " + x + ", y: " + y);
2572 * Allows you to specify a tag name that should not start a drag operation
2573 * when clicked. This is designed to facilitate embedding links within a
2574 * drag handle that do something other than start the drag.
2575 * @method addInvalidHandleType
2576 * @param {string} tagName the type of element to exclude
2578 addInvalidHandleType: function(tagName) {
2579 var type = tagName.toUpperCase();
2580 this.invalidHandleTypes[type] = type;
2584 * Lets you to specify an element id for a child of a drag handle
2585 * that should not initiate a drag
2586 * @method addInvalidHandleId
2587 * @param {string} id the element id of the element you wish to ignore
2589 addInvalidHandleId: function(id) {
2590 if (typeof id !== "string") {
2591 YAHOO.log("id is not a string, assuming it is an HTMLElement");
2592 id = Dom.generateId(id);
2594 this.invalidHandleIds[id] = id;
2599 * Lets you specify a css class of elements that will not initiate a drag
2600 * @method addInvalidHandleClass
2601 * @param {string} cssClass the class of the elements you wish to ignore
2603 addInvalidHandleClass: function(cssClass) {
2604 this.invalidHandleClasses.push(cssClass);
2608 * Unsets an excluded tag name set by addInvalidHandleType
2609 * @method removeInvalidHandleType
2610 * @param {string} tagName the type of element to unexclude
2612 removeInvalidHandleType: function(tagName) {
2613 var type = tagName.toUpperCase();
2614 // this.invalidHandleTypes[type] = null;
2615 delete this.invalidHandleTypes[type];
2619 * Unsets an invalid handle id
2620 * @method removeInvalidHandleId
2621 * @param {string} id the id of the element to re-enable
2623 removeInvalidHandleId: function(id) {
2624 if (typeof id !== "string") {
2625 YAHOO.log("id is not a string, assuming it is an HTMLElement");
2626 id = Dom.generateId(id);
2628 delete this.invalidHandleIds[id];
2632 * Unsets an invalid css class
2633 * @method removeInvalidHandleClass
2634 * @param {string} cssClass the class of the element(s) you wish to
2637 removeInvalidHandleClass: function(cssClass) {
2638 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
2639 if (this.invalidHandleClasses[i] == cssClass) {
2640 delete this.invalidHandleClasses[i];
2646 * Checks the tag exclusion list to see if this click should be ignored
2647 * @method isValidHandleChild
2648 * @param {HTMLElement} node the HTMLElement to evaluate
2649 * @return {boolean} true if this is a valid tag type, false if not
2651 isValidHandleChild: function(node) {
2654 // var n = (node.nodeName == "#text") ? node.parentNode : node;
2657 nodeName = node.nodeName.toUpperCase();
2659 nodeName = node.nodeName;
2661 valid = valid && !this.invalidHandleTypes[nodeName];
2662 valid = valid && !this.invalidHandleIds[node.id];
2664 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
2665 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
2668 this.logger.log("Valid handle? ... " + valid);
2675 * Create the array of horizontal tick marks if an interval was specified
2676 * in setXConstraint().
2680 setXTicks: function(iStartX, iTickSize) {
2682 this.xTickSize = iTickSize;
2686 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
2688 this.xTicks[this.xTicks.length] = i;
2693 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
2695 this.xTicks[this.xTicks.length] = i;
2700 this.xTicks.sort(this.DDM.numericSort) ;
2701 this.logger.log("xTicks: " + this.xTicks.join());
2705 * Create the array of vertical tick marks if an interval was specified in
2710 setYTicks: function(iStartY, iTickSize) {
2711 // this.logger.log("setYTicks: " + iStartY + ", " + iTickSize
2712 // + ", " + this.initPageY + ", " + this.minY + ", " + this.maxY );
2714 this.yTickSize = iTickSize;
2718 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
2720 this.yTicks[this.yTicks.length] = i;
2725 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
2727 this.yTicks[this.yTicks.length] = i;
2732 this.yTicks.sort(this.DDM.numericSort) ;
2733 this.logger.log("yTicks: " + this.yTicks.join());
2737 * By default, the element can be dragged any place on the screen. Use
2738 * this method to limit the horizontal travel of the element. Pass in
2739 * 0,0 for the parameters if you want to lock the drag to the y axis.
2740 * @method setXConstraint
2741 * @param {int} iLeft the number of pixels the element can move to the left
2742 * @param {int} iRight the number of pixels the element can move to the
2744 * @param {int} iTickSize optional parameter for specifying that the
2746 * should move iTickSize pixels at a time.
2748 setXConstraint: function(iLeft, iRight, iTickSize) {
2749 this.leftConstraint = parseInt(iLeft, 10);
2750 this.rightConstraint = parseInt(iRight, 10);
2752 this.minX = this.initPageX - this.leftConstraint;
2753 this.maxX = this.initPageX + this.rightConstraint;
2754 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
2756 this.constrainX = true;
2757 this.logger.log("initPageX:" + this.initPageX + " minX:" + this.minX +
2758 " maxX:" + this.maxX);
2762 * Clears any constraints applied to this instance. Also clears ticks
2763 * since they can't exist independent of a constraint at this time.
2764 * @method clearConstraints
2766 clearConstraints: function() {
2767 this.logger.log("Clearing constraints");
2768 this.constrainX = false;
2769 this.constrainY = false;
2774 * Clears any tick interval defined for this instance
2775 * @method clearTicks
2777 clearTicks: function() {
2778 this.logger.log("Clearing ticks");
2786 * By default, the element can be dragged any place on the screen. Set
2787 * this to limit the vertical travel of the element. Pass in 0,0 for the
2788 * parameters if you want to lock the drag to the x axis.
2789 * @method setYConstraint
2790 * @param {int} iUp the number of pixels the element can move up
2791 * @param {int} iDown the number of pixels the element can move down
2792 * @param {int} iTickSize optional parameter for specifying that the
2793 * element should move iTickSize pixels at a time.
2795 setYConstraint: function(iUp, iDown, iTickSize) {
2796 this.logger.log("setYConstraint: " + iUp + "," + iDown + "," + iTickSize);
2797 this.topConstraint = parseInt(iUp, 10);
2798 this.bottomConstraint = parseInt(iDown, 10);
2800 this.minY = this.initPageY - this.topConstraint;
2801 this.maxY = this.initPageY + this.bottomConstraint;
2802 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
2804 this.constrainY = true;
2806 this.logger.log("initPageY:" + this.initPageY + " minY:" + this.minY +
2807 " maxY:" + this.maxY);
2811 * resetConstraints must be called if you manually reposition a dd element.
2812 * @method resetConstraints
2814 resetConstraints: function() {
2816 //this.logger.log("resetConstraints");
2818 // Maintain offsets if necessary
2819 if (this.initPageX || this.initPageX === 0) {
2820 //this.logger.log("init pagexy: " + this.initPageX + ", " +
2822 //this.logger.log("last pagexy: " + this.lastPageX + ", " +
2824 // figure out how much this thing has moved
2825 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
2826 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
2828 this.setInitPosition(dx, dy);
2830 // This is the first time we have detected the element's position
2832 this.setInitPosition();
2835 if (this.constrainX) {
2836 this.setXConstraint( this.leftConstraint,
2837 this.rightConstraint,
2841 if (this.constrainY) {
2842 this.setYConstraint( this.topConstraint,
2843 this.bottomConstraint,
2849 * Normally the drag element is moved pixel by pixel, but we can specify
2850 * that it move a number of pixels at a time. This method resolves the
2851 * location when we have it set up like this.
2853 * @param {int} val where we want to place the object
2854 * @param {int[]} tickArray sorted array of valid points
2855 * @return {int} the closest tick
2858 getTick: function(val, tickArray) {
2861 // If tick interval is not defined, it is effectively 1 pixel,
2862 // so we return the value passed to us.
2864 } else if (tickArray[0] >= val) {
2865 // The value is lower than the first tick, so we return the first
2867 return tickArray[0];
2869 for (var i=0, len=tickArray.length; i<len; ++i) {
2871 if (tickArray[next] && tickArray[next] >= val) {
2872 var diff1 = val - tickArray[i];
2873 var diff2 = tickArray[next] - val;
2874 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
2878 // The value is larger than the last tick, so we return the last
2880 return tickArray[tickArray.length - 1];
2887 * @return {string} string representation of the dd obj
2889 toString: function() {
2890 return ("DragDrop " + this.id);
2894 YAHOO.augment(YAHOO.util.DragDrop, YAHOO.util.EventProvider);
2897 * @event mouseDownEvent
2898 * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation.
2899 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2903 * @event b4MouseDownEvent
2904 * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag.
2905 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2909 * @event mouseUpEvent
2910 * @description Fired from inside DragDropMgr when the drag operation is finished.
2911 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2915 * @event b4StartDragEvent
2916 * @description Fires before the startDragEvent, returning false will cancel the startDrag Event.
2917 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2921 * @event startDragEvent
2922 * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown.
2923 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2927 * @event b4EndDragEvent
2928 * @description Fires before the endDragEvent. Returning false will cancel.
2929 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2933 * @event endDragEvent
2934 * @description Fires on the mouseup event after a drag has been initiated (startDrag fired).
2935 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2940 * @description Occurs every mousemove event while dragging.
2941 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2944 * @event b4DragEvent
2945 * @description Fires before the dragEvent.
2946 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2949 * @event invalidDropEvent
2950 * @description Fires when the dragged objects is dropped in a location that contains no drop targets.
2951 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2954 * @event b4DragOutEvent
2955 * @description Fires before the dragOutEvent
2956 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2959 * @event dragOutEvent
2960 * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire.
2961 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2964 * @event dragEnterEvent
2965 * @description Occurs when the dragged object first interacts with another targettable drag and drop object.
2966 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2969 * @event b4DragOverEvent
2970 * @description Fires before the dragOverEvent.
2971 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2974 * @event dragOverEvent
2975 * @description Fires every mousemove event while over a drag and drop object.
2976 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2979 * @event b4DragDropEvent
2980 * @description Fires before the dragDropEvent
2981 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2984 * @event dragDropEvent
2985 * @description Fires when the dragged objects is dropped on another.
2986 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
2990 * A DragDrop implementation where the linked element follows the
2991 * mouse cursor during a drag.
2993 * @extends YAHOO.util.DragDrop
2995 * @param {String} id the id of the linked element
2996 * @param {String} sGroup the group of related DragDrop items
2997 * @param {object} config an object containing configurable attributes
2998 * Valid properties for DD:
3001 YAHOO.util.DD = function(id, sGroup, config) {
3003 this.init(id, sGroup, config);
3007 YAHOO.extend(YAHOO.util.DD, YAHOO.util.DragDrop, {
3010 * When set to true, the utility automatically tries to scroll the browser
3011 * window when a drag and drop element is dragged near the viewport boundary.
3019 * Sets the pointer offset to the distance between the linked element's top
3020 * left corner and the location the element was clicked
3021 * @method autoOffset
3022 * @param {int} iPageX the X coordinate of the click
3023 * @param {int} iPageY the Y coordinate of the click
3025 autoOffset: function(iPageX, iPageY) {
3026 var x = iPageX - this.startPageX;
3027 var y = iPageY - this.startPageY;
3028 this.setDelta(x, y);
3029 // this.logger.log("autoOffset el pos: " + aCoord + ", delta: " + x + "," + y);
3033 * Sets the pointer offset. You can call this directly to force the
3034 * offset to be in a particular location (e.g., pass in 0,0 to set it
3035 * to the center of the object, as done in YAHOO.widget.Slider)
3037 * @param {int} iDeltaX the distance from the left
3038 * @param {int} iDeltaY the distance from the top
3040 setDelta: function(iDeltaX, iDeltaY) {
3041 this.deltaX = iDeltaX;
3042 this.deltaY = iDeltaY;
3043 this.logger.log("deltaX:" + this.deltaX + ", deltaY:" + this.deltaY);
3047 * Sets the drag element to the location of the mousedown or click event,
3048 * maintaining the cursor location relative to the location on the element
3049 * that was clicked. Override this if you want to place the element in a
3050 * location other than where the cursor is.
3051 * @method setDragElPos
3052 * @param {int} iPageX the X coordinate of the mousedown or drag event
3053 * @param {int} iPageY the Y coordinate of the mousedown or drag event
3055 setDragElPos: function(iPageX, iPageY) {
3056 // the first time we do this, we are going to check to make sure
3057 // the element has css positioning
3059 var el = this.getDragEl();
3060 this.alignElWithMouse(el, iPageX, iPageY);
3064 * Sets the element to the location of the mousedown or click event,
3065 * maintaining the cursor location relative to the location on the element
3066 * that was clicked. Override this if you want to place the element in a
3067 * location other than where the cursor is.
3068 * @method alignElWithMouse
3069 * @param {HTMLElement} el the element to move
3070 * @param {int} iPageX the X coordinate of the mousedown or drag event
3071 * @param {int} iPageY the Y coordinate of the mousedown or drag event
3073 alignElWithMouse: function(el, iPageX, iPageY) {
3074 var oCoord = this.getTargetCoord(iPageX, iPageY);
3075 // this.logger.log("****alignElWithMouse : " + el.id + ", " + aCoord + ", " + el.style.display);
3077 if (!this.deltaSetXY) {
3078 var aCoord = [oCoord.x, oCoord.y];
3079 YAHOO.util.Dom.setXY(el, aCoord);
3081 var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 );
3082 var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 );
3084 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
3086 YAHOO.util.Dom.setStyle(el, "left", (oCoord.x + this.deltaSetXY[0]) + "px");
3087 YAHOO.util.Dom.setStyle(el, "top", (oCoord.y + this.deltaSetXY[1]) + "px");
3090 this.cachePosition(oCoord.x, oCoord.y);
3092 setTimeout(function() {
3093 self.autoScroll.call(self, oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
3098 * Saves the most recent position so that we can reset the constraints and
3099 * tick marks on-demand. We need to know this so that we can calculate the
3100 * number of pixels the element is offset from its original position.
3101 * @method cachePosition
3102 * @param iPageX the current x position (optional, this just makes it so we
3103 * don't have to look it up again)
3104 * @param iPageY the current y position (optional, this just makes it so we
3105 * don't have to look it up again)
3107 cachePosition: function(iPageX, iPageY) {
3109 this.lastPageX = iPageX;
3110 this.lastPageY = iPageY;
3112 var aCoord = YAHOO.util.Dom.getXY(this.getEl());
3113 this.lastPageX = aCoord[0];
3114 this.lastPageY = aCoord[1];
3119 * Auto-scroll the window if the dragged object has been moved beyond the
3120 * visible window boundary.
3121 * @method autoScroll
3122 * @param {int} x the drag element's x position
3123 * @param {int} y the drag element's y position
3124 * @param {int} h the height of the drag element
3125 * @param {int} w the width of the drag element
3128 autoScroll: function(x, y, h, w) {
3131 // The client height
3132 var clientH = this.DDM.getClientHeight();
3135 var clientW = this.DDM.getClientWidth();
3137 // The amt scrolled down
3138 var st = this.DDM.getScrollTop();
3140 // The amt scrolled right
3141 var sl = this.DDM.getScrollLeft();
3143 // Location of the bottom of the element
3146 // Location of the right of the element
3149 // The distance from the cursor to the bottom of the visible area,
3150 // adjusted so that we don't scroll if the cursor is beyond the
3151 // element drag constraints
3152 var toBot = (clientH + st - y - this.deltaY);
3154 // The distance from the cursor to the right of the visible area
3155 var toRight = (clientW + sl - x - this.deltaX);
3157 // this.logger.log( " x: " + x + " y: " + y + " h: " + h +
3158 // " clientH: " + clientH + " clientW: " + clientW +
3159 // " st: " + st + " sl: " + sl + " bot: " + bot +
3160 // " right: " + right + " toBot: " + toBot + " toRight: " + toRight);
3162 // How close to the edge the cursor must be before we scroll
3163 // var thresh = (document.all) ? 100 : 40;
3166 // How many pixels to scroll per autoscroll op. This helps to reduce
3167 // clunky scrolling. IE is more sensitive about this ... it needs this
3168 // value to be higher.
3169 var scrAmt = (document.all) ? 80 : 30;
3171 // Scroll down if we are near the bottom of the visible page and the
3172 // obj extends below the crease
3173 if ( bot > clientH && toBot < thresh ) {
3174 window.scrollTo(sl, st + scrAmt);
3177 // Scroll up if the window is scrolled down and the top of the object
3178 // goes above the top border
3179 if ( y < st && st > 0 && y - st < thresh ) {
3180 window.scrollTo(sl, st - scrAmt);
3183 // Scroll right if the obj is beyond the right border and the cursor is
3185 if ( right > clientW && toRight < thresh ) {
3186 window.scrollTo(sl + scrAmt, st);
3189 // Scroll left if the window has been scrolled to the right and the obj
3190 // extends past the left border
3191 if ( x < sl && sl > 0 && x - sl < thresh ) {
3192 window.scrollTo(sl - scrAmt, st);
3198 * Sets up config options specific to this class. Overrides
3199 * YAHOO.util.DragDrop, but all versions of this method through the
3200 * inheritance chain are called
3202 applyConfig: function() {
3203 YAHOO.util.DD.superclass.applyConfig.call(this);
3204 this.scroll = (this.config.scroll !== false);
3208 * Event that fires prior to the onMouseDown event. Overrides
3209 * YAHOO.util.DragDrop.
3211 b4MouseDown: function(e) {
3212 this.setStartPosition();
3213 // this.resetConstraints();
3214 this.autoOffset(YAHOO.util.Event.getPageX(e),
3215 YAHOO.util.Event.getPageY(e));
3219 * Event that fires prior to the onDrag event. Overrides
3220 * YAHOO.util.DragDrop.
3222 b4Drag: function(e) {
3223 this.setDragElPos(YAHOO.util.Event.getPageX(e),
3224 YAHOO.util.Event.getPageY(e));
3227 toString: function() {
3228 return ("DD " + this.id);
3231 //////////////////////////////////////////////////////////////////////////
3232 // Debugging ygDragDrop events that can be overridden
3233 //////////////////////////////////////////////////////////////////////////
3235 startDrag: function(x, y) {
3236 this.logger.log(this.id.toString() + " startDrag");
3239 onDrag: function(e) {
3240 this.logger.log(this.id.toString() + " onDrag");
3243 onDragEnter: function(e, id) {
3244 this.logger.log(this.id.toString() + " onDragEnter: " + id);
3247 onDragOver: function(e, id) {
3248 this.logger.log(this.id.toString() + " onDragOver: " + id);
3251 onDragOut: function(e, id) {
3252 this.logger.log(this.id.toString() + " onDragOut: " + id);
3255 onDragDrop: function(e, id) {
3256 this.logger.log(this.id.toString() + " onDragDrop: " + id);
3259 endDrag: function(e) {
3260 this.logger.log(this.id.toString() + " endDrag");
3266 * @event mouseDownEvent
3267 * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation.
3268 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3272 * @event b4MouseDownEvent
3273 * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag.
3274 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3278 * @event mouseUpEvent
3279 * @description Fired from inside DragDropMgr when the drag operation is finished.
3280 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3284 * @event b4StartDragEvent
3285 * @description Fires before the startDragEvent, returning false will cancel the startDrag Event.
3286 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3290 * @event startDragEvent
3291 * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown.
3292 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3296 * @event b4EndDragEvent
3297 * @description Fires before the endDragEvent. Returning false will cancel.
3298 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3302 * @event endDragEvent
3303 * @description Fires on the mouseup event after a drag has been initiated (startDrag fired).
3304 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3309 * @description Occurs every mousemove event while dragging.
3310 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3313 * @event b4DragEvent
3314 * @description Fires before the dragEvent.
3315 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3318 * @event invalidDropEvent
3319 * @description Fires when the dragged objects is dropped in a location that contains no drop targets.
3320 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3323 * @event b4DragOutEvent
3324 * @description Fires before the dragOutEvent
3325 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3328 * @event dragOutEvent
3329 * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire.
3330 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3333 * @event dragEnterEvent
3334 * @description Occurs when the dragged object first interacts with another targettable drag and drop object.
3335 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3338 * @event b4DragOverEvent
3339 * @description Fires before the dragOverEvent.
3340 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3343 * @event dragOverEvent
3344 * @description Fires every mousemove event while over a drag and drop object.
3345 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3348 * @event b4DragDropEvent
3349 * @description Fires before the dragDropEvent
3350 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3353 * @event dragDropEvent
3354 * @description Fires when the dragged objects is dropped on another.
3355 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3359 * A DragDrop implementation that inserts an empty, bordered div into
3360 * the document that follows the cursor during drag operations. At the time of
3361 * the click, the frame div is resized to the dimensions of the linked html
3362 * element, and moved to the exact location of the linked element.
3364 * References to the "frame" element refer to the single proxy element that
3365 * was created to be dragged in place of all DDProxy elements on the
3369 * @extends YAHOO.util.DD
3371 * @param {String} id the id of the linked html element
3372 * @param {String} sGroup the group of related DragDrop objects
3373 * @param {object} config an object containing configurable attributes
3374 * Valid properties for DDProxy in addition to those in DragDrop:
3375 * resizeFrame, centerFrame, dragElId
3377 YAHOO.util.DDProxy = function(id, sGroup, config) {
3379 this.init(id, sGroup, config);
3385 * The default drag frame div id
3386 * @property YAHOO.util.DDProxy.dragElId
3390 YAHOO.util.DDProxy.dragElId = "ygddfdiv";
3392 YAHOO.extend(YAHOO.util.DDProxy, YAHOO.util.DD, {
3395 * By default we resize the drag frame to be the same size as the element
3396 * we want to drag (this is to get the frame effect). We can turn it off
3397 * if we want a different behavior.
3398 * @property resizeFrame
3404 * By default the frame is positioned exactly where the drag element is, so
3405 * we use the cursor offset provided by YAHOO.util.DD. Another option that works only if
3406 * you do not have constraints on the obj is to have the drag frame centered
3407 * around the cursor. Set centerFrame to true for this effect.
3408 * @property centerFrame
3414 * Creates the proxy element if it does not yet exist
3415 * @method createFrame
3417 createFrame: function() {
3418 var self=this, body=document.body;
3420 if (!body || !body.firstChild) {
3421 setTimeout( function() { self.createFrame(); }, 50 );
3425 var div=this.getDragEl(), Dom=YAHOO.util.Dom;
3428 div = document.createElement("div");
3429 div.id = this.dragElId;
3432 s.position = "absolute";
3433 s.visibility = "hidden";
3435 s.border = "2px solid #aaa";
3440 var _data = document.createElement('div');
3441 Dom.setStyle(_data, 'height', '100%');
3442 Dom.setStyle(_data, 'width', '100%');
3444 * If the proxy element has no background-color, then it is considered to the "transparent" by Internet Explorer.
3445 * Since it is "transparent" then the events pass through it to the iframe below.
3446 * So creating a "fake" div inside the proxy element and giving it a background-color, then setting it to an
3447 * opacity of 0, it appears to not be there, however IE still thinks that it is so the events never pass through.
3449 Dom.setStyle(_data, 'background-color', '#ccc');
3450 Dom.setStyle(_data, 'opacity', '0');
3451 div.appendChild(_data);
3453 // appendChild can blow up IE if invoked prior to the window load event
3454 // while rendering a table. It is possible there are other scenarios
3455 // that would cause this to happen as well.
3456 body.insertBefore(div, body.firstChild);
3461 * Initialization for the drag frame element. Must be called in the
3462 * constructor of all subclasses
3465 initFrame: function() {
3469 applyConfig: function() {
3470 //this.logger.log("DDProxy applyConfig");
3471 YAHOO.util.DDProxy.superclass.applyConfig.call(this);
3473 this.resizeFrame = (this.config.resizeFrame !== false);
3474 this.centerFrame = (this.config.centerFrame);
3475 this.setDragElId(this.config.dragElId || YAHOO.util.DDProxy.dragElId);
3479 * Resizes the drag frame to the dimensions of the clicked object, positions
3480 * it over the object, and finally displays it
3482 * @param {int} iPageX X click position
3483 * @param {int} iPageY Y click position
3486 showFrame: function(iPageX, iPageY) {
3487 var el = this.getEl();
3488 var dragEl = this.getDragEl();
3489 var s = dragEl.style;
3491 this._resizeProxy();
3493 if (this.centerFrame) {
3494 this.setDelta( Math.round(parseInt(s.width, 10)/2),
3495 Math.round(parseInt(s.height, 10)/2) );
3498 this.setDragElPos(iPageX, iPageY);
3500 YAHOO.util.Dom.setStyle(dragEl, "visibility", "visible");
3504 * The proxy is automatically resized to the dimensions of the linked
3505 * element when a drag is initiated, unless resizeFrame is set to false
3506 * @method _resizeProxy
3509 _resizeProxy: function() {
3510 if (this.resizeFrame) {
3511 var DOM = YAHOO.util.Dom;
3512 var el = this.getEl();
3513 var dragEl = this.getDragEl();
3515 var bt = parseInt( DOM.getStyle(dragEl, "borderTopWidth" ), 10);
3516 var br = parseInt( DOM.getStyle(dragEl, "borderRightWidth" ), 10);
3517 var bb = parseInt( DOM.getStyle(dragEl, "borderBottomWidth" ), 10);
3518 var bl = parseInt( DOM.getStyle(dragEl, "borderLeftWidth" ), 10);
3520 if (isNaN(bt)) { bt = 0; }
3521 if (isNaN(br)) { br = 0; }
3522 if (isNaN(bb)) { bb = 0; }
3523 if (isNaN(bl)) { bl = 0; }
3525 this.logger.log("proxy size: " + bt + " " + br + " " + bb + " " + bl);
3527 var newWidth = Math.max(0, el.offsetWidth - br - bl);
3528 var newHeight = Math.max(0, el.offsetHeight - bt - bb);
3530 this.logger.log("Resizing proxy element");
3532 DOM.setStyle( dragEl, "width", newWidth + "px" );
3533 DOM.setStyle( dragEl, "height", newHeight + "px" );
3537 // overrides YAHOO.util.DragDrop
3538 b4MouseDown: function(e) {
3539 this.setStartPosition();
3540 var x = YAHOO.util.Event.getPageX(e);
3541 var y = YAHOO.util.Event.getPageY(e);
3542 this.autoOffset(x, y);
3544 // This causes the autoscroll code to kick off, which means autoscroll can
3545 // happen prior to the check for a valid drag handle.
3546 // this.setDragElPos(x, y);
3549 // overrides YAHOO.util.DragDrop
3550 b4StartDrag: function(x, y) {
3551 // show the drag frame
3552 this.logger.log("start drag show frame, x: " + x + ", y: " + y);
3553 this.showFrame(x, y);
3556 // overrides YAHOO.util.DragDrop
3557 b4EndDrag: function(e) {
3558 this.logger.log(this.id + " b4EndDrag");
3559 YAHOO.util.Dom.setStyle(this.getDragEl(), "visibility", "hidden");
3562 // overrides YAHOO.util.DragDrop
3563 // By default we try to move the element to the last location of the frame.
3564 // This is so that the default behavior mirrors that of YAHOO.util.DD.
3565 endDrag: function(e) {
3566 var DOM = YAHOO.util.Dom;
3567 this.logger.log(this.id + " endDrag");
3568 var lel = this.getEl();
3569 var del = this.getDragEl();
3571 // Show the drag frame briefly so we can get its position
3572 // del.style.visibility = "";
3573 DOM.setStyle(del, "visibility", "");
3575 // Hide the linked element before the move to get around a Safari
3577 //lel.style.visibility = "hidden";
3578 DOM.setStyle(lel, "visibility", "hidden");
3579 YAHOO.util.DDM.moveToEl(lel, del);
3580 //del.style.visibility = "hidden";
3581 DOM.setStyle(del, "visibility", "hidden");
3582 //lel.style.visibility = "";
3583 DOM.setStyle(lel, "visibility", "");
3586 toString: function() {
3587 return ("DDProxy " + this.id);
3590 * @event mouseDownEvent
3591 * @description Provides access to the mousedown event. The mousedown does not always result in a drag operation.
3592 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3596 * @event b4MouseDownEvent
3597 * @description Provides access to the mousedown event, before the mouseDownEvent gets fired. Returning false will cancel the drag.
3598 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3602 * @event mouseUpEvent
3603 * @description Fired from inside DragDropMgr when the drag operation is finished.
3604 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3608 * @event b4StartDragEvent
3609 * @description Fires before the startDragEvent, returning false will cancel the startDrag Event.
3610 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3614 * @event startDragEvent
3615 * @description Occurs after a mouse down and the drag threshold has been met. The drag threshold default is either 3 pixels of mouse movement or 1 full second of holding the mousedown.
3616 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3620 * @event b4EndDragEvent
3621 * @description Fires before the endDragEvent. Returning false will cancel.
3622 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3626 * @event endDragEvent
3627 * @description Fires on the mouseup event after a drag has been initiated (startDrag fired).
3628 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3633 * @description Occurs every mousemove event while dragging.
3634 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3637 * @event b4DragEvent
3638 * @description Fires before the dragEvent.
3639 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3642 * @event invalidDropEvent
3643 * @description Fires when the dragged objects is dropped in a location that contains no drop targets.
3644 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3647 * @event b4DragOutEvent
3648 * @description Fires before the dragOutEvent
3649 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3652 * @event dragOutEvent
3653 * @description Fires when a dragged object is no longer over an object that had the onDragEnter fire.
3654 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3657 * @event dragEnterEvent
3658 * @description Occurs when the dragged object first interacts with another targettable drag and drop object.
3659 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3662 * @event b4DragOverEvent
3663 * @description Fires before the dragOverEvent.
3664 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3667 * @event dragOverEvent
3668 * @description Fires every mousemove event while over a drag and drop object.
3669 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3672 * @event b4DragDropEvent
3673 * @description Fires before the dragDropEvent
3674 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3677 * @event dragDropEvent
3678 * @description Fires when the dragged objects is dropped on another.
3679 * @type YAHOO.util.CustomEvent See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event.
3684 * A DragDrop implementation that does not move, but can be a drop
3685 * target. You would get the same result by simply omitting implementation
3686 * for the event callbacks, but this way we reduce the processing cost of the
3687 * event listener and the callbacks.
3689 * @extends YAHOO.util.DragDrop
3691 * @param {String} id the id of the element that is a drop target
3692 * @param {String} sGroup the group of related DragDrop objects
3693 * @param {object} config an object containing configurable attributes
3694 * Valid properties for DDTarget in addition to those in
3698 YAHOO.util.DDTarget = function(id, sGroup, config) {
3700 this.initTarget(id, sGroup, config);
3704 // YAHOO.util.DDTarget.prototype = new YAHOO.util.DragDrop();
3705 YAHOO.extend(YAHOO.util.DDTarget, YAHOO.util.DragDrop, {
3706 toString: function() {
3707 return ("DDTarget " + this.id);
3710 YAHOO.register("dragdrop", YAHOO.util.DragDropMgr, {version: "2.8.0r4", build: "2449"});