Debian Codegraph @

dijit/Tree.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.filter array.forEach array.map
3 "dojo/aspect",
4 "dojo/cookie", // cookie
5 "dojo/_base/declare", // declare
6 "dojo/Deferred", // Deferred
7 "dojo/promise/all",
8 "dojo/dom", // dom.isDescendant
9 "dojo/dom-class", // domClass.add domClass.remove domClass.replace domClass.toggle
10 "dojo/dom-geometry", // domGeometry.setMarginBox domGeometry.position
11 "dojo/dom-style", // domStyle.set
12 "dojo/errors/create", // createError
13 "dojo/fx", // fxUtils.wipeIn fxUtils.wipeOut
14 "dojo/has",
15 "dojo/_base/kernel", // kernel.deprecated
16 "dojo/keys", // arrows etc.
17 "dojo/_base/lang", // lang.getObject lang.mixin lang.hitch
18 "dojo/on", // on(), on.selector()
19 "dojo/topic",
20 "dojo/touch",
21 "dojo/when",
22 "./a11yclick",
23 "./focus",
24 "./registry", // registry.byNode(), registry.getEnclosingWidget()
25 "./_base/manager", // manager.defaultDuration
26 "./_Widget",
27 "./_TemplatedMixin",
28 "./_Container",
29 "./_Contained",
30 "./_CssStateMixin",
31 "./_KeyNavMixin",
32 "dojo/text!./templates/TreeNode.html",
33 "dojo/text!./templates/Tree.html",
34 "./tree/TreeStoreModel",
35 "./tree/ForestStoreModel",
36 "./tree/_dndSelector",
37 "dojo/query!css2" // needed when on.selector() used with a string for the selector
38 ], function(array, aspect, cookie, declare, Deferred, all,
39 dom, domClass, domGeometry, domStyle, createError, fxUtils, has, kernel, keys, lang, on, topic, touch, when,
40 a11yclick, focus, registry, manager, _Widget, _TemplatedMixin, _Container, _Contained, _CssStateMixin, _KeyNavMixin,
41 treeNodeTemplate, treeTemplate, TreeStoreModel, ForestStoreModel, _dndSelector){
42
43 // module:
44 // dijit/Tree
45
46 function shimmedPromise(/*Deferred|Promise*/ d){
47 // summary:
48 // Return a Promise based on given Deferred or Promise, with back-compat addCallback() and addErrback() shims
49 // added (TODO: remove those back-compat shims, and this method, for 2.0)
50
51 return lang.delegate(d.promise || d, {
52 addCallback: function(callback){
53 this.then(callback);
54 },
55 addErrback: function(errback){
56 this.otherwise(errback);
57 }
58 });
59 }
60
61 var TreeNode = declare("dijit._TreeNode", [_Widget, _TemplatedMixin, _Container, _Contained, _CssStateMixin], {
62 // summary:
63 // Single node within a tree. This class is used internally
64 // by Tree and should not be accessed directly.
65 // tags:
66 // private
67
68 // item: [const] Item
69 // the dojo.data entry this tree represents
70 item: null,
71
72 // isTreeNode: [protected] Boolean
73 // Indicates that this is a TreeNode. Used by `dijit.Tree` only,
74 // should not be accessed directly.
75 isTreeNode: true,
76
77 // label: String
78 // Text of this tree node
79 label: "",
80 _setLabelAttr: function(val){
81 this.labelNode[this.labelType == "html" ? "innerHTML" : "innerText" in this.labelNode ?
82 "innerText" : "textContent"] = val;
83 this._set("label", val);
84 if(has("dojo-bidi")){
85 this.applyTextDir(this.labelNode);
86 }
87 },
88
89 // labelType: [const] String
90 // Specifies how to interpret the label. Can be "html" or "text".
91 labelType: "text",
92
93 // isExpandable: [private] Boolean
94 // This node has children, so show the expando node (+ sign)
95 isExpandable: null,
96
97 // isExpanded: [readonly] Boolean
98 // This node is currently expanded (ie, opened)
99 isExpanded: false,
100
101 // state: [private] String
102 // Dynamic loading-related stuff.
103 // When an empty folder node appears, it is "NotLoaded" first,
104 // then after dojo.data query it becomes "Loading" and, finally "Loaded"
105 state: "NotLoaded",
106
107 templateString: treeNodeTemplate,
108
109 baseClass: "dijitTreeNode",
110
111 // For hover effect for tree node, and focus effect for label
112 cssStateNodes: {
113 rowNode: "dijitTreeRow"
114 },
115
116 // Tooltip is defined in _WidgetBase but we need to handle the mapping to DOM here
117 _setTooltipAttr: {node: "rowNode", type: "attribute", attribute: "title"},
118
119 buildRendering: function(){
120 this.inherited(arguments);
121
122 // set expand icon for leaf
123 this._setExpando();
124
125 // set icon and label class based on item
126 this._updateItemClasses(this.item);
127
128 if(this.isExpandable){
129 this.labelNode.setAttribute("aria-expanded", this.isExpanded);
130 }
131
132 //aria-selected should be false on all selectable elements.
133 this.setSelected(false);
134 },
135
136 _setIndentAttr: function(indent){
137 // summary:
138 // Tell this node how many levels it should be indented
139 // description:
140 // 0 for top level nodes, 1 for their children, 2 for their
141 // grandchildren, etc.
142
143 // Math.max() is to prevent negative padding on hidden root node (when indent == -1)
144 var pixels = (Math.max(indent, 0) * this.tree._nodePixelIndent) + "px";
145
146 domStyle.set(this.domNode, "backgroundPosition", pixels + " 0px"); // TODOC: what is this for???
147 domStyle.set(this.rowNode, this.isLeftToRight() ? "paddingLeft" : "paddingRight", pixels);
148
149 array.forEach(this.getChildren(), function(child){
150 child.set("indent", indent + 1);
151 });
152
153 this._set("indent", indent);
154 },
155
156 markProcessing: function(){
157 // summary:
158 // Visually denote that tree is loading data, etc.
159 // tags:
160 // private
161 this.state = "Loading";
162 this._setExpando(true);
163 },
164
165 unmarkProcessing: function(){
166 // summary:
167 // Clear markup from markProcessing() call
168 // tags:
169 // private
170 this._setExpando(false);
171 },
172
173 _updateItemClasses: function(item){
174 // summary:
175 // Set appropriate CSS classes for icon and label dom node
176 // (used to allow for item updates to change respective CSS)
177 // tags:
178 // private
179 var tree = this.tree, model = tree.model;
180 if(tree._v10Compat && item === model.root){
181 // For back-compat with 1.0, need to use null to specify root item (TODO: remove in 2.0)
182 item = null;
183 }
184 this._applyClassAndStyle(item, "icon", "Icon");
185 this._applyClassAndStyle(item, "label", "Label");
186 this._applyClassAndStyle(item, "row", "Row");
187
188 this.tree._startPaint(true); // signifies paint started and finished (synchronously)
189 },
190
191 _applyClassAndStyle: function(item, lower, upper){
192 // summary:
193 // Set the appropriate CSS classes and styles for labels, icons and rows.
194 //
195 // item:
196 // The data item.
197 //
198 // lower:
199 // The lower case attribute to use, e.g. 'icon', 'label' or 'row'.
200 //
201 // upper:
202 // The upper case attribute to use, e.g. 'Icon', 'Label' or 'Row'.
203 //
204 // tags:
205 // private
206
207 var clsName = "_" + lower + "Class";
208 var nodeName = lower + "Node";
209 var oldCls = this[clsName];
210
211 this[clsName] = this.tree["get" + upper + "Class"](item, this.isExpanded);
212 domClass.replace(this[nodeName], this[clsName] || "", oldCls || "");
213
214 domStyle.set(this[nodeName], this.tree["get" + upper + "Style"](item, this.isExpanded) || {});
215 },
216
217 _updateLayout: function(){
218 // summary:
219 // Set appropriate CSS classes for this.domNode
220 // tags:
221 // private
222
223 // if we are hiding the root node then make every first level child look like a root node
224 var parent = this.getParent(),
225 markAsRoot = !parent || !parent.rowNode || parent.rowNode.style.display == "none";
226 domClass.toggle(this.domNode, "dijitTreeIsRoot", markAsRoot);
227
228 domClass.toggle(this.domNode, "dijitTreeIsLast", !markAsRoot && !this.getNextSibling());
229 },
230
231 _setExpando: function(/*Boolean*/ processing){
232 // summary:
233 // Set the right image for the expando node
234 // tags:
235 // private
236
237 var styles = ["dijitTreeExpandoLoading", "dijitTreeExpandoOpened",
238 "dijitTreeExpandoClosed", "dijitTreeExpandoLeaf"],
239 _a11yStates = ["*", "-", "+", "*"],
240 idx = processing ? 0 : (this.isExpandable ? (this.isExpanded ? 1 : 2) : 3);
241
242 // apply the appropriate class to the expando node
243 domClass.replace(this.expandoNode, styles[idx], styles);
244
245 // provide a non-image based indicator for images-off mode
246 this.expandoNodeText.innerHTML = _a11yStates[idx];
247
248 },
249
250 expand: function(){
251 // summary:
252 // Show my children
253 // returns:
254 // Promise that resolves when expansion is complete
255
256 // If there's already an expand in progress or we are already expanded, just return
257 if(this._expandDeferred){
258 return shimmedPromise(this._expandDeferred); // dojo/promise/Promise
259 }
260
261 // cancel in progress collapse operation
262 if(this._collapseDeferred){
263 this._collapseDeferred.cancel();
264 delete this._collapseDeferred;
265 }
266
267 // All the state information for when a node is expanded, maybe this should be
268 // set when the animation completes instead
269 this.isExpanded = true;
270 this.labelNode.setAttribute("aria-expanded", "true");
271 if(this.tree.showRoot || this !== this.tree.rootNode){
272 this.containerNode.setAttribute("role", "group");
273 }
274 domClass.add(this.contentNode, 'dijitTreeContentExpanded');
275 this._setExpando();
276 this._updateItemClasses(this.item);
277
278 if(this == this.tree.rootNode && this.tree.showRoot){
279 this.tree.domNode.setAttribute("aria-expanded", "true");
280 }
281
282 var wipeIn = fxUtils.wipeIn({
283 node: this.containerNode,
284 duration: manager.defaultDuration
285 });
286
287 // Deferred that fires when expand is complete
288 var def = (this._expandDeferred = new Deferred(function(){
289 // Canceller
290 wipeIn.stop();
291 }));
292
293 aspect.after(wipeIn, "onEnd", function(){
294 def.resolve(true);
295 }, true);
296
297 wipeIn.play();
298
299 return shimmedPromise(def); // dojo/promise/Promise
300 },
301
302 collapse: function(){
303 // summary:
304 // Collapse this node (if it's expanded)
305 // returns:
306 // Promise that resolves when collapse is complete
307
308 if(this._collapseDeferred){
309 // Node is already collapsed, or there's a collapse in progress, just return that Deferred
310 return shimmedPromise(this._collapseDeferred);
311 }
312
313 // cancel in progress expand operation
314 if(this._expandDeferred){
315 this._expandDeferred.cancel();
316 delete this._expandDeferred;
317 }
318
319 this.isExpanded = false;
320 this.labelNode.setAttribute("aria-expanded", "false");
321 if(this == this.tree.rootNode && this.tree.showRoot){
322 this.tree.domNode.setAttribute("aria-expanded", "false");
323 }
324 domClass.remove(this.contentNode, 'dijitTreeContentExpanded');
325 this._setExpando();
326 this._updateItemClasses(this.item);
327
328 var wipeOut = fxUtils.wipeOut({
329 node: this.containerNode,
330 duration: manager.defaultDuration
331 });
332
333 // Deferred that fires when expand is complete
334 var def = (this._collapseDeferred = new Deferred(function(){
335 // Canceller
336 wipeOut.stop();
337 }));
338
339 aspect.after(wipeOut, "onEnd", function(){
340 def.resolve(true);
341 }, true);
342
343 wipeOut.play();
344
345 return shimmedPromise(def); // dojo/promise/Promise
346 },
347
348 // indent: Integer
349 // Levels from this node to the root node
350 indent: 0,
351
352 setChildItems: function(/* Object[] */ items){
353 // summary:
354 // Sets the child items of this node, removing/adding nodes
355 // from current children to match specified items[] array.
356 // Also, if this.persist == true, expands any children that were previously
357 // opened.
358 // returns:
359 // Promise that resolves after all previously opened children
360 // have been expanded again (or fires instantly if there are no such children).
361
362 var tree = this.tree,
363 model = tree.model,
364 defs = []; // list of deferreds that need to fire before I am complete
365
366
367 var focusedChild = tree.focusedChild;
368
369 // Orphan all my existing children.
370 // If items contains some of the same items as before then we will reattach them.
371 // Don't call this.removeChild() because that will collapse the tree etc.
372 var oldChildren = this.getChildren();
373 array.forEach(oldChildren, function(child){
374 _Container.prototype.removeChild.call(this, child);
375 }, this);
376
377 // All the old children of this TreeNode are subject for destruction if
378 // 1) they aren't listed in the new children array (items)
379 // 2) they aren't immediately adopted by another node (DnD)
380 this.defer(function(){
381 array.forEach(oldChildren, function(node){
382 if(!node._destroyed && !node.getParent()){
383 // If node is in selection then remove it.
384 tree.dndController.removeTreeNode(node);
385
386 // Deregister mapping from item id --> this node and its descendants
387 var remove = function remove(node){
388 var id = model.getIdentity(node.item),
389 ary = tree._itemNodesMap[id];
390 if(ary.length == 1){
391 delete tree._itemNodesMap[id];
392 }else{
393 var index = array.indexOf(ary, node);
394 if(index != -1){
395 ary.splice(index, 1);
396 }
397 }
398 array.forEach(node.getChildren(), remove);
399 };
400
401 remove(node);
402
403 // Remove any entries involving this node from cookie tracking expanded nodes
404 if(tree.persist){
405 var destroyedPath = array.map(node.getTreePath(),function(item){
406 return tree.model.getIdentity(item);
407 }).join("/");
408 for(var path in tree._openedNodes){
409 if(path.substr(0, destroyedPath.length) == destroyedPath){
410 delete tree._openedNodes[path];
411 }
412 }
413 tree._saveExpandedNodes();
414 }
415
416 // If we've orphaned the focused node then move focus to the root node
417 if(tree.lastFocusedChild && !dom.isDescendant(tree.lastFocusedChild.domNode, tree.domNode)){
418 delete tree.lastFocusedChild;
419 }
420 if(focusedChild && !dom.isDescendant(focusedChild.domNode, tree.domNode)){
421 tree.focus(); // could alternately focus this node (parent of the deleted node)
422 }
423
424 // And finally we can destroy the node
425 node.destroyRecursive();
426 }
427 });
428
429 });
430
431 this.state = "Loaded";
432
433 if(items && items.length > 0){
434 this.isExpandable = true;
435
436 // Create _TreeNode widget for each specified tree node, unless one already
437 // exists and isn't being used (presumably it's from a DnD move and was recently
438 // released
439 array.forEach(items, function(item){ // MARKER: REUSE NODE
440 var id = model.getIdentity(item),
441 existingNodes = tree._itemNodesMap[id],
442 node;
443 if(existingNodes){
444 for(var i = 0; i < existingNodes.length; i++){
445 if(existingNodes[i] && !existingNodes[i].getParent()){
446 node = existingNodes[i];
447 node.set('indent', this.indent + 1);
448 break;
449 }
450 }
451 }
452 if(!node){
453 node = this.tree._createTreeNode({
454 item: item,
455 tree: tree,
456 isExpandable: model.mayHaveChildren(item),
457 label: tree.getLabel(item),
458 labelType: (tree.model && tree.model.labelType) || "text",
459 tooltip: tree.getTooltip(item),
460 ownerDocument: tree.ownerDocument,
461 dir: tree.dir,
462 lang: tree.lang,
463 textDir: tree.textDir,
464 indent: this.indent + 1
465 });
466 if(existingNodes){
467 existingNodes.push(node);
468 }else{
469 tree._itemNodesMap[id] = [node];
470 }
471 }
472 this.addChild(node);
473
474 // If node was previously opened then open it again now (this may trigger
475 // more data store accesses, recursively)
476 if(this.tree.autoExpand || this.tree._state(node)){
477 defs.push(tree._expandNode(node));
478 }
479 }, this);
480
481 // note that updateLayout() needs to be called on each child after
482 // _all_ the children exist
483 array.forEach(this.getChildren(), function(child){
484 child._updateLayout();
485 });
486 }else{
487 this.isExpandable = false;
488 }
489
490 if(this._setExpando){
491 // change expando to/from dot or + icon, as appropriate
492 this._setExpando(false);
493 }
494
495 // Set leaf icon or folder icon, as appropriate
496 this._updateItemClasses(this.item);
497
498 var def = all(defs);
499 this.tree._startPaint(def); // to reset TreeNode widths after an item is added/removed from the Tree
500 return shimmedPromise(def); // dojo/promise/Promise
501 },
502
503 getTreePath: function(){
504 var node = this;
505 var path = [];
506 while(node && node !== this.tree.rootNode){
507 path.unshift(node.item);
508 node = node.getParent();
509 }
510 path.unshift(this.tree.rootNode.item);
511
512 return path;
513 },
514
515 getIdentity: function(){
516 return this.tree.model.getIdentity(this.item);
517 },
518
519 removeChild: function(/* treeNode */ node){
520 this.inherited(arguments);
521
522 var children = this.getChildren();
523 if(children.length == 0){
524 this.isExpandable = false;
525 this.collapse();
526 }
527
528 array.forEach(children, function(child){
529 child._updateLayout();
530 });
531 },
532
533 makeExpandable: function(){
534 // summary:
535 // if this node wasn't already showing the expando node,
536 // turn it into one and call _setExpando()
537
538 // TODO: hmm this isn't called from anywhere, maybe should remove it for 2.0
539
540 this.isExpandable = true;
541 this._setExpando(false);
542 },
543
544 setSelected: function(/*Boolean*/ selected){
545 // summary:
546 // A Tree has a (single) currently selected node.
547 // Mark that this node is/isn't that currently selected node.
548 // description:
549 // In particular, setting a node as selected involves setting tabIndex
550 // so that when user tabs to the tree, focus will go to that node (only).
551 this.labelNode.setAttribute("aria-selected", selected ? "true" : "false");
552 domClass.toggle(this.rowNode, "dijitTreeRowSelected", selected);
553 },
554
555 focus: function(){
556 focus.focus(this.focusNode);
557 }
558 });
559
560 if(has("dojo-bidi")){
561 TreeNode.extend({
562 _setTextDirAttr: function(textDir){
563 if(textDir && ((this.textDir != textDir) || !this._created)){
564 this._set("textDir", textDir);
565 this.applyTextDir(this.labelNode);
566 array.forEach(this.getChildren(), function(childNode){
567 childNode.set("textDir", textDir);
568 }, this);
569 }
570 }
571 });
572 }
573
574 var Tree = declare("dijit.Tree", [_Widget, _KeyNavMixin, _TemplatedMixin, _CssStateMixin], {
575 // summary:
576 // This widget displays hierarchical data from a store.
577
578 baseClass: "dijitTree",
579
580 // store: [deprecated] String|dojo/data/Store
581 // Deprecated. Use "model" parameter instead.
582 // The store to get data to display in the tree.
583 store: null,
584
585 // model: [const] dijit/tree/model
586 // Interface to read tree data, get notifications of changes to tree data,
587 // and for handling drop operations (i.e drag and drop onto the tree)
588 model: null,
589
590 // query: [deprecated] anything
591 // Deprecated. User should specify query to the model directly instead.
592 // Specifies datastore query to return the root item or top items for the tree.
593 query: null,
594
595 // label: [deprecated] String
596 // Deprecated. Use dijit/tree/ForestStoreModel directly instead.
597 // Used in conjunction with query parameter.
598 // If a query is specified (rather than a root node id), and a label is also specified,
599 // then a fake root node is created and displayed, with this label.
600 label: "",
601
602 // showRoot: [const] Boolean
603 // Should the root node be displayed, or hidden?
604 showRoot: true,
605
606 // childrenAttr: [deprecated] String[]
607 // Deprecated. This information should be specified in the model.
608 // One ore more attributes that holds children of a tree node
609 childrenAttr: ["children"],
610
611 // paths: String[][] or Item[][]
612 // Full paths from rootNode to selected nodes expressed as array of items or array of ids.
613 // Since setting the paths may be asynchronous (because of waiting on dojo.data), set("paths", ...)
614 // returns a Promise to indicate when the set is complete.
615 paths: [],
616
617 // path: String[] or Item[]
618 // Backward compatible singular variant of paths.
619 path: [],
620
621 // selectedItems: [readonly] Item[]
622 // The currently selected items in this tree.
623 // This property can only be set (via set('selectedItems', ...)) when that item is already
624 // visible in the tree. (I.e. the tree has already been expanded to show that node.)
625 // Should generally use `paths` attribute to set the selected items instead.
626 selectedItems: null,
627
628 // selectedItem: [readonly] Item
629 // Backward compatible singular variant of selectedItems.
630 selectedItem: null,
631
632 // openOnClick: Boolean
633 // If true, clicking a folder node's label will open it, rather than calling onClick()
634 openOnClick: false,
635
636 // openOnDblClick: Boolean
637 // If true, double-clicking a folder node's label will open it, rather than calling onDblClick()
638 openOnDblClick: false,
639
640 templateString: treeTemplate,
641
642 // persist: Boolean
643 // Enables/disables use of cookies for state saving.
644 persist: false,
645
646 // autoExpand: Boolean
647 // Fully expand the tree on load. Overrides `persist`.
648 autoExpand: false,
649
650 // dndController: [protected] Function|String
651 // Class to use as as the dnd controller. Specifying this class enables DnD.
652 // Generally you should specify this as dijit/tree/dndSource.
653 // Setting of dijit/tree/_dndSelector handles selection only (no actual DnD).
654 dndController: _dndSelector,
655
656 // parameters to pull off of the tree and pass on to the dndController as its params
657 dndParams: ["onDndDrop", "itemCreator", "onDndCancel", "checkAcceptance", "checkItemAcceptance", "dragThreshold", "betweenThreshold"],
658
659 //declare the above items so they can be pulled from the tree's markup
660
661 // onDndDrop: [protected] Function
662 // Parameter to dndController, see `dijit/tree/dndSource.onDndDrop()`.
663 // Generally this doesn't need to be set.
664 onDndDrop: null,
665
666 itemCreator: null,
667 /*=====
668 itemCreator: function(nodes, target, source){
669 // summary:
670 // Returns objects passed to `Tree.model.newItem()` based on DnD nodes
671 // dropped onto the tree. Developer must override this method to enable
672 // dropping from external sources onto this Tree, unless the Tree.model's items
673 // happen to look like {id: 123, name: "Apple" } with no other attributes.
674 //
675 // For each node in nodes[], which came from source, create a hash of name/value
676 // pairs to be passed to Tree.model.newItem(). Returns array of those hashes.
677 // nodes: DomNode[]
678 // The DOMNodes dragged from the source container
679 // target: DomNode
680 // The target TreeNode.rowNode
681 // source: dojo/dnd/Source
682 // The source container the nodes were dragged from, perhaps another Tree or a plain dojo/dnd/Source
683 // returns: Object[]
684 // Array of name/value hashes for each new item to be added to the Tree, like:
685 // | [
686 // | { id: 123, label: "apple", foo: "bar" },
687 // | { id: 456, label: "pear", zaz: "bam" }
688 // | ]
689 // tags:
690 // extension
691 return [{}];
692 },
693 =====*/
694
695 // onDndCancel: [protected] Function
696 // Parameter to dndController, see `dijit/tree/dndSource.onDndCancel()`.
697 // Generally this doesn't need to be set.
698 onDndCancel: null,
699
700 /*=====
701 checkAcceptance: function(source, nodes){
702 // summary:
703 // Checks if the Tree itself can accept nodes from this source
704 // source: dijit/tree/dndSource
705 // The source which provides items
706 // nodes: DOMNode[]
707 // Array of DOM nodes corresponding to nodes being dropped, dijitTreeRow nodes if
708 // source is a dijit/Tree.
709 // tags:
710 // extension
711 return true; // Boolean
712 },
713 =====*/
714 checkAcceptance: null,
715
716 /*=====
717 checkItemAcceptance: function(target, source, position){
718 // summary:
719 // Stub function to be overridden if one wants to check for the ability to drop at the node/item level
720 // description:
721 // In the base case, this is called to check if target can become a child of source.
722 // When betweenThreshold is set, position="before" or "after" means that we
723 // are asking if the source node can be dropped before/after the target node.
724 // target: DOMNode
725 // The dijitTreeRoot DOM node inside of the TreeNode that we are dropping on to
726 // Use registry.getEnclosingWidget(target) to get the TreeNode.
727 // source: dijit/tree/dndSource
728 // The (set of) nodes we are dropping
729 // position: String
730 // "over", "before", or "after"
731 // tags:
732 // extension
733 return true; // Boolean
734 },
735 =====*/
736 checkItemAcceptance: null,
737
738 // dragThreshold: Integer
739 // Number of pixels mouse moves before it's considered the start of a drag operation
740 dragThreshold: 5,
741
742 // betweenThreshold: Integer
743 // Set to a positive value to allow drag and drop "between" nodes.
744 //
745 // If during DnD mouse is over a (target) node but less than betweenThreshold
746 // pixels from the bottom edge, dropping the the dragged node will make it
747 // the next sibling of the target node, rather than the child.
748 //
749 // Similarly, if mouse is over a target node but less that betweenThreshold
750 // pixels from the top edge, dropping the dragged node will make it
751 // the target node's previous sibling rather than the target node's child.
752 betweenThreshold: 0,
753
754 // _nodePixelIndent: Integer
755 // Number of pixels to indent tree nodes (relative to parent node).
756 // Default is 19 but can be overridden by setting CSS class dijitTreeIndent
757 // and calling resize() or startup() on tree after it's in the DOM.
758 _nodePixelIndent: 19,
759
760 _publish: function(/*String*/ topicName, /*Object*/ message){
761 // summary:
762 // Publish a message for this widget/topic
763 topic.publish(this.id, lang.mixin({tree: this, event: topicName}, message || {})); // publish
764 },
765
766 postMixInProperties: function(){
767 this.tree = this;
768
769 if(this.autoExpand){
770 // There's little point in saving opened/closed state of nodes for a Tree
771 // that initially opens all it's nodes.
772 this.persist = false;
773 }
774
775 this._itemNodesMap = {};
776
777 if(!this.cookieName && this.id){
778 this.cookieName = this.id + "SaveStateCookie";
779 }
780
781 // Deferred that resolves when all the children have loaded.
782 this.expandChildrenDeferred = new Deferred();
783
784 // Promise that resolves when all pending operations complete.
785 this.pendingCommandsPromise = this.expandChildrenDeferred.promise;
786
787 this.inherited(arguments);
788 },
789
790 postCreate: function(){
791 this._initState();
792
793 // Catch events on TreeNodes
794 var self = this;
795 this.own(
796 on(this.containerNode, on.selector(".dijitTreeNode", touch.enter), function(evt){
797 self._onNodeMouseEnter(registry.byNode(this), evt);
798 }),
799 on(this.containerNode, on.selector(".dijitTreeNode", touch.leave), function(evt){
800 self._onNodeMouseLeave(registry.byNode(this), evt);
801 }),
802 on(this.containerNode, on.selector(".dijitTreeRow", a11yclick.press), function(evt){
803 self._onNodePress(registry.getEnclosingWidget(this), evt);
804 }),
805 on(this.containerNode, on.selector(".dijitTreeRow", a11yclick), function(evt){
806 self._onClick(registry.getEnclosingWidget(this), evt);
807 }),
808 on(this.containerNode, on.selector(".dijitTreeRow", "dblclick"), function(evt){
809 self._onDblClick(registry.getEnclosingWidget(this), evt);
810 })
811 );
812
813 // Create glue between store and Tree, if not specified directly by user
814 if(!this.model){
815 this._store2model();
816 }
817
818 // monitor changes to items
819 this.own(
820 aspect.after(this.model, "onChange", lang.hitch(this, "_onItemChange"), true),
821 aspect.after(this.model, "onChildrenChange", lang.hitch(this, "_onItemChildrenChange"), true),
822 aspect.after(this.model, "onDelete", lang.hitch(this, "_onItemDelete"), true)
823 );
824
825 this.inherited(arguments);
826
827 if(this.dndController){
828 // TODO: remove string support in 2.0.
829 if(lang.isString(this.dndController)){
830 this.dndController = lang.getObject(this.dndController);
831 }
832 var params = {};
833 for(var i = 0; i < this.dndParams.length; i++){
834 if(this[this.dndParams[i]]){
835 params[this.dndParams[i]] = this[this.dndParams[i]];
836 }
837 }
838 this.dndController = new this.dndController(this, params);
839 }
840
841 this._load();
842
843 // onLoadDeferred should fire when all commands that are part of initialization have completed.
844 // It will include all the set("paths", ...) commands that happen during initialization.
845 this.onLoadDeferred = shimmedPromise(this.pendingCommandsPromise);
846
847 this.onLoadDeferred.then(lang.hitch(this, "onLoad"));
848 },
849
850 _store2model: function(){
851 // summary:
852 // User specified a store&query rather than model, so create model from store/query
853 this._v10Compat = true;
854 kernel.deprecated("Tree: from version 2.0, should specify a model object rather than a store/query");
855
856 var modelParams = {
857 id: this.id + "_ForestStoreModel",
858 store: this.store,
859 query: this.query,
860 childrenAttrs: this.childrenAttr
861 };
862
863 // Only override the model's mayHaveChildren() method if the user has specified an override
864 if(this.params.mayHaveChildren){
865 modelParams.mayHaveChildren = lang.hitch(this, "mayHaveChildren");
866 }
867
868 if(this.params.getItemChildren){
869 modelParams.getChildren = lang.hitch(this, function(item, onComplete, onError){
870 this.getItemChildren((this._v10Compat && item === this.model.root) ? null : item, onComplete, onError);
871 });
872 }
873 this.model = new ForestStoreModel(modelParams);
874
875 // For backwards compatibility, the visibility of the root node is controlled by
876 // whether or not the user has specified a label
877 this.showRoot = Boolean(this.label);
878 },
879
880 onLoad: function(){
881 // summary:
882 // Called when tree finishes loading and expanding.
883 // description:
884 // If persist == true the loading may encompass many levels of fetches
885 // from the data store, each asynchronous. Waits for all to finish.
886 // tags:
887 // callback
888 },
889
890 _load: function(){
891 // summary:
892 // Initial load of the tree.
893 // Load root node (possibly hidden) and it's children.
894 this.model.getRoot(
895 lang.hitch(this, function(item){
896 var rn = (this.rootNode = this.tree._createTreeNode({
897 item: item,
898 tree: this,
899 isExpandable: true,
900 label: this.label || this.getLabel(item),
901 labelType: this.model.labelType || "text",
902 textDir: this.textDir,
903 indent: this.showRoot ? 0 : -1
904 }));
905
906 if(!this.showRoot){
907 rn.rowNode.style.display = "none";
908 // if root is not visible, move tree role to the invisible
909 // root node's containerNode, see #12135
910 this.domNode.setAttribute("role", "presentation");
911 this.domNode.removeAttribute("aria-expanded");
912 this.domNode.removeAttribute("aria-multiselectable");
913
914 // move the aria-label or aria-labelledby to the element with the role
915 if(this["aria-label"]){
916 rn.containerNode.setAttribute("aria-label", this["aria-label"]);
917 this.domNode.removeAttribute("aria-label");
918 }else if(this["aria-labelledby"]){
919 rn.containerNode.setAttribute("aria-labelledby", this["aria-labelledby"]);
920 this.domNode.removeAttribute("aria-labelledby");
921 }
922 rn.labelNode.setAttribute("role", "presentation");
923 rn.labelNode.removeAttribute("aria-selected");
924 rn.containerNode.setAttribute("role", "tree");
925 rn.containerNode.setAttribute("aria-expanded", "true");
926 rn.containerNode.setAttribute("aria-multiselectable", !this.dndController.singular);
927 }else{
928 this.domNode.setAttribute("aria-multiselectable", !this.dndController.singular);
929 this.rootLoadingIndicator.style.display = "none";
930 }
931
932 this.containerNode.appendChild(rn.domNode);
933 var identity = this.model.getIdentity(item);
934 if(this._itemNodesMap[identity]){
935 this._itemNodesMap[identity].push(rn);
936 }else{
937 this._itemNodesMap[identity] = [rn];
938 }
939
940 rn._updateLayout(); // sets "dijitTreeIsRoot" CSS classname
941
942 // Load top level children, and if persist==true, all nodes that were previously opened
943 this._expandNode(rn).then(lang.hitch(this, function(){
944 // Then, select the nodes specified by params.paths[], assuming Tree hasn't been deleted.
945 if(!this._destroyed){
946 this.rootLoadingIndicator.style.display = "none";
947 this.expandChildrenDeferred.resolve(true);
948 }
949 }));
950 }),
951 lang.hitch(this, function(err){
952 console.error(this, ": error loading root: ", err);
953 })
954 );
955 },
956
957 getNodesByItem: function(/*Item or id*/ item){
958 // summary:
959 // Returns all tree nodes that refer to an item
960 // returns:
961 // Array of tree nodes that refer to passed item
962
963 if(!item){
964 return [];
965 }
966 var identity = lang.isString(item) ? item : this.model.getIdentity(item);
967 // return a copy so widget don't get messed up by changes to returned array
968 return [].concat(this._itemNodesMap[identity]);
969 },
970
971 _setSelectedItemAttr: function(/*Item or id*/ item){
972 this.set('selectedItems', [item]);
973 },
974
975 _setSelectedItemsAttr: function(/*Items or ids*/ items){
976 // summary:
977 // Select tree nodes related to passed items.
978 // WARNING: if model use multi-parented items or desired tree node isn't already loaded
979 // behavior is undefined. Use set('paths', ...) instead.
980 var tree = this;
981 return this.pendingCommandsPromise = this.pendingCommandsPromise.always(lang.hitch(this, function(){
982 var identities = array.map(items, function(item){
983 return (!item || lang.isString(item)) ? item : tree.model.getIdentity(item);
984 });
985 var nodes = [];
986 array.forEach(identities, function(id){
987 nodes = nodes.concat(tree._itemNodesMap[id] || []);
988 });
989 this.set('selectedNodes', nodes);
990 }));
991 },
992
993 _setPathAttr: function(/*Item[]|String[]*/ path){
994 // summary:
995 // Singular variant of _setPathsAttr
996 if(path.length){
997 return shimmedPromise(this.set("paths", [path]).then(function(paths){ return paths[0]; }));
998 }else{
999 // Empty list is interpreted as "select nothing"
1000 return shimmedPromise(this.set("paths", []).then(function(paths){ return paths[0]; }));
1001 }
1002 },
1003
1004 _setPathsAttr: function(/*Item[][]|String[][]*/ paths){
1005 // summary:
1006 // Select the tree nodes identified by passed paths.
1007 // paths:
1008 // Array of arrays of items or item id's
1009 // returns:
1010 // Promise to indicate when the set is complete
1011
1012 var tree = this;
1013
1014 function selectPath(path, nodes){
1015 // Traverse path, returning Promise for node at the end of the path.
1016 // The next path component should be among "nodes".
1017 var nextPath = path.shift();
1018 var nextNode = array.filter(nodes, function(node){
1019 return node.getIdentity() == nextPath;
1020 })[0];
1021 if(!!nextNode){
1022 if(path.length){
1023 return tree._expandNode(nextNode).then(function(){
1024 return selectPath(path, nextNode.getChildren());
1025 });
1026 }else{
1027 // Successfully reached the end of this path
1028 return nextNode;
1029 }
1030 }else{
1031 throw new Tree.PathError("Could not expand path at " + nextPath);
1032 }
1033 }
1034
1035 // Let any previous set("path", ...) commands complete before this one starts.
1036 // TODO for 2.0: make the user do this wait themselves?
1037 return shimmedPromise(this.pendingCommandsPromise = this.pendingCommandsPromise.always(function(){
1038 // We may need to wait for some nodes to expand, so setting
1039 // each path will involve a Deferred. We bring those deferreds
1040 // together with a dojo/promise/all.
1041 return all(array.map(paths, function(path){
1042 // normalize path to use identity
1043 path = array.map(path, function(item){
1044 return item && lang.isObject(item) ? tree.model.getIdentity(item) : item;
1045 });
1046
1047 if(path.length){
1048 return selectPath(path, [tree.rootNode]);
1049 }else{
1050 throw new Tree.PathError("Empty path");
1051 }
1052 }));
1053 }).then(function setNodes(newNodes){
1054 // After all expansion is finished, set the selection to last element from each path
1055 tree.set("selectedNodes", newNodes);
1056 return tree.paths;
1057 }));
1058 },
1059
1060 _setSelectedNodeAttr: function(node){
1061 this.set('selectedNodes', [node]);
1062 },
1063 _setSelectedNodesAttr: function(nodes){
1064 // summary:
1065 // Marks the specified TreeNodes as selected.
1066 // nodes: TreeNode[]
1067 // TreeNodes to mark.
1068 this.dndController.setSelection(nodes);
1069 },
1070
1071
1072 expandAll: function(){
1073 // summary:
1074 // Expand all nodes in the tree
1075 // returns:
1076 // Promise that resolves when all nodes have expanded
1077
1078 var _this = this;
1079
1080 function expand(node){
1081 // Expand the node
1082 return _this._expandNode(node).then(function(){
1083 // When node has expanded, call expand() recursively on each non-leaf child
1084 var childBranches = array.filter(node.getChildren() || [], function(node){
1085 return node.isExpandable;
1086 });
1087
1088 // And when all those recursive calls finish, signal that I'm finished
1089 return all(array.map(childBranches, expand));
1090 });
1091 }
1092
1093 return shimmedPromise(expand(this.rootNode));
1094 },
1095
1096 collapseAll: function(){
1097 // summary:
1098 // Collapse all nodes in the tree
1099 // returns:
1100 // Promise that resolves when all nodes have collapsed
1101
1102 var _this = this;
1103
1104 function collapse(node){
1105 // Collapse children first
1106 var childBranches = array.filter(node.getChildren() || [], function(node){
1107 return node.isExpandable;
1108 }),
1109 defs = all(array.map(childBranches, collapse));
1110
1111 // And when all those recursive calls finish, collapse myself, unless I'm the invisible root node,
1112 // in which case collapseAll() is finished
1113 if(!node.isExpanded || (node == _this.rootNode && !_this.showRoot)){
1114 return defs;
1115 }else{
1116 // When node has collapsed, signal that call is finished
1117 return defs.then(function(){
1118 return _this._collapseNode(node);
1119 });
1120 }
1121 }
1122
1123 return shimmedPromise(collapse(this.rootNode));
1124 },
1125
1126 ////////////// Data store related functions //////////////////////
1127 // These just get passed to the model; they are here for back-compat
1128
1129 mayHaveChildren: function(/*dojo/data/Item*/ /*===== item =====*/){
1130 // summary:
1131 // Deprecated. This should be specified on the model itself.
1132 //
1133 // Overridable function to tell if an item has or may have children.
1134 // Controls whether or not +/- expando icon is shown.
1135 // (For efficiency reasons we may not want to check if an element actually
1136 // has children until user clicks the expando node)
1137 // tags:
1138 // deprecated
1139 },
1140
1141 getItemChildren: function(/*===== parentItem, onComplete =====*/){
1142 // summary:
1143 // Deprecated. This should be specified on the model itself.
1144 //
1145 // Overridable function that return array of child items of given parent item,
1146 // or if parentItem==null then return top items in tree
1147 // tags:
1148 // deprecated
1149 },
1150
1151 ///////////////////////////////////////////////////////
1152 // Functions for converting an item to a TreeNode
1153 getLabel: function(/*dojo/data/Item*/ item){
1154 // summary:
1155 // Overridable function to get the label for a tree node (given the item)
1156 // tags:
1157 // extension
1158 return this.model.getLabel(item); // String
1159 },
1160
1161 getIconClass: function(/*dojo/data/Item*/ item, /*Boolean*/ opened){
1162 // summary:
1163 // Overridable function to return CSS class name to display icon
1164 // tags:
1165 // extension
1166 return (!item || this.model.mayHaveChildren(item)) ? (opened ? "dijitFolderOpened" : "dijitFolderClosed") : "dijitLeaf"
1167 },
1168
1169 getLabelClass: function(/*===== item, opened =====*/){
1170 // summary:
1171 // Overridable function to return CSS class name to display label
1172 // item: dojo/data/Item
1173 // opened: Boolean
1174 // returns: String
1175 // CSS class name
1176 // tags:
1177 // extension
1178 },
1179
1180 getRowClass: function(/*===== item, opened =====*/){
1181 // summary:
1182 // Overridable function to return CSS class name to display row
1183 // item: dojo/data/Item
1184 // opened: Boolean
1185 // returns: String
1186 // CSS class name
1187 // tags:
1188 // extension
1189 },
1190
1191 getIconStyle: function(/*===== item, opened =====*/){
1192 // summary:
1193 // Overridable function to return CSS styles to display icon
1194 // item: dojo/data/Item
1195 // opened: Boolean
1196 // returns: Object
1197 // Object suitable for input to dojo.style() like {backgroundImage: "url(...)"}
1198 // tags:
1199 // extension
1200 },
1201
1202 getLabelStyle: function(/*===== item, opened =====*/){
1203 // summary:
1204 // Overridable function to return CSS styles to display label
1205 // item: dojo/data/Item
1206 // opened: Boolean
1207 // returns:
1208 // Object suitable for input to dojo.style() like {color: "red", background: "green"}
1209 // tags:
1210 // extension
1211 },
1212
1213 getRowStyle: function(/*===== item, opened =====*/){
1214 // summary:
1215 // Overridable function to return CSS styles to display row
1216 // item: dojo/data/Item
1217 // opened: Boolean
1218 // returns:
1219 // Object suitable for input to dojo.style() like {background-color: "#bbb"}
1220 // tags:
1221 // extension
1222 },
1223
1224 getTooltip: function(/*dojo/data/Item*/ /*===== item =====*/){
1225 // summary:
1226 // Overridable function to get the tooltip for a tree node (given the item)
1227 // tags:
1228 // extension
1229 return ""; // String
1230 },
1231
1232 /////////// Keyboard and Mouse handlers ////////////////////
1233
1234
1235 _onDownArrow: function(/*Event*/ evt, /*TreeNode*/ node){
1236 // summary:
1237 // down arrow pressed; get next visible node, set focus there
1238
1239 var nextNode = this._getNext(node);
1240 if(nextNode && nextNode.isTreeNode){
1241 this.focusNode(nextNode);
1242 }
1243 },
1244
1245 _onUpArrow: function(/*Event*/ evt, /*TreeNode*/ node){
1246 // summary:
1247 // Up arrow pressed; move to previous visible node
1248
1249 // if younger siblings
1250 var previousSibling = node.getPreviousSibling();
1251 if(previousSibling){
1252 node = previousSibling;
1253 // if the previous node is expanded, dive in deep
1254 while(node.isExpandable && node.isExpanded && node.hasChildren()){
1255 // move to the last child
1256 var children = node.getChildren();
1257 node = children[children.length - 1];
1258 }
1259 }else{
1260 // if this is the first child, return the parent
1261 // unless the parent is the root of a tree with a hidden root
1262 var parent = node.getParent();
1263 if(!(!this.showRoot && parent === this.rootNode)){
1264 node = parent;
1265 }
1266 }
1267
1268 if(node && node.isTreeNode){
1269 this.focusNode(node);
1270 }
1271 },
1272
1273 _onRightArrow: function(/*Event*/ evt, /*TreeNode*/ node){
1274 // summary:
1275 // Right arrow pressed; go to child node
1276
1277 // if not expanded, expand, else move to 1st child
1278 if(node.isExpandable && !node.isExpanded){
1279 this._expandNode(node);
1280 }else if(node.hasChildren()){
1281 node = node.getChildren()[0];
1282 if(node && node.isTreeNode){
1283 this.focusNode(node);
1284 }
1285 }
1286 },
1287
1288 _onLeftArrow: function(/*Event*/ evt, /*TreeNode*/ node){
1289 // summary:
1290 // Left arrow pressed.
1291 // If not collapsed, collapse, else move to parent.
1292
1293 if(node.isExpandable && node.isExpanded){
1294 this._collapseNode(node);
1295 }else{
1296 var parent = node.getParent();
1297 if(parent && parent.isTreeNode && !(!this.showRoot && parent === this.rootNode)){
1298 this.focusNode(parent);
1299 }
1300 }
1301 },
1302
1303 focusLastChild: function(){
1304 // summary:
1305 // End key pressed; go to last visible node.
1306
1307 var node = this._getLast();
1308 if(node && node.isTreeNode){
1309 this.focusNode(node);
1310 }
1311 },
1312
1313 _getFirst: function(){
1314 // summary:
1315 // Returns the first child.
1316 // tags:
1317 // abstract extension
1318 return this.showRoot ? this.rootNode : this.rootNode.getChildren()[0];
1319 },
1320
1321 _getLast: function(){
1322 // summary:
1323 // Returns the last descendant.
1324 // tags:
1325 // abstract extension
1326 var node = this.rootNode;
1327 while(node.isExpanded){
1328 var c = node.getChildren();
1329 if(!c.length){
1330 break;
1331 }
1332 node = c[c.length - 1];
1333 }
1334 return node;
1335 },
1336
1337 // Tree only searches forward so dir parameter is unused
1338 _getNext: function(node){
1339 // summary:
1340 // Returns the next descendant, compared to "child".
1341 // node: Widget
1342 // The current widget
1343 // tags:
1344 // abstract extension
1345
1346 if(node.isExpandable && node.isExpanded && node.hasChildren()){
1347 // if this is an expanded node, get the first child
1348 return node.getChildren()[0]; // TreeNode
1349 }else{
1350 // find a parent node with a sibling
1351 while(node && node.isTreeNode){
1352 var returnNode = node.getNextSibling();
1353 if(returnNode){
1354 return returnNode; // TreeNode
1355 }
1356 node = node.getParent();
1357 }
1358 return null;
1359 }
1360 },
1361
1362 // Implement _KeyNavContainer.childSelector, to identify which nodes are navigable
1363 childSelector: ".dijitTreeRow",
1364
1365 isExpandoNode: function(node, widget){
1366 // summary:
1367 // check whether a dom node is the expandoNode for a particular TreeNode widget
1368 return dom.isDescendant(node, widget.expandoNode) || dom.isDescendant(node, widget.expandoNodeText);
1369 },
1370
1371 _onNodePress: function(/*TreeNode*/ nodeWidget, /*Event*/ e){
1372 // Touching a node should focus it, even if you touch the expando node or the edges rather than the label.
1373 // Especially important to avoid _KeyNavMixin._onContainerFocus() causing the previously focused TreeNode
1374 // to get focus
1375 this.focusNode(nodeWidget);
1376 },
1377
1378 __click: function(/*TreeNode*/ nodeWidget, /*Event*/ e, /*Boolean*/doOpen, /*String*/func){
1379 var domElement = e.target,
1380 isExpandoClick = this.isExpandoNode(domElement, nodeWidget);
1381
1382 if(nodeWidget.isExpandable && (doOpen || isExpandoClick)){
1383 // expando node was clicked, or label of a folder node was clicked; open it
1384 this._onExpandoClick({node: nodeWidget});
1385 }else{
1386 this._publish("execute", { item: nodeWidget.item, node: nodeWidget, evt: e });
1387 this[func](nodeWidget.item, nodeWidget, e);
1388 this.focusNode(nodeWidget);
1389 }
1390 e.stopPropagation();
1391 e.preventDefault();
1392 },
1393 _onClick: function(/*TreeNode*/ nodeWidget, /*Event*/ e){
1394 // summary:
1395 // Translates click events into commands for the controller to process
1396 this.__click(nodeWidget, e, this.openOnClick, 'onClick');
1397 },
1398 _onDblClick: function(/*TreeNode*/ nodeWidget, /*Event*/ e){
1399 // summary:
1400 // Translates double-click events into commands for the controller to process
1401 this.__click(nodeWidget, e, this.openOnDblClick, 'onDblClick');
1402 },
1403
1404 _onExpandoClick: function(/*Object*/ message){
1405 // summary:
1406 // User clicked the +/- icon; expand or collapse my children.
1407 var node = message.node;
1408
1409 // If we are collapsing, we might be hiding the currently focused node.
1410 // Also, clicking the expando node might have erased focus from the current node.
1411 // For simplicity's sake just focus on the node with the expando.
1412 this.focusNode(node);
1413
1414 if(node.isExpanded){
1415 this._collapseNode(node);
1416 }else{
1417 this._expandNode(node);
1418 }
1419 },
1420
1421 onClick: function(/*===== item, node, evt =====*/){
1422 // summary:
1423 // Callback when a tree node is clicked
1424 // item: Object
1425 // Object from the dojo/store corresponding to this TreeNode
1426 // node: TreeNode
1427 // The TreeNode itself
1428 // evt: Event
1429 // The event
1430 // tags:
1431 // callback
1432 },
1433 onDblClick: function(/*===== item, node, evt =====*/){
1434 // summary:
1435 // Callback when a tree node is double-clicked
1436 // item: Object
1437 // Object from the dojo/store corresponding to this TreeNode
1438 // node: TreeNode
1439 // The TreeNode itself
1440 // evt: Event
1441 // The event
1442 // tags:
1443 // callback
1444 },
1445 onOpen: function(/*===== item, node =====*/){
1446 // summary:
1447 // Callback when a node is opened
1448 // item: dojo/data/Item
1449 // node: TreeNode
1450 // tags:
1451 // callback
1452 },
1453 onClose: function(/*===== item, node =====*/){
1454 // summary:
1455 // Callback when a node is closed
1456 // item: Object
1457 // Object from the dojo/store corresponding to this TreeNode
1458 // node: TreeNode
1459 // The TreeNode itself
1460 // tags:
1461 // callback
1462 },
1463
1464 _getNextNode: function(node){
1465 // summary:
1466 // Get next visible node
1467
1468 kernel.deprecated(this.declaredClass + "::_getNextNode(node) is deprecated. Use _getNext(node) instead.", "", "2.0");
1469 return this._getNext(node);
1470 },
1471
1472 _getRootOrFirstNode: function(){
1473 // summary:
1474 // Get first visible node
1475 kernel.deprecated(this.declaredClass + "::_getRootOrFirstNode() is deprecated. Use _getFirst() instead.", "", "2.0");
1476 return this._getFirst();
1477 },
1478
1479 _collapseNode: function(/*TreeNode*/ node){
1480 // summary:
1481 // Called when the user has requested to collapse the node
1482 // returns:
1483 // Promise that resolves when the node has finished closing
1484
1485 if(node._expandNodeDeferred){
1486 delete node._expandNodeDeferred;
1487 }
1488
1489 if(node.state == "Loading"){
1490 // ignore clicks while we are in the process of loading data
1491 return;
1492 }
1493
1494 if(node.isExpanded){
1495 var ret = node.collapse();
1496
1497 this.onClose(node.item, node);
1498 this._state(node, false);
1499
1500 this._startPaint(ret); // after this finishes, need to reset widths of TreeNodes
1501
1502 return ret;
1503 }
1504 },
1505
1506 _expandNode: function(/*TreeNode*/ node){
1507 // summary:
1508 // Called when the user has requested to expand the node
1509 // returns:
1510 // Promise that resolves when the node is loaded and opened and (if persist=true) all it's descendants
1511 // that were previously opened too
1512
1513 if(node._expandNodeDeferred){
1514 // there's already an expand in progress, or completed, so just return
1515 return node._expandNodeDeferred; // dojo/Deferred
1516 }
1517
1518 var model = this.model,
1519 item = node.item,
1520 _this = this;
1521
1522 // Load data if it's not already loaded
1523 if(!node._loadDeferred){
1524 // need to load all the children before expanding
1525 node.markProcessing();
1526
1527 // Setup deferred to signal when the load and expand are finished.
1528 // Save that deferred in this._expandDeferred as a flag that operation is in progress.
1529 node._loadDeferred = new Deferred();
1530
1531 // Get the children
1532 model.getChildren(
1533 item,
1534 function(items){
1535 node.unmarkProcessing();
1536
1537 // Display the children and also start expanding any children that were previously expanded
1538 // (if this.persist == true). The returned Deferred will fire when those expansions finish.
1539 node.setChildItems(items).then(function(){
1540 node._loadDeferred.resolve(items);
1541 });
1542 },
1543 function(err){
1544 console.error(_this, ": error loading " + node.label + " children: ", err);
1545 node._loadDeferred.reject(err);
1546 }
1547 );
1548 }
1549
1550 // Expand the node after data has loaded
1551 var def = node._loadDeferred.then(lang.hitch(this, function(){
1552 var def2 = node.expand();
1553
1554 // seems like these should delayed until node.expand() completes, but left here for back-compat about
1555 // when this.isOpen flag gets set (ie, at the beginning of the animation)
1556 this.onOpen(node.item, node);
1557 this._state(node, true);
1558
1559 return def2;
1560 }));
1561
1562 this._startPaint(def); // after this finishes, need to reset widths of TreeNodes
1563
1564 return def; // dojo/promise/Promise
1565 },
1566
1567 ////////////////// Miscellaneous functions ////////////////
1568
1569 focusNode: function(/* _tree.Node */ node){
1570 // summary:
1571 // Focus on the specified node (which must be visible)
1572 // tags:
1573 // protected
1574 var tmp = [];
1575 for(var domNode = this.domNode;
1576 domNode && domNode.tagName && domNode.tagName.toUpperCase() !== 'IFRAME';
1577 domNode = domNode.parentNode) {
1578 tmp.push({
1579 domNode: domNode.contentWindow || domNode,
1580 scrollLeft: domNode.scrollLeft || 0,
1581 scrollTop: domNode.scrollTop || 0
1582 });
1583 }
1584 this.focusChild(node);
1585 this.defer(function() {
1586 for (var i = 0, max = tmp.length; i < max; i++) {
1587 tmp[i].domNode.scrollLeft = tmp[i].scrollLeft;
1588 tmp[i].domNode.scrollTop = tmp[i].scrollTop;
1589 }
1590 }, 0);
1591 },
1592
1593 _onNodeMouseEnter: function(/*dijit/_WidgetBase*/ /*===== node =====*/){
1594 // summary:
1595 // Called when mouse is over a node (onmouseenter event),
1596 // this is monitored by the DND code
1597 },
1598
1599 _onNodeMouseLeave: function(/*dijit/_WidgetBase*/ /*===== node =====*/){
1600 // summary:
1601 // Called when mouse leaves a node (onmouseleave event),
1602 // this is monitored by the DND code
1603 },
1604
1605 //////////////// Events from the model //////////////////////////
1606
1607 _onItemChange: function(/*Item*/ item){
1608 // summary:
1609 // Processes notification of a change to an item's scalar values like label
1610 var model = this.model,
1611 identity = model.getIdentity(item),
1612 nodes = this._itemNodesMap[identity];
1613
1614 if(nodes){
1615 var label = this.getLabel(item),
1616 tooltip = this.getTooltip(item);
1617 array.forEach(nodes, function(node){
1618 node.set({
1619 item: item, // theoretically could be new JS Object representing same item
1620 label: label,
1621 tooltip: tooltip
1622 });
1623 node._updateItemClasses(item);
1624 });
1625 }
1626 },
1627
1628 _onItemChildrenChange: function(/*dojo/data/Item*/ parent, /*dojo/data/Item[]*/ newChildrenList){
1629 // summary:
1630 // Processes notification of a change to an item's children
1631 var model = this.model,
1632 identity = model.getIdentity(parent),
1633 parentNodes = this._itemNodesMap[identity];
1634
1635 if(parentNodes){
1636 array.forEach(parentNodes, function(parentNode){
1637 parentNode.setChildItems(newChildrenList);
1638 });
1639 }
1640 },
1641
1642 _onItemDelete: function(/*Item*/ item){
1643 // summary:
1644 // Processes notification of a deletion of an item.
1645 // Not called from new dojo.store interface but there's cleanup code in setChildItems() instead.
1646
1647 var model = this.model,
1648 identity = model.getIdentity(item),
1649 nodes = this._itemNodesMap[identity];
1650
1651 if(nodes){
1652 array.forEach(nodes, function(node){
1653 // Remove node from set of selected nodes (if it's selected)
1654 this.dndController.removeTreeNode(node);
1655
1656 var parent = node.getParent();
1657 if(parent){
1658 // if node has not already been orphaned from a _onSetItem(parent, "children", ..) call...
1659 parent.removeChild(node);
1660 }
1661
1662 // If we've orphaned the focused node then move focus to the root node
1663 if(this.lastFocusedChild && !dom.isDescendant(this.lastFocusedChild.domNode, this.domNode)){
1664 delete this.lastFocusedChild;
1665 }
1666 if(this.focusedChild && !dom.isDescendant(this.focusedChild.domNode, this.domNode)){
1667 this.focus();
1668 }
1669
1670 node.destroyRecursive();
1671 }, this);
1672 delete this._itemNodesMap[identity];
1673 }
1674 },
1675
1676 /////////////// Miscellaneous funcs
1677
1678 _initState: function(){
1679 // summary:
1680 // Load in which nodes should be opened automatically
1681 this._openedNodes = {};
1682 if(this.persist && this.cookieName){
1683 var oreo = cookie(this.cookieName);
1684 if(oreo){
1685 array.forEach(oreo.split(','), function(item){
1686 this._openedNodes[item] = true;
1687 }, this);
1688 }
1689 }
1690 },
1691
1692 _state: function(node, expanded){
1693 // summary:
1694 // Query or set expanded state for an node
1695 if(!this.persist){
1696 return false;
1697 }
1698 var path = array.map(node.getTreePath(),function(item){
1699 return this.model.getIdentity(item);
1700 }, this).join("/");
1701 if(arguments.length === 1){
1702 return this._openedNodes[path];
1703 }else{
1704 if(expanded){
1705 this._openedNodes[path] = true;
1706 }else{
1707 delete this._openedNodes[path];
1708 }
1709 this._saveExpandedNodes();
1710 }
1711 },
1712
1713 _saveExpandedNodes: function(){
1714 if(this.persist && this.cookieName){
1715 var ary = [];
1716 for(var id in this._openedNodes){
1717 ary.push(id);
1718 }
1719 cookie(this.cookieName, ary.join(","), {expires: 365});
1720 }
1721 },
1722
1723 destroy: function(){
1724 if(this._curSearch){
1725 this._curSearch.timer.remove();
1726 delete this._curSearch;
1727 }
1728 if(this.rootNode){
1729 this.rootNode.destroyRecursive();
1730 }
1731 if(this.dndController && !lang.isString(this.dndController)){
1732 this.dndController.destroy();
1733 }
1734 this.rootNode = null;
1735 this.inherited(arguments);
1736 },
1737
1738 destroyRecursive: function(){
1739 // A tree is treated as a leaf, not as a node with children (like a grid),
1740 // but defining destroyRecursive for back-compat.
1741 this.destroy();
1742 },
1743
1744 resize: function(changeSize){
1745 if(changeSize){
1746 domGeometry.setMarginBox(this.domNode, changeSize);
1747 }
1748
1749 // The main JS sizing involved w/tree is the indentation, which is specified
1750 // in CSS and read in through this dummy indentDetector node (tree must be
1751 // visible and attached to the DOM to read this).
1752 // If the Tree is hidden domGeometry.position(this.tree.indentDetector).w will return 0, in which case just
1753 // keep the default value.
1754 this._nodePixelIndent = domGeometry.position(this.tree.indentDetector).w || this._nodePixelIndent;
1755
1756 // resize() may be called before this.rootNode is created, so wait until it's available
1757 this.expandChildrenDeferred.then(lang.hitch(this, function(){
1758 // If tree has already loaded, then reset indent for all the nodes
1759 this.rootNode.set('indent', this.showRoot ? 0 : -1);
1760
1761 // Also, adjust widths of all rows to match width of Tree
1762 this._adjustWidths();
1763 }));
1764 },
1765
1766 _outstandingPaintOperations: 0,
1767 _startPaint: function(/*Promise|Boolean*/ p){
1768 // summary:
1769 // Called at the start of an operation that will change what's displayed.
1770 // p:
1771 // Promise that tells when the operation will complete. Alternately, if it's just a Boolean, it signifies
1772 // that the operation was synchronous, and already completed.
1773
1774 this._outstandingPaintOperations++;
1775 if(this._adjustWidthsTimer){
1776 this._adjustWidthsTimer.remove();
1777 delete this._adjustWidthsTimer;
1778 }
1779
1780 var oc = lang.hitch(this, function(){
1781 this._outstandingPaintOperations--;
1782
1783 if(this._outstandingPaintOperations <= 0 && !this._adjustWidthsTimer && this._started){
1784 // Use defer() to avoid a width adjustment when another operation will immediately follow,
1785 // such as a sequence of opening a node, then it's children, then it's grandchildren, etc.
1786 this._adjustWidthsTimer = this.defer("_adjustWidths");
1787 }
1788 });
1789 when(p, oc, oc);
1790 },
1791
1792 _adjustWidths: function(){
1793 // summary:
1794 // Size container to match widest TreeNode, so that highlighting with scrolling works (#13141, #16132)
1795
1796 if(this._adjustWidthsTimer){
1797 this._adjustWidthsTimer.remove();
1798 delete this._adjustWidthsTimer;
1799 }
1800
1801 this.containerNode.style.width = "auto";
1802 this.containerNode.style.width = this.domNode.scrollWidth > this.domNode.offsetWidth ? "auto" : "100%";
1803 },
1804
1805 _createTreeNode: function(/*Object*/ args){
1806 // summary:
1807 // creates a TreeNode
1808 // description:
1809 // Developers can override this method to define their own TreeNode class;
1810 // However it will probably be removed in a future release in favor of a way
1811 // of just specifying a widget for the label, rather than one that contains
1812 // the children too.
1813 return new TreeNode(args);
1814 },
1815
1816 focus: function(){
1817 // summary:
1818 // Default focus() implementation: focus the previously focused child, or first child.
1819 // Some applications may want to change this method to focus the [first] selected child.
1820
1821 if(this.lastFocusedChild){
1822 this.focusNode(this.lastFocusedChild);
1823 }else{
1824 this.focusFirstChild();
1825 }
1826 }
1827 });
1828
1829 if(has("dojo-bidi")){
1830 Tree.extend({
1831 _setTextDirAttr: function(textDir){
1832 if(textDir && this.textDir != textDir){
1833 this._set("textDir", textDir);
1834 this.rootNode.set("textDir", textDir);
1835 }
1836 }
1837 });
1838 }
1839
1840 Tree.PathError = createError("TreePathError");
1841 Tree._TreeNode = TreeNode; // for monkey patching or creating subclasses of TreeNode
1842
1843 return Tree;
1844 });