Converted Rico3 icons to CSS sprites. Moved minsrc and baselibs directories out of...
[infodrom/rico3] / minsrc / ricoTree.js
1 /*
2  *  (c) 2005-2009 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2009 Matt Brown (http://dowdybrown.com)
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6  *  file except in compliance with the License. You may obtain a copy of the License at
7  *
8  *         http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software distributed under the
11  *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12  *  either express or implied. See the License for the specific language governing permissions
13  *  and limitations under the License.
14  */
15
16 //  Rico Tree Control
17 //  Requires prototype.js and ricoCommon.js
18 //  Data for the tree can be obtained via AJAX requests
19 //  Each record in the AJAX response should contain 5 or 6 cells:
20 //   cells[0]=parent node id
21 //   cells[1]=node id
22 //   cells[2]=description
23 //   cells[3]=L/zero (leaf), C/non-zero (container)
24 //   cells[4]=0->not selectable, 1->selectable (use default action), otherwise the node is selectable and cells[4] contains the action
25 //   cells[5]=leafIcon (optional)
26
27
28 Rico.TreeControl = function(id,url,options) {
29   this.initialize(id,url,options);
30 };
31
32 Rico.TreeControl.prototype = {
33 /**
34  * @class Implements a pop-up tree control.
35  * @extends Rico.Popup
36  * @constructs
37  * @param id unique identifier
38  * @param url data source
39  * @param options object may contain any of the following:<dl>
40  *   <dt>nodeIdDisplay</dt><dd> first, last, tooltip, or none? default=none</dd>
41  *   <dt>showCheckBox </dt><dd> show checkbox next to each item? default=false</dd>
42  *   <dt>showFolders  </dt><dd> show folder icons? default=false</dd>
43  *   <dt>showPlusMinus</dt><dd> show +/- icons to open/close branches? default=true</dd>
44  *   <dt>showLines    </dt><dd> show vertical lines connecting each level? default=true</dd>
45  *   <dt>defaultAction</dt><dd> Rico event handle to call when user clicks on an item, default is to call returnValue method</dd>
46  *   <dt>height       </dt><dd> control height? default=300px</dd>
47  *   <dt>width        </dt><dd> control width? default=300px</dd>
48  *   <dt>leafIcon     </dt><dd> class name to display img, default="rico-icon rico-doc" ('none'=no leaf icon)</dd>
49  *</dl>
50  */
51   initialize: function(id,url,options) {
52     Rico.extend(this, new Rico.Popup());
53     Rico.extend(this.options, {
54       ignoreClicks:true,
55       nodeIdDisplay:'none',
56       showCheckBox: false,
57       showFolders: false,
58       showPlusMinus: true,
59       showLines: true,
60       defaultAction: Rico.eventHandle(this,'nodeClick'),
61       height: '300px',
62       width: '300px',
63       leafIcon: 'rico-icon rico-doc'
64     });
65     Rico.extend(this.options, options || {});
66     this.id=id;
67     this.dataSource=url;
68     this.close=this.closePopup;
69     this.hoverSet = new Rico.HoverSet([]);
70   },
71
72   atLoad : function() {
73     this.treeDiv=document.createElement("div");
74     this.treeDiv.id=this.id;
75     this.treeDiv.className='ricoTree';
76     if (Rico.theme.treeContent) Rico.addClass(this.treeDiv,Rico.theme.treeContent);
77     this.treeDiv.style.height=this.options.height;
78     this.treeDiv.style.width=this.options.width;
79     this.createContainer();
80     this.content.className=Rico.theme.tree || 'ricoTreeContainer';
81     this.content.appendChild(this.treeDiv);
82     if (this.options.showCheckBox) {
83       this.buttonDiv=document.createElement("div");
84       this.buttonDiv.style.width=this.options.width;
85       this.buttonDiv.className='ricoTreeButtons';
86       if (Rico.getStyle(this.container,'position')=='absolute') {
87         var span=document.createElement("span");
88         span.innerHTML=RicoTranslate.getPhraseById('treeSave');
89         Rico.setStyle(span,{'float':'left',cursor:'pointer'});
90         this.buttonDiv.appendChild(span);
91         Rico.eventBind(span, 'click', Rico.eventHandle(this,'saveSelection'));
92       }
93       var span=document.createElement("span");
94       span.innerHTML=RicoTranslate.getPhraseById('treeClear');
95       Rico.setStyle(span,{'float':'right',cursor:'pointer'});
96       this.buttonDiv.appendChild(span);
97       this.content.appendChild(this.buttonDiv);
98       Rico.eventBind(span, 'click', Rico.eventHandle(this,'clrCheckBoxEvent'));
99     }
100     this.close();
101   },
102
103   setTreeDiv: function(divId) {
104     this.treeDiv = Rico.$(divId);
105     this.openPopup = function() {};
106   },
107
108   open: function() {
109     this.openPopup();
110     if (this.treeDiv.childNodes.length == 0 && this.dataSource) {
111       this.loadXMLDoc();
112     }
113   },
114
115   loadXMLDoc: function(branchPin) {
116     var parms = { id: this.id };
117     if (branchPin) parms.Parent=branchPin;
118     Rico.log('Tree loadXMLDoc: '+this.id);
119     var self=this;
120     new Rico.ajaxRequest(this.dataSource, {parameters:parms, method:'get', onComplete: function(request) { self.processResponse(request); } });
121   },
122
123   domID: function(nodeID,part) {
124     return 'RicoTree_'+part+'_'+this.id+'_'+nodeID;
125   },
126
127   processResponse: function(request) {
128     var response = request.responseXML.getElementsByTagName("ajax-response");
129     if (response == null || response.length != 1) return;
130     var rowsElement = response[0].getElementsByTagName('rows')[0];
131     var trs = rowsElement.getElementsByTagName("tr");
132     var rowdata=[];
133     for (var i=0; i < trs.length; i++) {
134       var cells = trs[i].getElementsByTagName("td");
135       if (cells.length < 5) continue;
136       var content=[];
137       content[5]=this.options.leafIcon;
138       for (var j=0; j<cells.length; j++) {
139         content[j]=Rico.getContentAsString(cells[j],true);
140       }
141       content[3] = content[3].match(/^0|L$/i) ? 0 : 1;
142       content[4] = parseInt(content[4]);
143       rowdata.push(content);
144     }
145     for (var i=0; i < rowdata.length; i++) {
146       var moreChildren=(i < rowdata.length-1) && (rowdata[i][0]==rowdata[i+1][0]);
147       this.addNode(rowdata[i][0],rowdata[i][1],rowdata[i][2],rowdata[i][3],rowdata[i][4],rowdata[i][5],!moreChildren);
148     }
149   },
150
151   addNode: function(parentId, nodeId, nodeDesc, isContainer, isSelectable, leafIcon, isLast) {
152     var parentNode=Rico.$(this.domID(parentId,'Parent'));
153     var parentChildren=Rico.$(this.domID(parentId,'Children'));
154     var level=parentNode ? parentNode.TreeLevel+1 : 0;
155     //alert("addNode at level " + level + " (" + nodeId + ")")
156     var tab = document.createElement("table");
157     var div = document.createElement("div");
158     div.id=this.domID(nodeId,'Children');
159     div.className='ricoTreeBranch';
160     div.style.display=parentNode ? 'none' : '';
161     tab.border=0;
162     tab.cellSpacing=0;
163     tab.cellPadding=0;
164     tab.id=this.domID(nodeId,'Parent');
165     tab.TreeLevel=level;
166     tab.TreeContainer=isContainer;
167     tab.TreeFetchedChildren=this.dataSource ? false : true;
168     var row=tab.insertRow(0);
169     var td=[];
170     for (var i=0; i<level-1; i++) {
171       td[i]=row.insertCell(-1);
172     }
173     if (level>1) {
174       var tdParent=parentNode.getElementsByTagName('td');
175       for (var i=0; i<level-2; i++) {
176         td[i].innerHTML=tdParent[i].innerHTML;
177       }
178       var img = document.createElement("div");
179       img.className='rico-icon rico-tree-'+(parentChildren.nextSibling && this.options.showLines ? "nodeline" : "nodeblank");
180       td[level-2].appendChild(img);
181     }
182     if (level>0) {
183       var suffix=isLast && this.options.showLines ? 'last' : '';
184       var prefix=this.options.showLines ? 'node' : '';
185       if (this.options.showPlusMinus && isContainer) {
186         var img = document.createElement("div");
187         img.name=nodeId;
188         img.style.cursor='pointer';
189         Rico.eventBind(img, 'click', Rico.eventHandle(this,'clickBranch'));
190         img.className='rico-icon rico-tree-'+prefix+"p"+suffix;
191         row.insertCell(-1).appendChild(img);
192       } else if (this.options.showLines) {
193         var img = document.createElement("div");
194         img.className='rico-icon rico-tree-node'+suffix;
195         row.insertCell(-1).appendChild(img);
196       }
197       if (this.options.showFolders && (isContainer || (leafIcon && leafIcon!='none'))) {
198         var img = document.createElement("div");
199         if (!isContainer) {
200           img.className=leafIcon;
201         } else {
202           img.name=nodeId;
203           img.style.cursor='pointer';
204           Rico.eventBind(img, 'click', Rico.eventHandle(this,'clickBranch'));
205           img.className='rico-icon rico-folderclosed';
206         }
207         row.insertCell(-1).appendChild(img);
208       }
209     }
210     if (isSelectable && this.options.showCheckBox) {
211       var chkbx=document.createElement("input");
212       chkbx.type="checkbox";
213       chkbx.value=nodeId;
214       row.insertCell(-1).appendChild(chkbx);
215     }
216
217     if (isSelectable && !this.options.showCheckBox) {
218       var span=document.createElement('a');
219       if (typeof isSelectable=='string') {
220         span.href=isSelectable;
221       } else {
222         span.href='javascript:void(0)';
223         Rico.eventBind(span, 'click', this.options.defaultAction);
224       }
225       this.hoverSet.add(span);
226     } else {
227       var span=document.createElement('p');
228     }
229     span.id=this.domID(nodeId,'Desc');
230     span.className='ricoTreeLevel'+level;
231     switch (this.options.nodeIdDisplay) {
232       case 'last': nodeDesc+=' ('+nodeId+')'; break;
233       case 'first': nodeDesc=nodeId+' - '+nodeDesc; break;
234       case 'tooltip': span.title=nodeId; break;
235     }
236         span.appendChild(document.createTextNode(nodeDesc));
237     row.insertCell(-1).appendChild(span);
238
239     var parent=parentChildren || this.treeDiv;
240     parent.appendChild(tab);
241     parent.appendChild(div);
242   },
243
244   nodeClick: function(e) {
245     var node=Rico.eventElement(e);
246     if (this.returnValue) {
247       var t=this.domID('','Desc');
248       this.returnValue(node.id.substr(t.length),node.innerHTML);
249     }
250     this.close();
251   },
252
253   saveSelection: function(e) {
254     if (this.returnValue) {
255       this.returnValue(this.getCheckedItems());
256     }
257     this.close();
258   },
259
260   getCheckedItems: function() {
261     var inp=this.treeDiv.getElementsByTagName('input');
262     var vals=[];
263     for (var i=0; i<inp.length; i++) {
264       if (inp[i].type=='checkbox' && inp[i].checked) {
265         vals.push(inp[i].value);
266       }
267     }
268     return vals;
269   },
270
271   setCheckBoxes: function(val) {
272     var inp=this.treeDiv.getElementsByTagName('input');
273     for (var i=0; i<inp.length; i++) {
274       if (inp[i].type=='checkbox') {
275         inp[i].checked=val;
276       }
277     }
278   },
279
280   clrCheckBoxEvent: function(e) {
281     Rico.eventStop(e);
282     this.setCheckBoxes(false);
283   },
284
285   clickBranch: function(e) {
286     var node=Rico.eventElement(e);
287     var tab=Rico.getParentByTagName(node,'table');
288     if (!tab || !tab.TreeContainer) return;
289     var a=tab.id.split('_');
290     a[1]='Children';
291     var childDiv=Rico.$(a.join('_'));
292     Rico.toggle(childDiv);
293     if (node.tagName=='DIV') {
294       var v=Rico.visible(childDiv);
295       if (node.className.match(/node(p|m)(last)?$/)) {
296         node.className=node.className.replace(/nodep|nodem/,'node'+(v ? 'm' : 'p'));
297       } else if (node.className.match(/folder(open|closed)$/)) {
298         node.className=node.className.replace(/folder(open|closed)/,'folder'+(v ? 'open' : 'closed'));
299       } else if (node.className.match(/\b(m|p)$/)) {
300         node.className=node.className.replace(/(p|m)$/,v ? 'm' : 'p');
301       }
302     }
303     if (!tab.TreeFetchedChildren) {
304       tab.TreeFetchedChildren=1;
305       this.loadXMLDoc(node.name);
306     }
307   }
308
309 };