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 var Dom = YAHOO.util.Dom,
9 Event = YAHOO.util.Event,
11 Widget = YAHOO.widget;
16 * The treeview widget is a generic tree building tool.
18 * @title TreeView Widget
19 * @requires yahoo, event
20 * @optional animation, json
21 * @namespace YAHOO.widget
25 * Contains the tree view state data and the root node.
28 * @uses YAHOO.util.EventProvider
30 * @param {string|HTMLElement} id The id of the element, or the element itself that the tree will be inserted into. Existing markup in this element, if valid, will be used to build the tree
31 * @param {Array|object|string} oConfig (optional) An array containing the definition of the tree. (see buildTreeFromObject)
34 YAHOO.widget.TreeView = function(id, oConfig) {
35 if (id) { this.init(id); }
37 if (!Lang.isArray(oConfig)) {
40 this.buildTreeFromObject(oConfig);
41 } else if (Lang.trim(this._el.innerHTML)) {
42 this.buildTreeFromMarkup(id);
46 var TV = Widget.TreeView;
51 * The id of tree container element
58 * The host element for this tree
66 * Flat collection of all nodes in this tree. This is a sparse
67 * array, so the length property can't be relied upon for a
68 * node count for the tree.
76 * We lock the tree control while waiting for the dynamic loader to return
83 * The animation to use for expanding children, if any
84 * @property _expandAnim
91 * The animation to use for collapsing children, if any
92 * @property _collapseAnim
99 * The current number of animations that are executing
100 * @property _animCount
107 * The maximum number of animations to run at one time.
114 * Whether there is any subscriber to dblClickEvent
115 * @property _hasDblClickSubscriber
119 _hasDblClickSubscriber: false,
122 * Stores the timer used to check for double clicks
123 * @property _dblClickTimer
124 * @type window.timer object
127 _dblClickTimer: null,
130 * A reference to the Node currently having the focus or null if none.
131 * @property currentFocus
132 * @type YAHOO.widget.Node
137 * If true, only one Node can be highlighted at a time
138 * @property singleNodeHighlight
143 singleNodeHighlight: false,
146 * A reference to the Node that is currently highlighted.
147 * It is only meaningful if singleNodeHighlight is enabled
148 * @property _currentlyHighlighted
149 * @type YAHOO.widget.Node
154 _currentlyHighlighted: null,
157 * Sets up the animation for expanding children
158 * @method setExpandAnim
159 * @param {string} type the type of animation (acceptable values defined
160 * in YAHOO.widget.TVAnim)
162 setExpandAnim: function(type) {
163 this._expandAnim = (Widget.TVAnim.isValid(type)) ? type : null;
167 * Sets up the animation for collapsing children
168 * @method setCollapseAnim
169 * @param {string} the type of animation (acceptable values defined in
170 * YAHOO.widget.TVAnim)
172 setCollapseAnim: function(type) {
173 this._collapseAnim = (Widget.TVAnim.isValid(type)) ? type : null;
177 * Perform the expand animation if configured, or just show the
178 * element if not configured or too many animations are in progress
179 * @method animateExpand
180 * @param el {HTMLElement} the element to animate
181 * @param node {YAHOO.util.Node} the node that was expanded
182 * @return {boolean} true if animation could be invoked, false otherwise
184 animateExpand: function(el, node) {
186 if (this._expandAnim && this._animCount < this.maxAnim) {
187 // this.locked = true;
189 var a = Widget.TVAnim.getAnim(this._expandAnim, el,
190 function() { tree.expandComplete(node); });
193 this.fireEvent("animStart", {
207 * Perform the collapse animation if configured, or just show the
208 * element if not configured or too many animations are in progress
209 * @method animateCollapse
210 * @param el {HTMLElement} the element to animate
211 * @param node {YAHOO.util.Node} the node that was expanded
212 * @return {boolean} true if animation could be invoked, false otherwise
214 animateCollapse: function(el, node) {
216 if (this._collapseAnim && this._animCount < this.maxAnim) {
217 // this.locked = true;
219 var a = Widget.TVAnim.getAnim(this._collapseAnim, el,
220 function() { tree.collapseComplete(node); });
223 this.fireEvent("animStart", {
237 * Function executed when the expand animation completes
238 * @method expandComplete
240 expandComplete: function(node) {
242 this.fireEvent("animComplete", {
246 // this.locked = false;
250 * Function executed when the collapse animation completes
251 * @method collapseComplete
253 collapseComplete: function(node) {
255 this.fireEvent("animComplete", {
259 // this.locked = false;
263 * Initializes the tree
265 * @parm {string|HTMLElement} id the id of the element that will hold the tree
269 this._el = Dom.get(id);
270 this.id = Dom.generateId(this._el,"yui-tv-auto-id-");
273 * When animation is enabled, this event fires when the animation
277 * @param {YAHOO.widget.Node} node the node that is expanding/collapsing
278 * @parm {String} type the type of animation ("expand" or "collapse")
280 this.createEvent("animStart", this);
283 * When animation is enabled, this event fires when the animation
285 * @event animComplete
287 * @param {YAHOO.widget.Node} node the node that is expanding/collapsing
288 * @parm {String} type the type of animation ("expand" or "collapse")
290 this.createEvent("animComplete", this);
293 * Fires when a node is going to be collapsed. Return false to stop
297 * @param {YAHOO.widget.Node} node the node that is collapsing
299 this.createEvent("collapse", this);
302 * Fires after a node is successfully collapsed. This event will not fire
303 * if the "collapse" event was cancelled.
304 * @event collapseComplete
306 * @param {YAHOO.widget.Node} node the node that was collapsed
308 this.createEvent("collapseComplete", this);
311 * Fires when a node is going to be expanded. Return false to stop
315 * @param {YAHOO.widget.Node} node the node that is expanding
317 this.createEvent("expand", this);
320 * Fires after a node is successfully expanded. This event will not fire
321 * if the "expand" event was cancelled.
322 * @event expandComplete
324 * @param {YAHOO.widget.Node} node the node that was expanded
326 this.createEvent("expandComplete", this);
329 * Fires when the Enter key is pressed on a node that has the focus
330 * @event enterKeyPressed
332 * @param {YAHOO.widget.Node} node the node that has the focus
334 this.createEvent("enterKeyPressed", this);
337 * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a Click.
338 * The listener may return false to cancel toggling and focusing on the node.
341 * @param oArgs.event {HTMLEvent} The event object
342 * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked
344 this.createEvent("clickEvent", this);
347 * Fires when the focus receives the focus, when it changes from a Node
348 * to another Node or when it is completely lost (blurred)
349 * @event focusChanged
351 * @param oArgs.oldNode {YAHOO.widget.Node} Node that had the focus or null if none
352 * @param oArgs.newNode {YAHOO.widget.Node} Node that receives the focus or null if none
355 this.createEvent('focusChanged',this);
358 * Fires when the label in a TextNode or MenuNode or content in an HTMLNode receives a double Click
359 * @event dblClickEvent
361 * @param oArgs.event {HTMLEvent} The event object
362 * @param oArgs.node {YAHOO.widget.Node} node the node that was clicked
365 this.createEvent("dblClickEvent", {
367 onSubscribeCallback: function() {
368 self._hasDblClickSubscriber = true;
373 * Custom event that is fired when the text node label is clicked.
374 * The node clicked is provided as an argument
378 * @param {YAHOO.widget.Node} node the node clicked
379 * @deprecated use clickEvent or dblClickEvent
381 this.createEvent("labelClick", this);
384 * Custom event fired when the highlight of a node changes.
385 * The node that triggered the change is provided as an argument:
386 * The status of the highlight can be checked in
387 * <a href="YAHOO.widget.Node.html#property_highlightState">nodeRef.highlightState</a>.
388 * Depending on <a href="YAHOO.widget.Node.html#property_propagateHighlight">nodeRef.propagateHighlight</a>, other nodes might have changed
389 * @event highlightEvent
391 * @param node{YAHOO.widget.Node} the node that started the change in highlighting state
393 this.createEvent("highlightEvent",this);
399 // store a global reference
400 TV.trees[this.id] = this;
402 // Set up the root node
403 this.root = new Widget.RootNode(this);
405 var LW = Widget.LogWriter;
409 // YAHOO.util.Event.onContentReady(this.id, this.handleAvailable, this, true);
410 // YAHOO.util.Event.on(this.id, "click", this.handleClick, this, true);
413 //handleAvailable: function() {
414 //var Event = YAHOO.util.Event;
418 * Builds the TreeView from an object.
419 * This is the method called by the constructor to build the tree when it has a second argument.
420 * A tree can be described by an array of objects, each object corresponding to a node.
421 * Node descriptions may contain values for any property of a node plus the following extra properties: <ul>
422 * <li>type: can be one of the following:<ul>
423 * <li> A shortname for a node type (<code>'text','menu','html'</code>) </li>
424 * <li>The name of a Node class under YAHOO.widget (<code>'TextNode', 'MenuNode', 'DateNode'</code>, etc) </li>
425 * <li>a reference to an actual class: <code>YAHOO.widget.DateNode</code></li></ul></li>
426 * <li>children: an array containing further node definitions</li></ul>
427 * @method buildTreeFromObject
428 * @param oConfig {Array} array containing a full description of the tree
431 buildTreeFromObject: function (oConfig) {
432 var build = function (parent, oConfig) {
433 var i, item, node, children, type, NodeType, ThisType;
434 for (i = 0; i < oConfig.length; i++) {
436 if (Lang.isString(item)) {
437 node = new Widget.TextNode(item, parent);
438 } else if (Lang.isObject(item)) {
439 children = item.children;
440 delete item.children;
441 type = item.type || 'text';
443 switch (Lang.isString(type) && type.toLowerCase()) {
445 node = new Widget.TextNode(item, parent);
448 node = new Widget.MenuNode(item, parent);
451 node = new Widget.HTMLNode(item, parent);
454 if (Lang.isString(type)) {
455 NodeType = Widget[type];
459 if (Lang.isObject(NodeType)) {
460 for (ThisType = NodeType; ThisType && ThisType !== Widget.Node; ThisType = ThisType.superclass.constructor) {}
462 node = new NodeType(item, parent);
469 build(node,children);
477 build(this.root,oConfig);
480 * Builds the TreeView from existing markup. Markup should consist of <UL> or <OL> elements containing <LI> elements.
481 * Each <LI> can have one element used as label and a second optional element which is to be a <UL> or <OL>
482 * containing nested nodes.
483 * Depending on what the first element of the <LI> element is, the following Nodes will be created: <ul>
484 * <li>plain text: a regular TextNode</li>
485 * <li>anchor <A>: a TextNode with its <code>href</code> and <code>target</code> taken from the anchor</li>
486 * <li>anything else: an HTMLNode</li></ul>
487 * Only the first outermost (un-)ordered list in the markup and its children will be parsed.
488 * Nodes will be collapsed unless an <LI> tag has a className called 'expanded'.
489 * All other className attributes will be copied over to the Node className property.
490 * If the <LI> element contains an attribute called <code>yuiConfig</code>, its contents should be a JSON-encoded object
491 * as the one used in method <a href="#method_buildTreeFromObject">buildTreeFromObject</a>.
492 * @method buildTreeFromMarkup
493 * @param id{string|HTMLElement} The id of the element that contains the markup or a reference to it.
495 buildTreeFromMarkup: function (id) {
496 var build = function (markup) {
497 var el, child, branch = [], config = {}, label, yuiConfig;
498 // Dom's getFirstChild and getNextSibling skip over text elements
499 for (el = Dom.getFirstChild(markup); el; el = Dom.getNextSibling(el)) {
500 switch (el.tagName.toUpperCase()) {
504 expanded: Dom.hasClass(el,'expanded'),
505 title: el.title || el.alt || null,
506 className: Lang.trim(el.className.replace(/\bexpanded\b/,'')) || null
508 // I cannot skip over text elements here because I want them for labels
509 child = el.firstChild;
510 if (child.nodeType == 3) {
511 // nodes with only whitespace, tabs and new lines don't count, they are probably just formatting.
512 label = Lang.trim(child.nodeValue.replace(/[\n\t\r]*/g,''));
514 config.type = 'text';
515 config.label = label;
517 child = Dom.getNextSibling(child);
521 if (child.tagName.toUpperCase() == 'A') {
522 config.type = 'text';
523 config.label = child.innerHTML;
524 config.href = child.href;
525 config.target = child.target;
526 config.title = child.title || child.alt || config.title;
528 config.type = 'html';
529 var d = document.createElement('div');
530 d.appendChild(child.cloneNode(true));
531 config.html = d.innerHTML;
532 config.hasIcon = true;
535 // see if after the label it has a further list which will become children of this node.
536 child = Dom.getNextSibling(child);
537 switch (child && child.tagName.toUpperCase()) {
540 config.children = build(child);
543 // if there are further elements or text, it will be ignored.
545 if (YAHOO.lang.JSON) {
546 yuiConfig = el.getAttribute('yuiConfig');
548 yuiConfig = YAHOO.lang.JSON.parse(yuiConfig);
549 config = YAHOO.lang.merge(config,yuiConfig);
560 children: build(child)
569 var markup = Dom.getChildrenBy(Dom.get(id),function (el) {
570 var tag = el.tagName.toUpperCase();
571 return tag == 'UL' || tag == 'OL';
574 this.buildTreeFromObject(build(markup[0]));
579 * Returns the TD element where the event has occurred
580 * @method _getEventTargetTdEl
583 _getEventTargetTdEl: function (ev) {
584 var target = Event.getTarget(ev);
585 // go up looking for a TD with a className with a ygtv prefix
586 while (target && !(target.tagName.toUpperCase() == 'TD' && Dom.hasClass(target.parentNode,'ygtvrow'))) {
587 target = Dom.getAncestorByTagName(target,'td');
589 if (Lang.isNull(target)) { return null; }
590 // If it is a spacer cell, do nothing
591 if (/\bygtv(blank)?depthcell/.test(target.className)) { return null;}
592 // If it has an id, search for the node number and see if it belongs to a node in this tree.
594 var m = target.id.match(/\bygtv([^\d]*)(.*)/);
595 if (m && m[2] && this._nodes[m[2]]) {
602 * Event listener for click events
603 * @method _onClickEvent
606 _onClickEvent: function (ev) {
608 td = this._getEventTargetTdEl(ev),
611 toggle = function () {
615 Event.preventDefault(ev);
618 // For some reason IE8 is providing an event object with
619 // most of the fields missing, but only when clicking on
620 // the node's label, and only when working with inline
621 // editing. This generates a "Member not found" error
622 // in that browser. Determine if this is a browser
623 // bug, or a problem with this code. Already checked to
624 // see if the problem has to do with access the event
625 // in the outer scope, and that isn't the problem.
626 // Maybe the markup for inline editing is broken.
634 node = this.getNodeByElement(td);
639 // exception to handle deprecated event labelClick
640 // @TODO take another look at this deprecation. It is common for people to
641 // only be interested in the label click, so why make them have to test
642 // the node type to figure out whether the click was on the label?
643 target = Event.getTarget(ev);
644 if (Dom.hasClass(target, node.labelStyle) || Dom.getAncestorByClassName(target,node.labelStyle)) {
645 this.fireEvent('labelClick',node);
648 // If it is a toggle cell, toggle
649 if (/\bygtv[tl][mp]h?h?/.test(td.className)) {
652 if (this._dblClickTimer) {
653 window.clearTimeout(this._dblClickTimer);
654 this._dblClickTimer = null;
656 if (this._hasDblClickSubscriber) {
657 this._dblClickTimer = window.setTimeout(function () {
658 self._dblClickTimer = null;
659 if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) {
664 if (self.fireEvent('clickEvent', {event:ev,node:node}) !== false) {
673 * Event listener for double-click events
674 * @method _onDblClickEvent
677 _onDblClickEvent: function (ev) {
678 if (!this._hasDblClickSubscriber) { return; }
679 var td = this._getEventTargetTdEl(ev);
682 if (!(/\bygtv[tl][mp]h?h?/.test(td.className))) {
683 this.fireEvent('dblClickEvent', {event:ev, node:this.getNodeByElement(td)});
684 if (this._dblClickTimer) {
685 window.clearTimeout(this._dblClickTimer);
686 this._dblClickTimer = null;
691 * Event listener for mouse over events
692 * @method _onMouseOverEvent
695 _onMouseOverEvent:function (ev) {
697 if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) {
698 target.className = target.className.replace(/\bygtv([lt])([mp])\b/gi,'ygtv$1$2h');
702 * Event listener for mouse out events
703 * @method _onMouseOutEvent
706 _onMouseOutEvent: function (ev) {
708 if ((target = this._getEventTargetTdEl(ev)) && (target = this.getNodeByElement(target)) && (target = target.getToggleEl())) {
709 target.className = target.className.replace(/\bygtv([lt])([mp])h\b/gi,'ygtv$1$2');
713 * Event listener for key down events
714 * @method _onKeyDownEvent
717 _onKeyDownEvent: function (ev) {
718 var target = Event.getTarget(ev),
719 node = this.getNodeByElement(target),
721 KEY = YAHOO.util.KeyListener.KEY;
726 if (newNode.previousSibling) {
727 newNode = newNode.previousSibling;
729 newNode = newNode.parent;
731 } while (newNode && !newNode._canHaveFocus());
732 if (newNode) { newNode.focus(); }
733 Event.preventDefault(ev);
737 if (newNode.nextSibling) {
738 newNode = newNode.nextSibling;
741 newNode = (newNode.children.length || null) && newNode.children[0];
743 } while (newNode && !newNode._canHaveFocus);
744 if (newNode) { newNode.focus();}
745 Event.preventDefault(ev);
749 if (newNode.parent) {
750 newNode = newNode.parent;
752 newNode = newNode.previousSibling;
754 } while (newNode && !newNode._canHaveFocus());
755 if (newNode) { newNode.focus();}
756 Event.preventDefault(ev);
761 if (newNode.children.length) {
762 newNode = newNode.children[0];
764 newNode = newNode.nextSibling;
766 } while (newNode && !newNode._canHaveFocus());
767 if (newNode) { newNode.focus();}
768 Event.preventDefault(ev);
773 window.open(node.href,node.target);
775 window.location(node.href);
780 this.fireEvent('enterKeyPressed',node);
781 Event.preventDefault(ev);
784 newNode = this.getRoot();
785 if (newNode.children.length) {newNode = newNode.children[0];}
786 if (newNode._canHaveFocus()) { newNode.focus(); }
787 Event.preventDefault(ev);
790 newNode = newNode.parent.children;
791 newNode = newNode[newNode.length -1];
792 if (newNode._canHaveFocus()) { newNode.focus(); }
793 Event.preventDefault(ev);
797 // case KEY.PAGE_DOWN:
799 case 107: // plus key
801 node.parent.expandAll();
806 case 109: // minus key
808 node.parent.collapseAll();
818 * Renders the tree boilerplate and visible nodes
822 var html = this.root.getHtml(),
825 if (!this._hasEvents) {
826 Event.on(el, 'click', this._onClickEvent, this, true);
827 Event.on(el, 'dblclick', this._onDblClickEvent, this, true);
828 Event.on(el, 'mouseover', this._onMouseOverEvent, this, true);
829 Event.on(el, 'mouseout', this._onMouseOutEvent, this, true);
830 Event.on(el, 'keydown', this._onKeyDownEvent, this, true);
832 this._hasEvents = true;
836 * Returns the tree's host element
838 * @return {HTMLElement} the host element
842 this._el = Dom.get(this.id);
848 * Nodes register themselves with the tree instance when they are created.
850 * @param node {Node} the node to register
853 regNode: function(node) {
854 this._nodes[node.index] = node;
858 * Returns the root node of this tree
860 * @return {Node} the root node
862 getRoot: function() {
867 * Configures this tree to dynamically load all child data
868 * @method setDynamicLoad
869 * @param {function} fnDataLoader the function that will be called to get the data
870 * @param iconMode {int} configures the icon that is displayed when a dynamic
871 * load node is expanded the first time without children. By default, the
872 * "collapse" icon will be used. If set to 1, the leaf node icon will be
875 setDynamicLoad: function(fnDataLoader, iconMode) {
876 this.root.setDynamicLoad(fnDataLoader, iconMode);
880 * Expands all child nodes. Note: this conflicts with the "multiExpand"
881 * node property. If expand all is called in a tree with nodes that
882 * do not allow multiple siblings to be displayed, only the last sibling
886 expandAll: function() {
888 this.root.expandAll();
893 * Collapses all expanded child nodes in the entire tree.
894 * @method collapseAll
896 collapseAll: function() {
898 this.root.collapseAll();
903 * Returns a node in the tree that has the specified index (this index
904 * is created internally, so this function probably will only be used
905 * in html generated for a given node.)
906 * @method getNodeByIndex
907 * @param {int} nodeIndex the index of the node wanted
908 * @return {Node} the node with index=nodeIndex, null if no match
910 getNodeByIndex: function(nodeIndex) {
911 var n = this._nodes[nodeIndex];
912 return (n) ? n : null;
916 * Returns a node that has a matching property and value in the data
917 * object that was passed into its constructor.
918 * @method getNodeByProperty
919 * @param {object} property the property to search (usually a string)
920 * @param {object} value the value we want to find (usuall an int or string)
921 * @return {Node} the matching node, null if no match
923 getNodeByProperty: function(property, value) {
924 for (var i in this._nodes) {
925 if (this._nodes.hasOwnProperty(i)) {
926 var n = this._nodes[i];
927 if ((property in n && n[property] == value) || (n.data && value == n.data[property])) {
937 * Returns a collection of nodes that have a matching property
938 * and value in the data object that was passed into its constructor.
939 * @method getNodesByProperty
940 * @param {object} property the property to search (usually a string)
941 * @param {object} value the value we want to find (usuall an int or string)
942 * @return {Array} the matching collection of nodes, null if no match
944 getNodesByProperty: function(property, value) {
946 for (var i in this._nodes) {
947 if (this._nodes.hasOwnProperty(i)) {
948 var n = this._nodes[i];
949 if ((property in n && n[property] == value) || (n.data && value == n.data[property])) {
955 return (values.length) ? values : null;
959 * Returns the treeview node reference for an anscestor element
960 * of the node, or null if it is not contained within any node
962 * @method getNodeByElement
963 * @param {HTMLElement} the element to test
964 * @return {YAHOO.widget.Node} a node reference or null
966 getNodeByElement: function(el) {
968 var p=el, m, re=/ygtv([^\d]*)(.*)/;
975 return this.getNodeByIndex(m[2]);
981 if (!p || !p.tagName) {
986 while (p.id !== this.id && p.tagName.toLowerCase() !== "body");
992 * Removes the node and its children, and optionally refreshes the
993 * branch of the tree that was affected.
995 * @param {Node} The node to remove
996 * @param {boolean} autoRefresh automatically refreshes branch if true
997 * @return {boolean} False is there was a problem, true otherwise.
999 removeNode: function(node, autoRefresh) {
1001 // Don't delete the root node
1002 if (node.isRoot()) {
1006 // Get the branch that we may need to refresh
1007 var p = node.parent;
1012 // Delete the node and its children
1013 this._deleteNode(node);
1015 // Refresh the parent of the parent
1016 if (autoRefresh && p && p.childrenRendered) {
1024 * wait until the animation is complete before deleting
1025 * to avoid javascript errors
1026 * @method _removeChildren_animComplete
1027 * @param o the custom event payload
1030 _removeChildren_animComplete: function(o) {
1031 this.unsubscribe(this._removeChildren_animComplete);
1032 this.removeChildren(o.node);
1036 * Deletes this nodes child collection, recursively. Also collapses
1037 * the node, and resets the dynamic load flag. The primary use for
1038 * this method is to purge a node and allow it to fetch its data
1039 * dynamically again.
1040 * @method removeChildren
1041 * @param {Node} node the node to purge
1043 removeChildren: function(node) {
1045 if (node.expanded) {
1046 // wait until the animation is complete before deleting to
1047 // avoid javascript errors
1048 if (this._collapseAnim) {
1049 this.subscribe("animComplete",
1050 this._removeChildren_animComplete, this, true);
1051 Widget.Node.prototype.collapse.call(node);
1058 while (node.children.length) {
1059 this._deleteNode(node.children[0]);
1062 if (node.isRoot()) {
1063 Widget.Node.prototype.expand.call(node);
1066 node.childrenRendered = false;
1067 node.dynamicLoadComplete = false;
1073 * Deletes the node and recurses children
1074 * @method _deleteNode
1077 _deleteNode: function(node) {
1078 // Remove all the child nodes first
1079 this.removeChildren(node);
1081 // Remove the node from the tree
1086 * Removes the node from the tree, preserving the child collection
1087 * to make it possible to insert the branch into another part of the
1088 * tree, or another tree.
1090 * @param {Node} the node to remove
1092 popNode: function(node) {
1093 var p = node.parent;
1095 // Update the parent's collection of children
1098 for (var i=0, len=p.children.length;i<len;++i) {
1099 if (p.children[i] != node) {
1100 a[a.length] = p.children[i];
1106 // reset the childrenRendered flag for the parent
1107 p.childrenRendered = false;
1109 // Update the sibling relationship
1110 if (node.previousSibling) {
1111 node.previousSibling.nextSibling = node.nextSibling;
1114 if (node.nextSibling) {
1115 node.nextSibling.previousSibling = node.previousSibling;
1119 node.previousSibling = null;
1120 node.nextSibling = null;
1123 // Update the tree's node collection
1124 delete this._nodes[node.index];
1128 * Nulls out the entire TreeView instance and related objects, removes attached
1129 * event listeners, and clears out DOM elements inside the container. After
1130 * calling this method, the instance reference should be expliclitly nulled by
1131 * implementer, as in myDataTable = null. Use with caution!
1135 destroy : function() {
1136 // Since the label editor can be separated from the main TreeView control
1137 // the destroy method for it might not be there.
1138 if (this._destroyEditor) { this._destroyEditor(); }
1139 var el = this.getEl();
1140 Event.removeListener(el,'click');
1141 Event.removeListener(el,'dblclick');
1142 Event.removeListener(el,'mouseover');
1143 Event.removeListener(el,'mouseout');
1144 Event.removeListener(el,'keydown');
1145 for (var i = 0 ; i < this._nodes.length; i++) {
1146 var node = this._nodes[i];
1147 if (node && node.destroy) {node.destroy(); }
1150 this._hasEvents = false;
1157 * TreeView instance toString
1159 * @return {string} string representation of the tree
1161 toString: function() {
1162 return "TreeView " + this.id;
1166 * Count of nodes in tree
1167 * @method getNodeCount
1168 * @return {int} number of nodes in the tree
1170 getNodeCount: function() {
1171 return this.getRoot().getNodeCount();
1175 * Returns an object which could be used to rebuild the tree.
1176 * It can be passed to the tree constructor to reproduce the same tree.
1177 * It will return false if any node loads dynamically, regardless of whether it is loaded or not.
1178 * @method getTreeDefinition
1179 * @return {Object | false} definition of the tree or false if any node is defined as dynamic
1181 getTreeDefinition: function() {
1182 return this.getRoot().getNodeDefinition();
1186 * Abstract method that is executed when a node is expanded
1188 * @param node {Node} the node that was expanded
1189 * @deprecated use treeobj.subscribe("expand") instead
1191 onExpand: function(node) { },
1194 * Abstract method that is executed when a node is collapsed.
1195 * @method onCollapse
1196 * @param node {Node} the node that was collapsed.
1197 * @deprecated use treeobj.subscribe("collapse") instead
1199 onCollapse: function(node) { },
1202 * Sets the value of a property for all loaded nodes in the tree.
1203 * @method setNodesProperty
1204 * @param name {string} Name of the property to be set
1205 * @param value {any} value to be set
1206 * @param refresh {boolean} if present and true, it does a refresh
1208 setNodesProperty: function(name, value, refresh) {
1209 this.root.setNodesProperty(name,value);
1211 this.root.refresh();
1215 * Event listener to toggle node highlight.
1216 * Can be assigned as listener to clickEvent, dblClickEvent and enterKeyPressed.
1217 * It returns false to prevent the default action.
1218 * @method onEventToggleHighlight
1219 * @param oArgs {any} it takes the arguments of any of the events mentioned above
1220 * @return {false} Always cancels the default action for the event
1222 onEventToggleHighlight: function (oArgs) {
1224 if ('node' in oArgs && oArgs.node instanceof Widget.Node) {
1226 } else if (oArgs instanceof Widget.Node) {
1231 node.toggleHighlight();
1238 /* Backwards compatibility aliases */
1239 var PROT = TV.prototype;
1241 * Renders the tree boilerplate and visible nodes.
1244 * @deprecated Use render instead
1246 PROT.draw = PROT.render;
1248 /* end backwards compatibility aliases */
1250 YAHOO.augment(TV, YAHOO.util.EventProvider);
1253 * Running count of all nodes created in all trees. This is
1254 * used to provide unique identifies for all nodes. Deleting
1255 * nodes does not change the nodeCount.
1256 * @property YAHOO.widget.TreeView.nodeCount
1263 * Global cache of tree instances
1264 * @property YAHOO.widget.TreeView.trees
1272 * Global method for getting a tree by its id. Used in the generated
1274 * @method YAHOO.widget.TreeView.getTree
1275 * @param treeId {String} the id of the tree instance
1276 * @return {TreeView} the tree instance requested, null if not found.
1279 TV.getTree = function(treeId) {
1280 var t = TV.trees[treeId];
1281 return (t) ? t : null;
1286 * Global method for getting a node by its id. Used in the generated
1288 * @method YAHOO.widget.TreeView.getNode
1289 * @param treeId {String} the id of the tree instance
1290 * @param nodeIndex {String} the index of the node to return
1291 * @return {Node} the node instance requested, null if not found
1294 TV.getNode = function(treeId, nodeIndex) {
1295 var t = TV.getTree(treeId);
1296 return (t) ? t.getNodeByIndex(nodeIndex) : null;
1301 * Class name assigned to elements that have the focus
1303 * @property TreeView.FOCUS_CLASS_NAME
1307 * @default "ygtvfocus"
1310 TV.FOCUS_CLASS_NAME = 'ygtvfocus';
1313 * Attempts to preload the images defined in the styles used to draw the tree by
1314 * rendering off-screen elements that use the styles.
1315 * @method YAHOO.widget.TreeView.preload
1316 * @param {string} prefix the prefix to use to generate the names of the
1317 * images to preload, default is ygtv
1320 TV.preload = function(e, prefix) {
1321 prefix = prefix || "ygtv";
1324 var styles = ["tn","tm","tmh","tp","tph","ln","lm","lmh","lp","lph","loading"];
1325 // var styles = ["tp"];
1329 // save the first one for the outer container
1330 for (var i=1; i < styles.length; i=i+1) {
1331 sb[sb.length] = '<span class="' + prefix + styles[i] + '"> </span>';
1334 var f = document.createElement("div");
1336 s.className = prefix + styles[0];
1337 s.position = "absolute";
1342 f.innerHTML = sb.join("");
1344 document.body.appendChild(f);
1346 Event.removeListener(window, "load", TV.preload);
1350 Event.addListener(window,"load", TV.preload);
1353 var Dom = YAHOO.util.Dom,
1355 Event = YAHOO.util.Event;
1357 * The base class for all tree nodes. The node's presentation and behavior in
1358 * response to mouse events is handled in Node subclasses.
1359 * @namespace YAHOO.widget
1361 * @uses YAHOO.util.EventProvider
1362 * @param oData {object} a string or object containing the data that will
1363 * be used to render this node, and any custom attributes that should be
1364 * stored with the node (which is available in noderef.data).
1365 * All values in oData will be used to set equally named properties in the node
1366 * as long as the node does have such properties, they are not undefined, private or functions,
1367 * the rest of the values will be stored in noderef.data
1368 * @param oParent {Node} this node's parent node
1369 * @param expanded {boolean} the initial expanded/collapsed state (deprecated, use oData.expanded)
1372 YAHOO.widget.Node = function(oData, oParent, expanded) {
1373 if (oData) { this.init(oData, oParent, expanded); }
1376 YAHOO.widget.Node.prototype = {
1379 * The index for this instance obtained from global counter in YAHOO.widget.TreeView.
1386 * This node's child node collection.
1387 * @property children
1393 * Tree instance this node is part of
1400 * The data linked to this node. This can be any object or primitive
1401 * value, and the data can be used in getNodeHtml().
1415 * The depth of this node. We start at -1 for the root node.
1422 * The node's expanded/collapsed state
1423 * @property expanded
1429 * Can multiple children be expanded at once?
1430 * @property multiExpand
1436 * Should we render children for a collapsed node? It is possible that the
1437 * implementer will want to render the hidden data... @todo verify that we
1438 * need this, and implement it if we do.
1439 * @property renderHidden
1442 renderHidden: false,
1445 * This flag is set to true when the html is generated for this node's
1446 * children, and set to false when new children are added.
1447 * @property childrenRendered
1450 childrenRendered: false,
1453 * Dynamically loaded nodes only fetch the data the first time they are
1454 * expanded. This flag is set to true once the data has been fetched.
1455 * @property dynamicLoadComplete
1458 dynamicLoadComplete: false,
1461 * This node's previous sibling
1462 * @property previousSibling
1465 previousSibling: null,
1468 * This node's next sibling
1469 * @property nextSibling
1475 * We can set the node up to call an external method to get the child
1477 * @property _dynLoad
1484 * Function to execute when we need to get this node's child data.
1485 * @property dataLoader
1491 * This is true for dynamically loading nodes while waiting for the
1492 * callback to return.
1493 * @property isLoading
1499 * The toggle/branch icon will not show if this is set to false. This
1500 * could be useful if the implementer wants to have the child contain
1501 * extra info about the parent, rather than an actual node.
1508 * Used to configure what happens when a dynamic load node is expanded
1509 * and we discover that it does not have children. By default, it is
1510 * treated as if it still could have children (plus/minus icon). Set
1511 * iconMode to have it display like a leaf node instead.
1512 * @property iconMode
1518 * Specifies whether or not the content area of the node should be allowed
1527 * If true, the node will alway be rendered as a leaf node. This can be
1528 * used to override the presentation when dynamically loading the entire
1529 * tree. Setting this to true also disables the dynamic load call for the
1538 * The CSS class for the html content container. Defaults to ygtvhtml, but
1539 * can be overridden to provide a custom presentation for a specific node.
1540 * @property contentStyle
1547 * The generated id that will contain the data passed in by the implementer.
1548 * @property contentElId
1554 * Enables node highlighting. If true, the node can be highlighted and/or propagate highlighting
1555 * @property enableHighlight
1559 enableHighlight: true,
1562 * Stores the highlight state. Can be any of:
1564 * <li>0 - not highlighted</li>
1565 * <li>1 - highlighted</li>
1566 * <li>2 - some children highlighted</li>
1568 * @property highlightState
1576 * Tells whether highlighting will be propagated up to the parents of the clicked node
1577 * @property propagateHighlightUp
1582 propagateHighlightUp: false,
1585 * Tells whether highlighting will be propagated down to the children of the clicked node
1586 * @property propagateHighlightDown
1591 propagateHighlightDown: false,
1594 * User-defined className to be added to the Node
1595 * @property className
1612 spacerPath: "http://us.i1.yimg.com/us.yimg.com/i/space.gif",
1613 expandedText: "Expanded",
1614 collapsedText: "Collapsed",
1615 loadingText: "Loading",
1619 * Initializes this node, gets some of the properties from the parent
1621 * @param oData {object} a string or object containing the data that will
1622 * be used to render this node
1623 * @param oParent {Node} this node's parent node
1624 * @param expanded {boolean} the initial expanded/collapsed state
1626 init: function(oData, oParent, expanded) {
1630 this.index = YAHOO.widget.TreeView.nodeCount;
1631 ++YAHOO.widget.TreeView.nodeCount;
1632 this.contentElId = "ygtvcontentel" + this.index;
1634 if (Lang.isObject(oData)) {
1635 for (var property in oData) {
1636 if (oData.hasOwnProperty(property)) {
1637 if (property.charAt(0) != '_' && !Lang.isUndefined(this[property]) && !Lang.isFunction(this[property]) ) {
1638 this[property] = oData[property];
1640 this.data[property] = oData[property];
1645 if (!Lang.isUndefined(expanded) ) { this.expanded = expanded; }
1649 * The parentChange event is fired when a parent element is applied
1650 * to the node. This is useful if you need to apply tree-level
1651 * properties to a tree that need to happen if a node is moved from
1652 * one tree to another.
1654 * @event parentChange
1657 this.createEvent("parentChange", this);
1659 // oParent should never be null except when we create the root node.
1661 oParent.appendChild(this);
1666 * Certain properties for the node cannot be set until the parent
1667 * is known. This is called after the node is inserted into a tree.
1668 * the parent is also applied to this node's children in order to
1669 * make it possible to move a branch from one tree to another.
1670 * @method applyParent
1671 * @param {Node} parentNode this node's parent node
1672 * @return {boolean} true if the application was successful
1674 applyParent: function(parentNode) {
1679 this.tree = parentNode.tree;
1680 this.parent = parentNode;
1681 this.depth = parentNode.depth + 1;
1683 // @todo why was this put here. This causes new nodes added at the
1684 // root level to lose the menu behavior.
1685 // if (! this.multiExpand) {
1686 // this.multiExpand = parentNode.multiExpand;
1689 this.tree.regNode(this);
1690 parentNode.childrenRendered = false;
1692 // cascade update existing children
1693 for (var i=0, len=this.children.length;i<len;++i) {
1694 this.children[i].applyParent(this);
1697 this.fireEvent("parentChange");
1703 * Appends a node to the child collection.
1704 * @method appendChild
1705 * @param childNode {Node} the new node
1706 * @return {Node} the child node
1709 appendChild: function(childNode) {
1710 if (this.hasChildren()) {
1711 var sib = this.children[this.children.length - 1];
1712 sib.nextSibling = childNode;
1713 childNode.previousSibling = sib;
1715 this.children[this.children.length] = childNode;
1716 childNode.applyParent(this);
1718 // part of the IE display issue workaround. If child nodes
1719 // are added after the initial render, and the node was
1720 // instantiated with expanded = true, we need to show the
1721 // children div now that the node has a child.
1722 if (this.childrenRendered && this.expanded) {
1723 this.getChildrenEl().style.display = "";
1730 * Appends this node to the supplied node's child collection
1732 * @param parentNode {Node} the node to append to.
1733 * @return {Node} The appended node
1735 appendTo: function(parentNode) {
1736 return parentNode.appendChild(this);
1740 * Inserts this node before this supplied node
1741 * @method insertBefore
1742 * @param node {Node} the node to insert this node before
1743 * @return {Node} the inserted node
1745 insertBefore: function(node) {
1746 var p = node.parent;
1750 this.tree.popNode(this);
1753 var refIndex = node.isChildOf(p);
1754 p.children.splice(refIndex, 0, this);
1755 if (node.previousSibling) {
1756 node.previousSibling.nextSibling = this;
1758 this.previousSibling = node.previousSibling;
1759 this.nextSibling = node;
1760 node.previousSibling = this;
1762 this.applyParent(p);
1769 * Inserts this node after the supplied node
1770 * @method insertAfter
1771 * @param node {Node} the node to insert after
1772 * @return {Node} the inserted node
1774 insertAfter: function(node) {
1775 var p = node.parent;
1779 this.tree.popNode(this);
1782 var refIndex = node.isChildOf(p);
1784 if (!node.nextSibling) {
1785 this.nextSibling = null;
1786 return this.appendTo(p);
1789 p.children.splice(refIndex + 1, 0, this);
1791 node.nextSibling.previousSibling = this;
1792 this.previousSibling = node;
1793 this.nextSibling = node.nextSibling;
1794 node.nextSibling = this;
1796 this.applyParent(p);
1803 * Returns true if the Node is a child of supplied Node
1805 * @param parentNode {Node} the Node to check
1806 * @return {boolean} The node index if this Node is a child of
1807 * supplied Node, else -1.
1810 isChildOf: function(parentNode) {
1811 if (parentNode && parentNode.children) {
1812 for (var i=0, len=parentNode.children.length; i<len ; ++i) {
1813 if (parentNode.children[i] === this) {
1823 * Returns a node array of this node's siblings, null if none.
1824 * @method getSiblings
1827 getSiblings: function() {
1828 var sib = this.parent.children.slice(0);
1829 for (var i=0;i < sib.length && sib[i] != this;i++) {}
1831 if (sib.length) { return sib; }
1836 * Shows this node's children
1837 * @method showChildren
1839 showChildren: function() {
1840 if (!this.tree.animateExpand(this.getChildrenEl(), this)) {
1841 if (this.hasChildren()) {
1842 this.getChildrenEl().style.display = "";
1848 * Hides this node's children
1849 * @method hideChildren
1851 hideChildren: function() {
1853 if (!this.tree.animateCollapse(this.getChildrenEl(), this)) {
1854 this.getChildrenEl().style.display = "none";
1859 * Returns the id for this node's container div
1861 * @return {string} the element id
1863 getElId: function() {
1864 return "ygtv" + this.index;
1868 * Returns the id for this node's children div
1869 * @method getChildrenElId
1870 * @return {string} the element id for this node's children div
1872 getChildrenElId: function() {
1873 return "ygtvc" + this.index;
1877 * Returns the id for this node's toggle element
1878 * @method getToggleElId
1879 * @return {string} the toggel element id
1881 getToggleElId: function() {
1882 return "ygtvt" + this.index;
1887 * Returns the id for this node's spacer image. The spacer is positioned
1888 * over the toggle and provides feedback for screen readers.
1889 * @method getSpacerId
1890 * @return {string} the id for the spacer image
1893 getSpacerId: function() {
1894 return "ygtvspacer" + this.index;
1899 * Returns this node's container html element
1901 * @return {HTMLElement} the container html element
1904 return Dom.get(this.getElId());
1908 * Returns the div that was generated for this node's children
1909 * @method getChildrenEl
1910 * @return {HTMLElement} this node's children div
1912 getChildrenEl: function() {
1913 return Dom.get(this.getChildrenElId());
1917 * Returns the element that is being used for this node's toggle.
1918 * @method getToggleEl
1919 * @return {HTMLElement} this node's toggle html element
1921 getToggleEl: function() {
1922 return Dom.get(this.getToggleElId());
1925 * Returns the outer html element for this node's content
1926 * @method getContentEl
1927 * @return {HTMLElement} the element
1929 getContentEl: function() {
1930 return Dom.get(this.contentElId);
1935 * Returns the element that is being used for this node's spacer.
1937 * @return {HTMLElement} this node's spacer html element
1940 getSpacer: function() {
1941 return document.getElementById( this.getSpacerId() ) || {};
1946 getStateText: function() {
1947 if (this.isLoading) {
1948 return this.loadingText;
1949 } else if (this.hasChildren(true)) {
1950 if (this.expanded) {
1951 return this.expandedText;
1953 return this.collapsedText;
1962 * Hides this nodes children (creating them if necessary), changes the toggle style.
1965 collapse: function() {
1966 // Only collapse if currently expanded
1967 if (!this.expanded) { return; }
1969 // fire the collapse event handler
1970 var ret = this.tree.onCollapse(this);
1972 if (false === ret) {
1976 ret = this.tree.fireEvent("collapse", this);
1978 if (false === ret) {
1983 if (!this.getEl()) {
1984 this.expanded = false;
1986 // hide the child div
1987 this.hideChildren();
1988 this.expanded = false;
1993 // this.getSpacer().title = this.getStateText();
1995 ret = this.tree.fireEvent("collapseComplete", this);
2000 * Shows this nodes children (creating them if necessary), changes the
2001 * toggle style, and collapses its siblings if multiExpand is not set.
2004 expand: function(lazySource) {
2005 // Only expand if currently collapsed.
2006 if (this.expanded && !lazySource) {
2012 // When returning from the lazy load handler, expand is called again
2013 // in order to render the new children. The "expand" event already
2014 // fired before fething the new data, so we need to skip it now.
2016 // fire the expand event handler
2017 ret = this.tree.onExpand(this);
2019 if (false === ret) {
2023 ret = this.tree.fireEvent("expand", this);
2026 if (false === ret) {
2030 if (!this.getEl()) {
2031 this.expanded = true;
2035 if (!this.childrenRendered) {
2036 this.getChildrenEl().innerHTML = this.renderChildren();
2040 this.expanded = true;
2044 // this.getSpacer().title = this.getStateText();
2046 // We do an extra check for children here because the lazy
2047 // load feature can expose nodes that have no children.
2049 // if (!this.hasChildren()) {
2050 if (this.isLoading) {
2051 this.expanded = false;
2055 if (! this.multiExpand) {
2056 var sibs = this.getSiblings();
2057 for (var i=0; sibs && i<sibs.length; ++i) {
2058 if (sibs[i] != this && sibs[i].expanded) {
2064 this.showChildren();
2066 ret = this.tree.fireEvent("expandComplete", this);
2069 updateIcon: function() {
2071 var el = this.getToggleEl();
2073 el.className = el.className.replace(/\bygtv(([tl][pmn]h?)|(loading))\b/gi,this.getStyle());
2079 * Returns the css style name for the toggle
2081 * @return {string} the css class for this node's toggle
2083 getStyle: function() {
2084 if (this.isLoading) {
2085 return "ygtvloading";
2087 // location top or bottom, middle nodes also get the top style
2088 var loc = (this.nextSibling) ? "t" : "l";
2090 // type p=plus(expand), m=minus(collapase), n=none(no children)
2092 if (this.hasChildren(true) || (this.isDynamic() && !this.getIconMode())) {
2093 // if (this.hasChildren(true)) {
2094 type = (this.expanded) ? "m" : "p";
2097 return "ygtv" + loc + type;
2102 * Returns the hover style for the icon
2103 * @return {string} the css class hover state
2104 * @method getHoverStyle
2106 getHoverStyle: function() {
2107 var s = this.getStyle();
2108 if (this.hasChildren(true) && !this.isLoading) {
2115 * Recursively expands all of this node's children.
2118 expandAll: function() {
2119 var l = this.children.length;
2120 for (var i=0;i<l;++i) {
2121 var c = this.children[i];
2122 if (c.isDynamic()) {
2124 } else if (! c.multiExpand) {
2134 * Recursively collapses all of this node's children.
2135 * @method collapseAll
2137 collapseAll: function() {
2138 for (var i=0;i<this.children.length;++i) {
2139 this.children[i].collapse();
2140 this.children[i].collapseAll();
2145 * Configures this node for dynamically obtaining the child data
2146 * when the node is first expanded. Calling it without the callback
2147 * will turn off dynamic load for the node.
2148 * @method setDynamicLoad
2149 * @param fmDataLoader {function} the function that will be used to get the data.
2150 * @param iconMode {int} configures the icon that is displayed when a dynamic
2151 * load node is expanded the first time without children. By default, the
2152 * "collapse" icon will be used. If set to 1, the leaf node icon will be
2155 setDynamicLoad: function(fnDataLoader, iconMode) {
2157 this.dataLoader = fnDataLoader;
2158 this._dynLoad = true;
2160 this.dataLoader = null;
2161 this._dynLoad = false;
2165 this.iconMode = iconMode;
2170 * Evaluates if this node is the root node of the tree
2172 * @return {boolean} true if this is the root node
2174 isRoot: function() {
2175 return (this == this.tree.root);
2179 * Evaluates if this node's children should be loaded dynamically. Looks for
2180 * the property both in this instance and the root node. If the tree is
2181 * defined to load all children dynamically, the data callback function is
2182 * defined in the root node
2184 * @return {boolean} true if this node's children are to be loaded dynamically
2186 isDynamic: function() {
2190 return (!this.isRoot() && (this._dynLoad || this.tree.root._dynLoad));
2196 * Returns the current icon mode. This refers to the way childless dynamic
2197 * load nodes appear (this comes into play only after the initial dynamic
2198 * load request produced no children).
2199 * @method getIconMode
2200 * @return {int} 0 for collapse style, 1 for leaf node style
2202 getIconMode: function() {
2203 return (this.iconMode || this.tree.root.iconMode);
2207 * Checks if this node has children. If this node is lazy-loading and the
2208 * children have not been rendered, we do not know whether or not there
2209 * are actual children. In most cases, we need to assume that there are
2210 * children (for instance, the toggle needs to show the expandable
2211 * presentation state). In other times we want to know if there are rendered
2212 * children. For the latter, "checkForLazyLoad" should be false.
2213 * @method hasChildren
2214 * @param checkForLazyLoad {boolean} should we check for unloaded children?
2215 * @return {boolean} true if this has children or if it might and we are
2216 * checking for this condition.
2218 hasChildren: function(checkForLazyLoad) {
2222 return ( this.children.length > 0 ||
2223 (checkForLazyLoad && this.isDynamic() && !this.dynamicLoadComplete) );
2228 * Expands if node is collapsed, collapses otherwise.
2231 toggle: function() {
2232 if (!this.tree.locked && ( this.hasChildren(true) || this.isDynamic()) ) {
2233 if (this.expanded) { this.collapse(); } else { this.expand(); }
2238 * Returns the markup for this node and its children.
2240 * @return {string} the markup for this node and its expanded children.
2242 getHtml: function() {
2244 this.childrenRendered = false;
2246 return ['<div class="ygtvitem" id="' , this.getElId() , '">' ,this.getNodeHtml() , this.getChildrenHtml() ,'</div>'].join("");
2250 * Called when first rendering the tree. We always build the div that will
2251 * contain this nodes children, but we don't render the children themselves
2252 * unless this node is expanded.
2253 * @method getChildrenHtml
2254 * @return {string} the children container div html and any expanded children
2257 getChildrenHtml: function() {
2261 sb[sb.length] = '<div class="ygtvchildren" id="' + this.getChildrenElId() + '"';
2263 // This is a workaround for an IE rendering issue, the child div has layout
2264 // in IE, creating extra space if a leaf node is created with the expanded
2265 // property set to true.
2266 if (!this.expanded || !this.hasChildren()) {
2267 sb[sb.length] = ' style="display:none;"';
2269 sb[sb.length] = '>';
2272 // Don't render the actual child node HTML unless this node is expanded.
2273 if ( (this.hasChildren(true) && this.expanded) ||
2274 (this.renderHidden && !this.isDynamic()) ) {
2275 sb[sb.length] = this.renderChildren();
2278 sb[sb.length] = '</div>';
2284 * Generates the markup for the child nodes. This is not done until the node
2286 * @method renderChildren
2287 * @return {string} the html for this node's children
2290 renderChildren: function() {
2295 if (this.isDynamic() && !this.dynamicLoadComplete) {
2296 this.isLoading = true;
2297 this.tree.locked = true;
2299 if (this.dataLoader) {
2303 node.dataLoader(node,
2305 node.loadComplete();
2309 } else if (this.tree.root.dataLoader) {
2313 node.tree.root.dataLoader(node,
2315 node.loadComplete();
2320 return "Error: data loader not found or not specified.";
2326 return this.completeRender();
2331 * Called when we know we have all the child data.
2332 * @method completeRender
2333 * @return {string} children html
2335 completeRender: function() {
2338 for (var i=0; i < this.children.length; ++i) {
2339 // this.children[i].childrenRendered = false;
2340 sb[sb.length] = this.children[i].getHtml();
2343 this.childrenRendered = true;
2349 * Load complete is the callback function we pass to the data provider
2350 * in dynamic load situations.
2351 * @method loadComplete
2353 loadComplete: function() {
2354 this.getChildrenEl().innerHTML = this.completeRender();
2355 this.dynamicLoadComplete = true;
2356 this.isLoading = false;
2358 this.tree.locked = false;
2362 * Returns this node's ancestor at the specified depth.
2363 * @method getAncestor
2364 * @param {int} depth the depth of the ancestor.
2365 * @return {Node} the ancestor
2367 getAncestor: function(depth) {
2368 if (depth >= this.depth || depth < 0) {
2372 var p = this.parent;
2374 while (p.depth > depth) {
2382 * Returns the css class for the spacer at the specified depth for
2383 * this node. If this node's ancestor at the specified depth
2384 * has a next sibling the presentation is different than if it
2385 * does not have a next sibling
2386 * @method getDepthStyle
2387 * @param {int} depth the depth of the ancestor.
2388 * @return {string} the css class for the spacer
2390 getDepthStyle: function(depth) {
2391 return (this.getAncestor(depth).nextSibling) ?
2392 "ygtvdepthcell" : "ygtvblankdepthcell";
2396 * Get the markup for the node. This may be overrided so that we can
2397 * support different types of nodes.
2398 * @method getNodeHtml
2399 * @return {string} The HTML that will render this node.
2401 getNodeHtml: function() {
2404 sb[sb.length] = '<table id="ygtvtableel' + this.index + '"border="0" cellpadding="0" cellspacing="0" class="ygtvtable ygtvdepth' + this.depth;
2405 if (this.enableHighlight) {
2406 sb[sb.length] = ' ygtv-highlight' + this.highlightState;
2408 if (this.className) {
2409 sb[sb.length] = ' ' + this.className;
2411 sb[sb.length] = '"><tr class="ygtvrow">';
2413 for (var i=0;i<this.depth;++i) {
2414 sb[sb.length] = '<td class="ygtvcell ' + this.getDepthStyle(i) + '"><div class="ygtvspacer"></div></td>';
2418 sb[sb.length] = '<td id="' + this.getToggleElId();
2419 sb[sb.length] = '" class="ygtvcell ';
2420 sb[sb.length] = this.getStyle() ;
2421 sb[sb.length] = '"><a href="#" class="ygtvspacer"> </a></td>';
2424 sb[sb.length] = '<td id="' + this.contentElId;
2425 sb[sb.length] = '" class="ygtvcell ';
2426 sb[sb.length] = this.contentStyle + ' ygtvcontent" ';
2427 sb[sb.length] = (this.nowrap) ? ' nowrap="nowrap" ' : '';
2428 sb[sb.length] = ' >';
2429 sb[sb.length] = this.getContentHtml();
2430 sb[sb.length] = '</td></tr></table>';
2436 * Get the markup for the contents of the node. This is designed to be overrided so that we can
2437 * support different types of nodes.
2438 * @method getContentHtml
2439 * @return {string} The HTML that will render the content of this node.
2441 getContentHtml: function () {
2446 * Regenerates the html for this node and its children. To be used when the
2447 * node is expanded and new children have been added.
2450 refresh: function() {
2451 // this.loadComplete();
2452 this.getChildrenEl().innerHTML = this.completeRender();
2455 var el = this.getToggleEl();
2457 el.className = el.className.replace(/\bygtv[lt][nmp]h*\b/gi,this.getStyle());
2465 * @return {string} string representation of the node
2467 toString: function() {
2468 return this._type + " (" + this.index + ")";
2471 * array of items that had the focus set on them
2472 * so that they can be cleaned when focus is lost
2473 * @property _focusHighlightedItems
2474 * @type Array of DOM elements
2477 _focusHighlightedItems: [],
2479 * DOM element that actually got the browser focus
2480 * @property _focusedItem
2487 * Returns true if there are any elements in the node that can
2488 * accept the real actual browser focus
2489 * @method _canHaveFocus
2490 * @return {boolean} success
2493 _canHaveFocus: function() {
2494 return this.getEl().getElementsByTagName('a').length > 0;
2497 * Removes the focus of previously selected Node
2498 * @method _removeFocus
2501 _removeFocus:function () {
2502 if (this._focusedItem) {
2503 Event.removeListener(this._focusedItem,'blur');
2504 this._focusedItem = null;
2507 while ((el = this._focusHighlightedItems.shift())) { // yes, it is meant as an assignment, really
2508 Dom.removeClass(el,YAHOO.widget.TreeView.FOCUS_CLASS_NAME );
2512 * Sets the focus on the node element.
2513 * It will only be able to set the focus on nodes that have anchor elements in it.
2514 * Toggle or branch icons have anchors and can be focused on.
2515 * If will fail in nodes that have no anchor
2517 * @return {boolean} success
2519 focus: function () {
2520 var focused = false, self = this;
2522 if (this.tree.currentFocus) {
2523 this.tree.currentFocus._removeFocus();
2526 var expandParent = function (node) {
2528 expandParent(node.parent);
2529 node.parent.expand();
2536 return /ygtv(([tl][pmn]h?)|(content))/.test(el.className);
2539 self.getEl().firstChild ,
2541 Dom.addClass(el, YAHOO.widget.TreeView.FOCUS_CLASS_NAME );
2543 var aEl = el.getElementsByTagName('a');
2547 self._focusedItem = aEl;
2548 Event.on(aEl,'blur',function () {
2549 //console.log('f1');
2550 self.tree.fireEvent('focusChanged',{oldNode:self.tree.currentFocus,newNode:null});
2551 self.tree.currentFocus = null;
2552 self._removeFocus();
2557 self._focusHighlightedItems.push(el);
2561 //console.log('f2');
2562 this.tree.fireEvent('focusChanged',{oldNode:this.tree.currentFocus,newNode:this});
2563 this.tree.currentFocus = this;
2565 //console.log('f3');
2566 this.tree.fireEvent('focusChanged',{oldNode:self.tree.currentFocus,newNode:null});
2567 this.tree.currentFocus = null;
2568 this._removeFocus();
2574 * Count of nodes in a branch
2575 * @method getNodeCount
2576 * @return {int} number of nodes in the branch
2578 getNodeCount: function() {
2579 for (var i = 0, count = 0;i< this.children.length;i++) {
2580 count += this.children[i].getNodeCount();
2586 * Returns an object which could be used to build a tree out of this node and its children.
2587 * It can be passed to the tree constructor to reproduce this node as a tree.
2588 * It will return false if the node or any children loads dynamically, regardless of whether it is loaded or not.
2589 * @method getNodeDefinition
2590 * @return {Object | false} definition of the tree or false if the node or any children is defined as dynamic
2592 getNodeDefinition: function() {
2594 if (this.isDynamic()) { return false; }
2596 var def, defs = Lang.merge(this.data), children = [];
2600 if (this.expanded) {defs.expanded = this.expanded; }
2601 if (!this.multiExpand) { defs.multiExpand = this.multiExpand; }
2602 if (!this.renderHidden) { defs.renderHidden = this.renderHidden; }
2603 if (!this.hasIcon) { defs.hasIcon = this.hasIcon; }
2604 if (this.nowrap) { defs.nowrap = this.nowrap; }
2605 if (this.className) { defs.className = this.className; }
2606 if (this.editable) { defs.editable = this.editable; }
2607 if (this.enableHighlight) { defs.enableHighlight = this.enableHighlight; }
2608 if (this.highlightState) { defs.highlightState = this.highlightState; }
2609 if (this.propagateHighlightUp) { defs.propagateHighlightUp = this.propagateHighlightUp; }
2610 if (this.propagateHighlightDown) { defs.propagateHighlightDown = this.propagateHighlightDown; }
2611 defs.type = this._type;
2615 for (var i = 0; i < this.children.length;i++) {
2616 def = this.children[i].getNodeDefinition();
2617 if (def === false) { return false;}
2620 if (children.length) { defs.children = children; }
2626 * Generates the link that will invoke this node's toggle method
2627 * @method getToggleLink
2628 * @return {string} the javascript url for toggling this node
2630 getToggleLink: function() {
2631 return 'return false;';
2635 * Sets the value of property for this node and all loaded descendants.
2636 * Only public and defined properties can be set, not methods.
2637 * Values for unknown properties will be assigned to the refNode.data object
2638 * @method setNodesProperty
2639 * @param name {string} Name of the property to be set
2640 * @param value {any} value to be set
2641 * @param refresh {boolean} if present and true, it does a refresh
2643 setNodesProperty: function(name, value, refresh) {
2644 if (name.charAt(0) != '_' && !Lang.isUndefined(this[name]) && !Lang.isFunction(this[name]) ) {
2647 this.data[name] = value;
2649 for (var i = 0; i < this.children.length;i++) {
2650 this.children[i].setNodesProperty(name,value);
2657 * Toggles the highlighted state of a Node
2658 * @method toggleHighlight
2660 toggleHighlight: function() {
2661 if (this.enableHighlight) {
2662 // unhighlights only if fully highligthed. For not or partially highlighted it will highlight
2663 if (this.highlightState == 1) {
2672 * Turns highlighting on node.
2674 * @param _silent {boolean} optional, don't fire the highlightEvent
2676 highlight: function(_silent) {
2677 if (this.enableHighlight) {
2678 if (this.tree.singleNodeHighlight) {
2679 if (this.tree._currentlyHighlighted) {
2680 this.tree._currentlyHighlighted.unhighlight();
2682 this.tree._currentlyHighlighted = this;
2684 this.highlightState = 1;
2685 this._setHighlightClassName();
2686 if (this.propagateHighlightDown) {
2687 for (var i = 0;i < this.children.length;i++) {
2688 this.children[i].highlight(true);
2691 if (this.propagateHighlightUp) {
2693 this.parent._childrenHighlighted();
2697 this.tree.fireEvent('highlightEvent',this);
2702 * Turns highlighting off a node.
2703 * @method unhighlight
2704 * @param _silent {boolean} optional, don't fire the highlightEvent
2706 unhighlight: function(_silent) {
2707 if (this.enableHighlight) {
2708 this.highlightState = 0;
2709 this._setHighlightClassName();
2710 if (this.propagateHighlightDown) {
2711 for (var i = 0;i < this.children.length;i++) {
2712 this.children[i].unhighlight(true);
2715 if (this.propagateHighlightUp) {
2717 this.parent._childrenHighlighted();
2721 this.tree.fireEvent('highlightEvent',this);
2726 * Checks whether all or part of the children of a node are highlighted and
2727 * sets the node highlight to full, none or partial highlight.
2728 * If set to propagate it will further call the parent
2729 * @method _childrenHighlighted
2732 _childrenHighlighted: function() {
2733 var yes = false, no = false;
2734 if (this.enableHighlight) {
2735 for (var i = 0;i < this.children.length;i++) {
2736 switch(this.children[i].highlightState) {
2749 this.highlightState = 2;
2751 this.highlightState = 1;
2753 this.highlightState = 0;
2755 this._setHighlightClassName();
2756 if (this.propagateHighlightUp) {
2758 this.parent._childrenHighlighted();
2765 * Changes the classNames on the toggle and content containers to reflect the current highlighting
2766 * @method _setHighlightClassName
2769 _setHighlightClassName: function() {
2770 var el = Dom.get('ygtvtableel' + this.index);
2772 el.className = el.className.replace(/\bygtv-highlight\d\b/gi,'ygtv-highlight' + this.highlightState);
2778 YAHOO.augment(YAHOO.widget.Node, YAHOO.util.EventProvider);
2781 * A custom YAHOO.widget.Node that handles the unique nature of
2782 * the virtual, presentationless root node.
2783 * @namespace YAHOO.widget
2785 * @extends YAHOO.widget.Node
2786 * @param oTree {YAHOO.widget.TreeView} The tree instance this node belongs to
2789 YAHOO.widget.RootNode = function(oTree) {
2790 // Initialize the node with null params. The root node is a
2791 // special case where the node has no presentation. So we have
2792 // to alter the standard properties a bit.
2793 this.init(null, null, true);
2796 * For the root node, we get the tree reference from as a param
2797 * to the constructor instead of from the parent element.
2802 YAHOO.extend(YAHOO.widget.RootNode, YAHOO.widget.Node, {
2809 * @default "RootNode"
2813 // overrides YAHOO.widget.Node
2814 getNodeHtml: function() {
2818 toString: function() {
2822 loadComplete: function() {
2827 * Count of nodes in tree.
2828 * It overrides Nodes.getNodeCount because the root node should not be counted.
2829 * @method getNodeCount
2830 * @return {int} number of nodes in the tree
2832 getNodeCount: function() {
2833 for (var i = 0, count = 0;i< this.children.length;i++) {
2834 count += this.children[i].getNodeCount();
2840 * Returns an object which could be used to build a tree out of this node and its children.
2841 * It can be passed to the tree constructor to reproduce this node as a tree.
2842 * Since the RootNode is automatically created by treeView,
2843 * its own definition is excluded from the returned node definition
2844 * which only contains its children.
2845 * @method getNodeDefinition
2846 * @return {Object | false} definition of the tree or false if any child node is defined as dynamic
2848 getNodeDefinition: function() {
2850 for (var def, defs = [], i = 0; i < this.children.length;i++) {
2851 def = this.children[i].getNodeDefinition();
2852 if (def === false) { return false;}
2858 collapse: function() {},
2859 expand: function() {},
2860 getSiblings: function() { return null; },
2861 focus: function () {}
2865 var Dom = YAHOO.util.Dom,
2867 Event = YAHOO.util.Event;
2869 * The default node presentation. The first parameter should be
2870 * either a string that will be used as the node's label, or an object
2871 * that has at least a string property called label. By default, clicking the
2872 * label will toggle the expanded/collapsed state of the node. By
2873 * setting the href property of the instance, this behavior can be
2874 * changed so that the label will go to the specified href.
2875 * @namespace YAHOO.widget
2877 * @extends YAHOO.widget.Node
2879 * @param oData {object} a string or object containing the data that will
2880 * be used to render this node.
2881 * Providing a string is the same as providing an object with a single property named label.
2882 * All values in the oData will be used to set equally named properties in the node
2883 * as long as the node does have such properties, they are not undefined, private or functions.
2884 * All attributes are made available in noderef.data, which
2885 * can be used to store custom attributes. TreeView.getNode(s)ByProperty
2886 * can be used to retrieve a node by one of the attributes.
2887 * @param oParent {YAHOO.widget.Node} this node's parent node
2888 * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded)
2890 YAHOO.widget.TextNode = function(oData, oParent, expanded) {
2893 if (Lang.isString(oData)) {
2894 oData = { label: oData };
2896 this.init(oData, oParent, expanded);
2897 this.setUpLabel(oData);
2902 YAHOO.extend(YAHOO.widget.TextNode, YAHOO.widget.Node, {
2905 * The CSS class for the label href. Defaults to ygtvlabel, but can be
2906 * overridden to provide a custom presentation for a specific node.
2907 * @property labelStyle
2910 labelStyle: "ygtvlabel",
2913 * The derived element id of the label for this node
2914 * @property labelElId
2920 * The text for the label. It is assumed that the oData parameter will
2921 * either be a string that will be used as the label, or an object that
2922 * has a property called "label" that we will use.
2929 * The text for the title (tooltip) for the label element
2936 * The href for the node's label. If one is not specified, the href will
2937 * be set so that it toggles the node.
2944 * The label href target, defaults to current window
2955 * @default "TextNode"
2961 * Sets up the node label
2962 * @method setUpLabel
2963 * @param oData string containing the label, or an object with a label property
2965 setUpLabel: function(oData) {
2967 if (Lang.isString(oData)) {
2973 this.labelStyle = oData.style;
2977 this.label = oData.label;
2979 this.labelElId = "ygtvlabelel" + this.index;
2984 * Returns the label element
2985 * @for YAHOO.widget.TextNode
2986 * @method getLabelEl
2987 * @return {object} the element
2989 getLabelEl: function() {
2990 return Dom.get(this.labelElId);
2993 // overrides YAHOO.widget.Node
2994 getContentHtml: function() {
2996 sb[sb.length] = this.href?'<a':'<span';
2997 sb[sb.length] = ' id="' + this.labelElId + '"';
2998 sb[sb.length] = ' class="' + this.labelStyle + '"';
3000 sb[sb.length] = ' href="' + this.href + '"';
3001 sb[sb.length] = ' target="' + this.target + '"';
3004 sb[sb.length] = ' title="' + this.title + '"';
3006 sb[sb.length] = ' >';
3007 sb[sb.length] = this.label;
3008 sb[sb.length] = this.href?'</a>':'</span>';
3015 * Returns an object which could be used to build a tree out of this node and its children.
3016 * It can be passed to the tree constructor to reproduce this node as a tree.
3017 * It will return false if the node or any descendant loads dynamically, regardless of whether it is loaded or not.
3018 * @method getNodeDefinition
3019 * @return {Object | false} definition of the tree or false if this node or any descendant is defined as dynamic
3021 getNodeDefinition: function() {
3022 var def = YAHOO.widget.TextNode.superclass.getNodeDefinition.call(this);
3023 if (def === false) { return false; }
3025 // Node specific properties
3026 def.label = this.label;
3027 if (this.labelStyle != 'ygtvlabel') { def.style = this.labelStyle; }
3028 if (this.title) { def.title = this.title; }
3029 if (this.href) { def.href = this.href; }
3030 if (this.target != '_self') { def.target = this.target; }
3036 toString: function() {
3037 return YAHOO.widget.TextNode.superclass.toString.call(this) + ": " + this.label;
3041 onLabelClick: function() {
3044 refresh: function() {
3045 YAHOO.widget.TextNode.superclass.refresh.call(this);
3046 var label = this.getLabelEl();
3047 label.innerHTML = this.label;
3048 if (label.tagName.toUpperCase() == 'A') {
3049 label.href = this.href;
3050 label.target = this.target;
3060 * A menu-specific implementation that differs from TextNode in that only
3061 * one sibling can be expanded at a time.
3062 * @namespace YAHOO.widget
3064 * @extends YAHOO.widget.TextNode
3065 * @param oData {object} a string or object containing the data that will
3066 * be used to render this node.
3067 * Providing a string is the same as providing an object with a single property named label.
3068 * All values in the oData will be used to set equally named properties in the node
3069 * as long as the node does have such properties, they are not undefined, private or functions.
3070 * All attributes are made available in noderef.data, which
3071 * can be used to store custom attributes. TreeView.getNode(s)ByProperty
3072 * can be used to retrieve a node by one of the attributes.
3073 * @param oParent {YAHOO.widget.Node} this node's parent node
3074 * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded)
3077 YAHOO.widget.MenuNode = function(oData, oParent, expanded) {
3078 YAHOO.widget.MenuNode.superclass.constructor.call(this,oData,oParent,expanded);
3081 * Menus usually allow only one branch to be open at a time.
3083 this.multiExpand = false;
3087 YAHOO.extend(YAHOO.widget.MenuNode, YAHOO.widget.TextNode, {
3093 * @default "MenuNode"
3099 var Dom = YAHOO.util.Dom,
3101 Event = YAHOO.util.Event;
3104 * This implementation takes either a string or object for the
3105 * oData argument. If is it a string, it will use it for the display
3106 * of this node (and it can contain any html code). If the parameter
3107 * is an object,it looks for a parameter called "html" that will be
3108 * used for this node's display.
3109 * @namespace YAHOO.widget
3111 * @extends YAHOO.widget.Node
3113 * @param oData {object} a string or object containing the data that will
3114 * be used to render this node.
3115 * Providing a string is the same as providing an object with a single property named html.
3116 * All values in the oData will be used to set equally named properties in the node
3117 * as long as the node does have such properties, they are not undefined, private or functions.
3118 * All other attributes are made available in noderef.data, which
3119 * can be used to store custom attributes. TreeView.getNode(s)ByProperty
3120 * can be used to retrieve a node by one of the attributes.
3121 * @param oParent {YAHOO.widget.Node} this node's parent node
3122 * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded)
3123 * @param hasIcon {boolean} specifies whether or not leaf nodes should
3124 * be rendered with or without a horizontal line line and/or toggle icon. If the icon
3125 * is not displayed, the content fills the space it would have occupied.
3126 * This option operates independently of the leaf node presentation logic
3127 * for dynamic nodes.
3128 * (deprecated; use oData.hasIcon)
3130 YAHOO.widget.HTMLNode = function(oData, oParent, expanded, hasIcon) {
3132 this.init(oData, oParent, expanded);
3133 this.initContent(oData, hasIcon);
3137 YAHOO.extend(YAHOO.widget.HTMLNode, YAHOO.widget.Node, {
3140 * The CSS class for the html content container. Defaults to ygtvhtml, but
3141 * can be overridden to provide a custom presentation for a specific node.
3142 * @property contentStyle
3145 contentStyle: "ygtvhtml",
3149 * The HTML content to use for this node's display
3160 * @default "HTMLNode"
3165 * Sets up the node label
3166 * @property initContent
3167 * @param oData {object} An html string or object containing an html property
3168 * @param hasIcon {boolean} determines if the node will be rendered with an
3171 initContent: function(oData, hasIcon) {
3172 this.setHtml(oData);
3173 this.contentElId = "ygtvcontentel" + this.index;
3174 if (!Lang.isUndefined(hasIcon)) { this.hasIcon = hasIcon; }
3179 * Synchronizes the node.data, node.html, and the node's content
3181 * @param o {object} An html string or object containing an html property
3183 setHtml: function(o) {
3185 this.html = (typeof o === "string") ? o : o.html;
3187 var el = this.getContentEl();
3189 el.innerHTML = this.html;
3194 // overrides YAHOO.widget.Node
3195 getContentHtml: function() {
3200 * Returns an object which could be used to build a tree out of this node and its children.
3201 * It can be passed to the tree constructor to reproduce this node as a tree.
3202 * It will return false if any node loads dynamically, regardless of whether it is loaded or not.
3203 * @method getNodeDefinition
3204 * @return {Object | false} definition of the tree or false if any node is defined as dynamic
3206 getNodeDefinition: function() {
3207 var def = YAHOO.widget.HTMLNode.superclass.getNodeDefinition.call(this);
3208 if (def === false) { return false; }
3209 def.html = this.html;
3216 var Dom = YAHOO.util.Dom,
3218 Event = YAHOO.util.Event,
3219 Calendar = YAHOO.widget.Calendar;
3222 * A Date-specific implementation that differs from TextNode in that it uses
3223 * YAHOO.widget.Calendar as an in-line editor, if available
3224 * If Calendar is not available, it behaves as a plain TextNode.
3225 * @namespace YAHOO.widget
3227 * @extends YAHOO.widget.TextNode
3228 * @param oData {object} a string or object containing the data that will
3229 * be used to render this node.
3230 * Providing a string is the same as providing an object with a single property named label.
3231 * All values in the oData will be used to set equally named properties in the node
3232 * as long as the node does have such properties, they are not undefined, private nor functions.
3233 * All attributes are made available in noderef.data, which
3234 * can be used to store custom attributes. TreeView.getNode(s)ByProperty
3235 * can be used to retrieve a node by one of the attributes.
3236 * @param oParent {YAHOO.widget.Node} this node's parent node
3237 * @param expanded {boolean} the initial expanded/collapsed state (deprecated; use oData.expanded)
3240 YAHOO.widget.DateNode = function(oData, oParent, expanded) {
3241 YAHOO.widget.DateNode.superclass.constructor.call(this,oData, oParent, expanded);
3244 YAHOO.extend(YAHOO.widget.DateNode, YAHOO.widget.TextNode, {
3251 * @default "DateNode"
3256 * Configuration object for the Calendar editor, if used.
3257 * See <a href="http://developer.yahoo.com/yui/calendar/#internationalization">http://developer.yahoo.com/yui/calendar/#internationalization</a>
3258 * @property calendarConfig
3260 calendarConfig: null,
3265 * If YAHOO.widget.Calendar is available, it will pop up a Calendar to enter a new date. Otherwise, it falls back to a plain <input> textbox
3266 * @method fillEditorContainer
3267 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3270 fillEditorContainer: function (editorData) {
3272 var cal, container = editorData.inputContainer;
3274 if (Lang.isUndefined(Calendar)) {
3275 Dom.replaceClass(editorData.editorPanel,'ygtv-edit-DateNode','ygtv-edit-TextNode');
3276 YAHOO.widget.DateNode.superclass.fillEditorContainer.call(this, editorData);
3280 if (editorData.nodeType != this._type) {
3281 editorData.nodeType = this._type;
3282 editorData.saveOnEnter = false;
3284 editorData.node.destroyEditorContents(editorData);
3286 editorData.inputObject = cal = new Calendar(container.appendChild(document.createElement('div')));
3287 if (this.calendarConfig) {
3288 cal.cfg.applyConfig(this.calendarConfig,true);
3289 cal.cfg.fireQueue();
3291 cal.selectEvent.subscribe(function () {
3292 this.tree._closeEditor(true);
3295 cal = editorData.inputObject;
3298 cal.cfg.setProperty("selected",this.label, false);
3300 var delim = cal.cfg.getProperty('DATE_FIELD_DELIMITER');
3301 var pageDate = this.label.split(delim);
3302 cal.cfg.setProperty('pagedate',pageDate[cal.cfg.getProperty('MDY_MONTH_POSITION') -1] + delim + pageDate[cal.cfg.getProperty('MDY_YEAR_POSITION') -1]);
3303 cal.cfg.fireQueue();
3306 cal.oDomContainer.focus();
3309 * Saves the date entered in the editor into the DateNode label property and displays it.
3310 * Overrides Node.saveEditorValue
3311 * @method saveEditorValue
3312 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3314 saveEditorValue: function (editorData) {
3315 var node = editorData.node,
3316 validator = node.tree.validator,
3318 if (Lang.isUndefined(Calendar)) {
3319 value = editorData.inputElement.value;
3321 var cal = editorData.inputObject,
3322 date = cal.getSelectedDates()[0],
3325 dd[cal.cfg.getProperty('MDY_DAY_POSITION') -1] = date.getDate();
3326 dd[cal.cfg.getProperty('MDY_MONTH_POSITION') -1] = date.getMonth() + 1;
3327 dd[cal.cfg.getProperty('MDY_YEAR_POSITION') -1] = date.getFullYear();
3328 value = dd.join(cal.cfg.getProperty('DATE_FIELD_DELIMITER'));
3330 if (Lang.isFunction(validator)) {
3331 value = validator(value,node.label,node);
3332 if (Lang.isUndefined(value)) { return false; }
3336 node.getLabelEl().innerHTML = value;
3339 * Returns an object which could be used to build a tree out of this node and its children.
3340 * It can be passed to the tree constructor to reproduce this node as a tree.
3341 * It will return false if the node or any descendant loads dynamically, regardless of whether it is loaded or not.
3342 * @method getNodeDefinition
3343 * @return {Object | false} definition of the node or false if this node or any descendant is defined as dynamic
3345 getNodeDefinition: function() {
3346 var def = YAHOO.widget.DateNode.superclass.getNodeDefinition.call(this);
3347 if (def === false) { return false; }
3348 if (this.calendarConfig) { def.calendarConfig = this.calendarConfig; }
3356 var Dom = YAHOO.util.Dom,
3358 Event = YAHOO.util.Event,
3359 TV = YAHOO.widget.TreeView,
3360 TVproto = TV.prototype;
3363 * An object to store information used for in-line editing
3364 * for all Nodes of all TreeViews. It contains:
3366 * <li>active {boolean}, whether there is an active cell editor </li>
3367 * <li>whoHasIt {YAHOO.widget.TreeView} TreeView instance that is currently using the editor</li>
3368 * <li>nodeType {string} value of static Node._type property, allows reuse of input element if node is of the same type.</li>
3369 * <li>editorPanel {HTMLelement (<div>)} element holding the in-line editor</li>
3370 * <li>inputContainer {HTMLelement (<div>)} element which will hold the type-specific input element(s) to be filled by the fillEditorContainer method</li>
3371 * <li>buttonsContainer {HTMLelement (<div>)} element which holds the <button> elements for Ok/Cancel. If you don't want any of the buttons, hide it via CSS styles, don't destroy it</li>
3372 * <li>node {YAHOO.widget.Node} reference to the Node being edited</li>
3373 * <li>saveOnEnter {boolean}, whether the Enter key should be accepted as a Save command (Esc. is always taken as Cancel), disable for multi-line input elements </li>
3375 * Editors are free to use this object to store additional data.
3376 * @property editorData
3378 * @for YAHOO.widget.TreeView
3382 whoHasIt:null, // which TreeView has it
3385 inputContainer:null,
3386 buttonsContainer:null,
3387 node:null, // which Node is being edited
3389 // Each node type is free to add its own properties to this as it sees fit.
3393 * Validator function for edited data, called from the TreeView instance scope,
3394 * receives the arguments (newValue, oldValue, nodeInstance)
3395 * and returns either the validated (or type-converted) value or undefined.
3396 * An undefined return will prevent the editor from closing
3397 * @property validator
3399 * @for YAHOO.widget.TreeView
3401 TVproto.validator = null;
3404 * Entry point of the editing plug-in.
3405 * TreeView will call this method if it exists when a node label is clicked
3406 * @method _nodeEditing
3407 * @param node {YAHOO.widget.Node} the node to be edited
3408 * @return {Boolean} true to indicate that the node is editable and prevent any further bubbling of the click.
3409 * @for YAHOO.widget.TreeView
3414 TVproto._nodeEditing = function (node) {
3415 if (node.fillEditorContainer && node.editable) {
3416 var ed, topLeft, buttons, button, editorData = TV.editorData;
3417 editorData.active = true;
3418 editorData.whoHasIt = this;
3419 if (!editorData.nodeType) {
3420 editorData.editorPanel = ed = document.body.appendChild(document.createElement('div'));
3421 Dom.addClass(ed,'ygtv-label-editor');
3423 buttons = editorData.buttonsContainer = ed.appendChild(document.createElement('div'));
3424 Dom.addClass(buttons,'ygtv-button-container');
3425 button = buttons.appendChild(document.createElement('button'));
3426 Dom.addClass(button,'ygtvok');
3427 button.innerHTML = ' ';
3428 button = buttons.appendChild(document.createElement('button'));
3429 Dom.addClass(button,'ygtvcancel');
3430 button.innerHTML = ' ';
3431 Event.on(buttons, 'click', function (ev) {
3432 var target = Event.getTarget(ev);
3433 var node = TV.editorData.node;
3434 if (Dom.hasClass(target,'ygtvok')) {
3435 Event.stopEvent(ev);
3436 this._closeEditor(true);
3438 if (Dom.hasClass(target,'ygtvcancel')) {
3439 Event.stopEvent(ev);
3440 this._closeEditor(false);
3444 editorData.inputContainer = ed.appendChild(document.createElement('div'));
3445 Dom.addClass(editorData.inputContainer,'ygtv-input');
3447 Event.on(ed,'keydown',function (ev) {
3448 var editorData = TV.editorData,
3449 KEY = YAHOO.util.KeyListener.KEY;
3450 switch (ev.keyCode) {
3452 Event.stopEvent(ev);
3453 if (editorData.saveOnEnter) {
3454 this._closeEditor(true);
3458 Event.stopEvent(ev);
3459 this._closeEditor(false);
3467 ed = editorData.editorPanel;
3469 editorData.node = node;
3470 if (editorData.nodeType) {
3471 Dom.removeClass(ed,'ygtv-edit-' + editorData.nodeType);
3473 Dom.addClass(ed,' ygtv-edit-' + node._type);
3474 topLeft = Dom.getXY(node.getContentEl());
3475 Dom.setStyle(ed,'left',topLeft[0] + 'px');
3476 Dom.setStyle(ed,'top',topLeft[1] + 'px');
3477 Dom.setStyle(ed,'display','block');
3479 node.fillEditorContainer(editorData);
3481 return true; // If inline editor available, don't do anything else.
3486 * Method to be associated with an event (clickEvent, dblClickEvent or enterKeyPressed) to pop up the contents editor
3487 * It calls the corresponding node editNode method.
3488 * @method onEventEditNode
3489 * @param oArgs {object} Object passed as arguments to TreeView event listeners
3490 * @for YAHOO.widget.TreeView
3493 TVproto.onEventEditNode = function (oArgs) {
3494 if (oArgs instanceof YAHOO.widget.Node) {
3496 } else if (oArgs.node instanceof YAHOO.widget.Node) {
3497 oArgs.node.editNode();
3502 * Method to be called when the inline editing is finished and the editor is to be closed
3503 * @method _closeEditor
3504 * @param save {Boolean} true if the edited value is to be saved, false if discarded
3506 * @for YAHOO.widget.TreeView
3509 TVproto._closeEditor = function (save) {
3510 var ed = TV.editorData,
3514 close = ed.node.saveEditorValue(ed) !== false;
3517 Dom.setStyle(ed.editorPanel,'display','none');
3524 * Entry point for TreeView's destroy method to destroy whatever the editing plug-in has created
3525 * @method _destroyEditor
3527 * @for YAHOO.widget.TreeView
3529 TVproto._destroyEditor = function() {
3530 var ed = TV.editorData;
3531 if (ed && ed.nodeType && (!ed.active || ed.whoHasIt === this)) {
3532 Event.removeListener(ed.editorPanel,'keydown');
3533 Event.removeListener(ed.buttonContainer,'click');
3534 ed.node.destroyEditorContents(ed);
3535 document.body.removeChild(ed.editorPanel);
3536 ed.nodeType = ed.editorPanel = ed.inputContainer = ed.buttonsContainer = ed.whoHasIt = ed.node = null;
3541 var Nproto = YAHOO.widget.Node.prototype;
3544 * Signals if the label is editable. (Ignored on TextNodes with href set.)
3545 * @property editable
3547 * @for YAHOO.widget.Node
3549 Nproto.editable = false;
3552 * pops up the contents editor, if there is one and the node is declared editable
3554 * @for YAHOO.widget.Node
3557 Nproto.editNode = function () {
3558 this.tree._nodeEditing(this);
3564 /** Placeholder for a function that should provide the inline node label editor.
3565 * Leaving it set to null will indicate that this node type is not editable.
3566 * It should be overridden by nodes that provide inline editing.
3567 * The Node-specific editing element (input box, textarea or whatever) should be inserted into editorData.inputContainer.
3568 * @method fillEditorContainer
3569 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3571 * @for YAHOO.widget.Node
3573 Nproto.fillEditorContainer = null;
3577 * Node-specific destroy function to empty the contents of the inline editor panel
3578 * This function is the worst case alternative that will purge all possible events and remove the editor contents
3579 * Method Event.purgeElement is somewhat costly so if it can be replaced by specifc Event.removeListeners, it is better to do so.
3580 * @method destroyEditorContents
3581 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3582 * @for YAHOO.widget.Node
3584 Nproto.destroyEditorContents = function (editorData) {
3585 // In the worst case, if the input editor (such as the Calendar) has no destroy method
3586 // we can only try to remove all possible events on it.
3587 Event.purgeElement(editorData.inputContainer,true);
3588 editorData.inputContainer.innerHTML = '';
3592 * Saves the value entered into the editor.
3593 * Should be overridden by each node type
3594 * @method saveEditorValue
3595 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3596 * @return a return of exactly false will prevent the editor from closing
3597 * @for YAHOO.widget.Node
3599 Nproto.saveEditorValue = function (editorData) {
3602 var TNproto = YAHOO.widget.TextNode.prototype;
3607 * Places an <input> textbox in the input container and loads the label text into it
3608 * @method fillEditorContainer
3609 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3611 * @for YAHOO.widget.TextNode
3613 TNproto.fillEditorContainer = function (editorData) {
3616 // If last node edited is not of the same type as this one, delete it and fill it with our editor
3617 if (editorData.nodeType != this._type) {
3618 editorData.nodeType = this._type;
3619 editorData.saveOnEnter = true;
3620 editorData.node.destroyEditorContents(editorData);
3622 editorData.inputElement = input = editorData.inputContainer.appendChild(document.createElement('input'));
3625 // if the last node edited was of the same time, reuse the input element.
3626 input = editorData.inputElement;
3629 input.value = this.label;
3635 * Saves the value entered in the editor into the TextNode label property and displays it
3636 * Overrides Node.saveEditorValue
3637 * @method saveEditorValue
3638 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3639 * @for YAHOO.widget.TextNode
3641 TNproto.saveEditorValue = function (editorData) {
3642 var node = editorData.node,
3643 value = editorData.inputElement.value,
3644 validator = node.tree.validator;
3646 if (Lang.isFunction(validator)) {
3647 value = validator(value,node.label,node);
3648 if (Lang.isUndefined(value)) { return false; }
3651 node.getLabelEl().innerHTML = value;
3655 * Destroys the contents of the inline editor panel
3656 * Overrides Node.destroyEditorContent
3657 * Since we didn't set any event listeners on this inline editor, it is more efficient to avoid the generic method in Node
3658 * @method destroyEditorContents
3659 * @param editorData {YAHOO.widget.TreeView.editorData} a shortcut to the static object holding editing information
3660 * @for YAHOO.widget.TextNode
3662 TNproto.destroyEditorContents = function (editorData) {
3663 editorData.inputContainer.innerHTML = '';
3666 YAHOO.register("treeview", YAHOO.widget.TreeView, {version: "2.7.0", build: "1799"});