Debian Codegraph @

dijit/tree/dndSource.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.forEach array.indexOf array.map
3 "dojo/_base/declare", // declare
4 "dojo/dnd/common",
5 "dojo/dom-class", // domClass.add
6 "dojo/dom-geometry", // domGeometry.position
7 "dojo/_base/lang", // lang.mixin lang.hitch
8 "dojo/mouse",
9 "dojo/on", // subscribe
10 "dojo/touch",
11 "dojo/topic",
12 "dojo/dnd/Manager", // DNDManager.manager
13 "./_dndSelector"
14 ], function(array, declare, dndCommon, domClass, domGeometry, lang, mouse, on, touch, topic, DNDManager, _dndSelector){
15
16 // module:
17 // dijit/tree/dndSource
18
19 /*=====
20 var __Item = {
21 // summary:
22 // New item to be added to the Tree, like:
23 // id: Anything
24 id: "",
25 // name: String
26 name: ""
27 };
28 =====*/
29
30 var dndSource = declare("dijit.tree.dndSource", _dndSelector, {
31 // summary:
32 // Handles drag and drop operations (as a source or a target) for `dijit.Tree`
33
34 // isSource: Boolean
35 // Can be used as a DnD source.
36 isSource: true,
37
38 // accept: String[]
39 // List of accepted types (text strings) for the Tree; defaults to
40 // ["text"]
41 accept: ["text", "treeNode"],
42
43 // copyOnly: [private] Boolean
44 // Copy items, if true, use a state of Ctrl key otherwise
45 copyOnly: false,
46
47 // dragThreshold: Number
48 // The move delay in pixels before detecting a drag; 5 by default
49 dragThreshold: 5,
50
51 // betweenThreshold: Integer
52 // Distance from upper/lower edge of node to allow drop to reorder nodes
53 betweenThreshold: 0,
54
55 // Flag used by Avatar.js to signal to generate text node when dragging
56 generateText: true,
57
58 constructor: function(/*dijit/Tree*/ tree, /*dijit/tree/dndSource*/ params){
59 // summary:
60 // a constructor of the Tree DnD Source
61 // tags:
62 // private
63 if(!params){
64 params = {};
65 }
66 lang.mixin(this, params);
67 var type = params.accept instanceof Array ? params.accept : ["text", "treeNode"];
68 this.accept = null;
69 if(type.length){
70 this.accept = {};
71 for(var i = 0; i < type.length; ++i){
72 this.accept[type[i]] = 1;
73 }
74 }
75
76 // class-specific variables
77 this.isDragging = false;
78 this.mouseDown = false;
79 this.targetAnchor = null; // DOMNode corresponding to the currently moused over TreeNode
80 this.targetBox = null; // coordinates of this.targetAnchor
81 this.dropPosition = ""; // whether mouse is over/after/before this.targetAnchor
82 this._lastX = 0;
83 this._lastY = 0;
84
85 // states
86 this.sourceState = "";
87 if(this.isSource){
88 domClass.add(this.node, "dojoDndSource");
89 }
90 this.targetState = "";
91 if(this.accept){
92 domClass.add(this.node, "dojoDndTarget");
93 }
94
95 // set up events
96 this.topics = [
97 topic.subscribe("/dnd/source/over", lang.hitch(this, "onDndSourceOver")),
98 topic.subscribe("/dnd/start", lang.hitch(this, "onDndStart")),
99 topic.subscribe("/dnd/drop", lang.hitch(this, "onDndDrop")),
100 topic.subscribe("/dnd/cancel", lang.hitch(this, "onDndCancel"))
101 ];
102 },
103
104 // methods
105 checkAcceptance: function(/*===== source, nodes =====*/){
106 // summary:
107 // Checks if the target can accept nodes from this source
108 // source: dijit/tree/dndSource
109 // The source which provides items
110 // nodes: DOMNode[]
111 // Array of DOM nodes corresponding to nodes being dropped, dijitTreeRow nodes if
112 // source is a dijit/Tree.
113 // tags:
114 // extension
115 return true; // Boolean
116 },
117
118 copyState: function(keyPressed){
119 // summary:
120 // Returns true, if we need to copy items, false to move.
121 // It is separated to be overwritten dynamically, if needed.
122 // keyPressed: Boolean
123 // The "copy" control key was pressed
124 // tags:
125 // protected
126 return this.copyOnly || keyPressed; // Boolean
127 },
128 destroy: function(){
129 // summary:
130 // Prepares the object to be garbage-collected.
131 this.inherited(arguments);
132 var h;
133 while(h = this.topics.pop()){
134 h.remove();
135 }
136 this.targetAnchor = null;
137 },
138
139 _onDragMouse: function(e, firstTime){
140 // summary:
141 // Helper method for processing onmousemove/onmouseover events while drag is in progress.
142 // Keeps track of current drop target.
143 // e: Event
144 // The mousemove event.
145 // firstTime: Boolean?
146 // If this flag is set, this is the first mouse move event of the drag, so call m.canDrop() etc.
147 // even if newTarget == null because the user quickly dragged a node in the Tree to a position
148 // over Tree.containerNode but not over any TreeNode (#7971)
149
150 var m = DNDManager.manager(),
151 oldTarget = this.targetAnchor, // the TreeNode corresponding to TreeNode mouse was previously over
152 newTarget = this.current, // TreeNode corresponding to TreeNode mouse is currently over
153 oldDropPosition = this.dropPosition; // the previous drop position (over/before/after)
154
155 // calculate if user is indicating to drop the dragged node before, after, or over
156 // (i.e., to become a child of) the target node
157 var newDropPosition = "Over";
158 if(newTarget && this.betweenThreshold > 0){
159 // If mouse is over a new TreeNode, then get new TreeNode's position and size
160 if(!this.targetBox || oldTarget != newTarget){
161 this.targetBox = domGeometry.position(newTarget.rowNode, true);
162 }
163 if((e.pageY - this.targetBox.y) <= this.betweenThreshold){
164 newDropPosition = "Before";
165 }else if((e.pageY - this.targetBox.y) >= (this.targetBox.h - this.betweenThreshold)){
166 newDropPosition = "After";
167 }
168 }
169
170 if(firstTime || newTarget != oldTarget || newDropPosition != oldDropPosition){
171 if(oldTarget){
172 this._removeItemClass(oldTarget.rowNode, oldDropPosition);
173 }
174 if(newTarget){
175 this._addItemClass(newTarget.rowNode, newDropPosition);
176 }
177
178 // Check if it's ok to drop the dragged node on/before/after the target node.
179 if(!newTarget){
180 m.canDrop(false);
181 }else if(newTarget == this.tree.rootNode && newDropPosition != "Over"){
182 // Can't drop before or after tree's root node; the dropped node would just disappear (at least visually)
183 m.canDrop(false);
184 }else{
185 // Guard against dropping onto yourself or your parent.
186 // But when dragging multiple objects, it's OK if some of them are being dropped onto own parent.
187 var dropOntoSelf = false,
188 dropOntoParent = false;
189 if(m.source == this){
190 dropOntoParent = (newDropPosition === "Over");
191 for(var dragId in this.selection){
192 var dragNode = this.selection[dragId];
193 if(dragNode.item === newTarget.item){
194 dropOntoSelf = true;
195 break;
196 }
197 if(dragNode.getParent().id !== newTarget.id){
198 dropOntoParent = false;
199 }
200 }
201 }
202 m.canDrop(
203 !dropOntoSelf && !dropOntoParent &&
204 !this._isParentChildDrop(m.source, newTarget.rowNode) &&
205 this.checkItemAcceptance(newTarget.rowNode, m.source, newDropPosition.toLowerCase())
206 );
207 }
208
209 this.targetAnchor = newTarget;
210 this.dropPosition = newDropPosition;
211 }
212 },
213
214 onMouseMove: function(e){
215 // summary:
216 // Called for any onmousemove/ontouchmove events over the Tree
217 // e: Event
218 // onmousemouse/ontouchmove event
219 // tags:
220 // private
221 if(this.isDragging && this.targetState == "Disabled"){
222 return;
223 }
224 this.inherited(arguments);
225 var m = DNDManager.manager();
226 if(this.isDragging){
227 this._onDragMouse(e);
228 }else{
229 if(this.mouseDown && this.isSource &&
230 (Math.abs(e.pageX - this._lastX) >= this.dragThreshold || Math.abs(e.pageY - this._lastY) >= this.dragThreshold)){
231 var nodes = this.getSelectedTreeNodes();
232 if(nodes.length){
233 if(nodes.length > 1){
234 //filter out all selected items which has one of their ancestor selected as well
235 var seen = this.selection, i = 0, r = [], n, p;
236 nextitem: while((n = nodes[i++])){
237 for(p = n.getParent(); p && p !== this.tree; p = p.getParent()){
238 if(seen[p.id]){ //parent is already selected, skip this node
239 continue nextitem;
240 }
241 }
242 //this node does not have any ancestors selected, add it
243 r.push(n);
244 }
245 nodes = r;
246 }
247 nodes = array.map(nodes, function(n){
248 return n.domNode
249 });
250 m.startDrag(this, nodes, this.copyState(dndCommon.getCopyKeyState(e)));
251 this._onDragMouse(e, true); // because this may be the only mousemove event we get before the drop
252 }
253 }
254 }
255 },
256
257 onMouseDown: function(e){
258 // summary:
259 // Event processor for onmousedown/ontouchstart
260 // e: Event
261 // onmousedown/ontouchend event
262 // tags:
263 // private
264
265 if(e.type == "touchstart" || mouse.isLeft(e)){ // ignore right click
266 this.mouseDown = true;
267 this.mouseButton = e.button;
268 this._lastX = e.pageX;
269 this._lastY = e.pageY;
270 }
271
272 this.inherited(arguments);
273 },
274
275 onMouseUp: function(e){
276 // summary:
277 // Event processor for onmouseup/ontouchend
278 // e: Event
279 // onmouseup/ontouchend event
280 // tags:
281 // private
282 if(this.mouseDown){
283 this.mouseDown = false;
284 this.inherited(arguments);
285 }
286 },
287
288 onMouseOut: function(){
289 // summary:
290 // Event processor for when mouse is moved away from a TreeNode
291 // tags:
292 // private
293 this.inherited(arguments);
294 this._unmarkTargetAnchor();
295 },
296
297 checkItemAcceptance: function(/*===== target, source, position =====*/){
298 // summary:
299 // Stub function to be overridden if one wants to check for the ability to drop at the node/item level
300 // description:
301 // In the base case, this is called to check if target can become a child of source.
302 // When betweenThreshold is set, position="before" or "after" means that we
303 // are asking if the source node can be dropped before/after the target node.
304 // target: DOMNode
305 // The dijitTreeRoot DOM node inside of the TreeNode that we are dropping on to
306 // Use dijit.getEnclosingWidget(target) to get the TreeNode.
307 // source: dijit/tree/dndSource
308 // The (set of) nodes we are dropping
309 // position: String
310 // "over", "before", or "after"
311 // tags:
312 // extension
313 return true;
314 },
315
316 // topic event processors
317 onDndSourceOver: function(source){
318 // summary:
319 // Topic event processor for /dnd/source/over, called when detected a current source.
320 // source: Object
321 // The dijit/tree/dndSource / dojo/dnd/Source which has the mouse over it
322 // tags:
323 // private
324 if(this != source){
325 this.mouseDown = false;
326 this._unmarkTargetAnchor();
327 }else if(this.isDragging){
328 var m = DNDManager.manager();
329 m.canDrop(false);
330 }
331 },
332 onDndStart: function(source, nodes, copy){
333 // summary:
334 // Topic event processor for /dnd/start, called to initiate the DnD operation
335 // source: Object
336 // The dijit/tree/dndSource / dojo/dnd/Source which is providing the items
337 // nodes: DomNode[]
338 // The list of transferred items, dndTreeNode nodes if dragging from a Tree
339 // copy: Boolean
340 // Copy items, if true, move items otherwise
341 // tags:
342 // private
343
344 if(this.isSource){
345 this._changeState("Source", this == source ? (copy ? "Copied" : "Moved") : "");
346 }
347 var accepted = this.checkAcceptance(source, nodes);
348
349 this._changeState("Target", accepted ? "" : "Disabled");
350
351 if(this == source){
352 DNDManager.manager().overSource(this);
353 }
354
355 this.isDragging = true;
356 },
357
358 itemCreator: function(nodes /*===== , target, source =====*/){
359 // summary:
360 // Returns objects passed to `Tree.model.newItem()` based on DnD nodes
361 // dropped onto the tree. Developer must override this method to enable
362 // dropping from external sources onto this Tree, unless the Tree.model's items
363 // happen to look like {id: 123, name: "Apple" } with no other attributes.
364 // description:
365 // For each node in nodes[], which came from source, create a hash of name/value
366 // pairs to be passed to Tree.model.newItem(). Returns array of those hashes.
367 // nodes: DomNode[]
368 // target: DomNode
369 // source: dojo/dnd/Source
370 // returns: __Item[]
371 // Array of name/value hashes for each new item to be added to the Tree
372 // tags:
373 // extension
374
375 // TODO: for 2.0 refactor so itemCreator() is called once per drag node, and
376 // make signature itemCreator(sourceItem, node, target) (or similar).
377
378 return array.map(nodes, function(node){
379 return {
380 "id": node.id,
381 "name": node.textContent || node.innerText || ""
382 };
383 }); // Object[]
384 },
385
386 onDndDrop: function(source, nodes, copy){
387 // summary:
388 // Topic event processor for /dnd/drop, called to finish the DnD operation.
389 // description:
390 // Updates data store items according to where node was dragged from and dropped
391 // to. The tree will then respond to those data store updates and redraw itself.
392 // source: Object
393 // The dijit/tree/dndSource / dojo/dnd/Source which is providing the items
394 // nodes: DomNode[]
395 // The list of transferred items, dndTreeNode nodes if dragging from a Tree
396 // copy: Boolean
397 // Copy items, if true, move items otherwise
398 // tags:
399 // protected
400 if(this.containerState == "Over"){
401 var tree = this.tree,
402 model = tree.model,
403 target = this.targetAnchor,
404 doExpand = false; // this is so we don't expand the sibling above
405
406 this.isDragging = false;
407
408 // Compute the new parent item
409 var newParentItem;
410 var insertIndex;
411 var before; // drop source before (aka previous sibling) of target
412 newParentItem = (target && target.item) || tree.item;
413 if(this.dropPosition == "Before" || this.dropPosition == "After"){
414 // TODO: if there is no parent item then disallow the drop.
415 // Actually this should be checked during onMouseMove too, to make the drag icon red.
416 newParentItem = (target.getParent() && target.getParent().item) || tree.item;
417 // Compute the insert index for reordering
418 insertIndex = target.getIndexInParent();
419 if(this.dropPosition == "After"){
420 insertIndex = target.getIndexInParent() + 1;
421 before = target.getNextSibling() && target.getNextSibling().item;
422 }else{
423 before = target.item;
424 }
425 }else{
426 newParentItem = (target && target.item) || tree.item;
427 doExpand = true;
428 }
429
430 // If necessary, use this variable to hold array of hashes to pass to model.newItem()
431 // (one entry in the array for each dragged node).
432 var newItemsParams;
433
434 array.forEach(nodes, function(node, idx){
435 // dojo/dnd/Item representing the thing being dropped.
436 // Don't confuse the use of item here (meaning a DnD item) with the
437 // uses below where item means dojo.data item.
438 var sourceItem = source.getItem(node.id);
439
440 // Information that's available if the source is another Tree
441 // (possibly but not necessarily this tree, possibly but not
442 // necessarily the same model as this Tree)
443 if(array.indexOf(sourceItem.type, "treeNode") != -1){
444 var childTreeNode = sourceItem.data,
445 childItem = childTreeNode.item,
446 oldParentItem = childTreeNode.getParent().item;
447 }
448
449 if(source == this){
450 // This is a node from my own tree, and we are moving it, not copying.
451 // Remove item from old parent's children attribute.
452 // TODO: dijit/tree/dndSelector should implement deleteSelectedNodes()
453 // and this code should go there.
454
455 if(typeof insertIndex == "number"){
456 if(newParentItem == oldParentItem && childTreeNode.getIndexInParent() < insertIndex){
457 insertIndex -= 1;
458 }
459 }
460 model.pasteItem(childItem, oldParentItem, newParentItem, copy, insertIndex, before);
461 }else if(model.isItem(childItem)){
462 // Item from same model
463 // (maybe we should only do this branch if the source is a tree?)
464 model.pasteItem(childItem, oldParentItem, newParentItem, copy, insertIndex, before);
465 }else{
466 // Get the hash to pass to model.newItem(). A single call to
467 // itemCreator() returns an array of hashes, one for each drag source node.
468 if(!newItemsParams){
469 newItemsParams = this.itemCreator(nodes, target.rowNode, source);
470 }
471
472 // Create new item in the tree, based on the drag source.
473 model.newItem(newItemsParams[idx], newParentItem, insertIndex, before);
474 }
475 }, this);
476
477 // Expand the target node (if it's currently collapsed) so the user can see
478 // where their node was dropped. In particular since that node is still selected.
479 if(doExpand) {
480 this.tree._expandNode(target);
481 }
482 }
483 this.onDndCancel();
484 },
485
486 onDndCancel: function(){
487 // summary:
488 // Topic event processor for /dnd/cancel, called to cancel the DnD operation
489 // tags:
490 // private
491 this._unmarkTargetAnchor();
492 this.isDragging = false;
493 this.mouseDown = false;
494 delete this.mouseButton;
495 this._changeState("Source", "");
496 this._changeState("Target", "");
497 },
498
499 // When focus moves in/out of the entire Tree
500 onOverEvent: function(){
501 // summary:
502 // This method is called when mouse is moved over our container (like onmouseenter)
503 // tags:
504 // private
505 this.inherited(arguments);
506 DNDManager.manager().overSource(this);
507 },
508 onOutEvent: function(){
509 // summary:
510 // This method is called when mouse is moved out of our container (like onmouseleave)
511 // tags:
512 // private
513 this._unmarkTargetAnchor();
514 var m = DNDManager.manager();
515 if(this.isDragging){
516 m.canDrop(false);
517 }
518 m.outSource(this);
519
520 this.inherited(arguments);
521 },
522
523 _isParentChildDrop: function(source, targetRow){
524 // summary:
525 // Checks whether the dragged items are parent rows in the tree which are being
526 // dragged into their own children.
527 //
528 // source:
529 // The DragSource object.
530 //
531 // targetRow:
532 // The tree row onto which the dragged nodes are being dropped.
533 //
534 // tags:
535 // private
536
537 // If the dragged object is not coming from the tree this widget belongs to,
538 // it cannot be invalid.
539 if(!source.tree || source.tree != this.tree){
540 return false;
541 }
542
543
544 var root = source.tree.domNode;
545 var ids = source.selection;
546
547 var node = targetRow.parentNode;
548
549 // Iterate up the DOM hierarchy from the target drop row,
550 // checking of any of the dragged nodes have the same ID.
551 while(node != root && !ids[node.id]){
552 node = node.parentNode;
553 }
554
555 return node.id && ids[node.id];
556 },
557
558 _unmarkTargetAnchor: function(){
559 // summary:
560 // Removes hover class of the current target anchor
561 // tags:
562 // private
563 if(!this.targetAnchor){
564 return;
565 }
566 this._removeItemClass(this.targetAnchor.rowNode, this.dropPosition);
567 this.targetAnchor = null;
568 this.targetBox = null;
569 this.dropPosition = null;
570 },
571
572 _markDndStatus: function(copy){
573 // summary:
574 // Changes source's state based on "copy" status
575 this._changeState("Source", copy ? "Copied" : "Moved");
576 }
577 });
578
579 /*=====
580 dndSource.__Item = __Item;
581 =====*/
582
583 return dndSource;
584 });