Fix wheel scrolling on LiveGrid content
[infodrom/rico3] / minsrc / ricoTree.js
1 /*
2  *  (c) 2005-2011 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2011 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     var self=this;
71     Rico.onLoad(function() { self.atLoad(); })
72   },
73
74   atLoad : function() {
75     this.treeDiv=document.createElement("div");
76     this.treeDiv.className='ricoTree';
77     if (Rico.theme.treeContent) Rico.addClass(this.treeDiv,Rico.theme.treeContent);
78     var elem=Rico.$(this.id);
79     if (elem) {
80       this.setDiv(elem, { position: 'auto' });
81     } else {
82       this.treeDiv.id=this.id;
83       this.createContainer();
84     }
85     this.treeDiv.style.height=this.options.height;
86     this.treeDiv.style.width=this.options.width;
87     this.content.className=Rico.theme.tree || 'ricoTreeContainer';
88     this.content.appendChild(this.treeDiv);
89     if (this.options.showCheckBox) {
90       this.buttonDiv=document.createElement("div");
91       this.buttonDiv.style.width=this.options.width;
92       this.buttonDiv.className='ricoTreeButtons';
93       if (Rico.getStyle(this.container,'position')=='absolute') {
94         var span=document.createElement("span");
95         span.innerHTML=Rico.getPhraseById('treeSave');
96         Rico.setStyle(span,{'float':'left',cursor:'pointer'});
97         this.buttonDiv.appendChild(span);
98         Rico.eventBind(span, 'click', Rico.eventHandle(this,'saveSelection'));
99       }
100       var span=document.createElement("span");
101       span.innerHTML=Rico.getPhraseById('treeClear');
102       Rico.setStyle(span,{'float':'right',cursor:'pointer'});
103       this.buttonDiv.appendChild(span);
104       this.content.appendChild(this.buttonDiv);
105       Rico.eventBind(span, 'click', Rico.eventHandle(this,'clrCheckBoxEvent'));
106     }
107     if (this.position == 'absolute') this.close();
108   },
109
110   setTreeDiv: function(divId) {
111     this.treeDiv = Rico.$(divId);
112     this.openPopup = function() {};
113   },
114
115   open: function() {
116     this.openPopup();
117     if (this.treeDiv.childNodes.length == 0 && this.dataSource) {
118       this.loadXMLDoc();
119     }
120   },
121
122   loadXMLDoc: function(branchPin) {
123     var parms = { id: this.id };
124     if (branchPin) parms.Parent=branchPin;
125     Rico.log('Tree loadXMLDoc: '+this.id);
126     var self=this;
127     new Rico.ajaxRequest(this.dataSource, {parameters:parms, method:'get', onComplete: function(request) { self.processResponse(request); } });
128   },
129
130   domID: function(nodeID,part) {
131     return 'RicoTree_'+part+'_'+this.id+'_'+nodeID;
132   },
133
134   processResponse: function(request) {
135     var response = request.responseXML.getElementsByTagName("ajax-response");
136     if (response == null || response.length != 1) return;
137     var rowsElement = response[0].getElementsByTagName('rows')[0];
138     var trs = rowsElement.getElementsByTagName("tr");
139     var rowdata=[];
140     for (var i=0; i < trs.length; i++) {
141       var cells = trs[i].getElementsByTagName("td");
142       if (cells.length < 5) continue;
143       var content=[];
144       content[5]=this.options.leafIcon;
145       for (var j=0; j<cells.length; j++) {
146         content[j]=Rico.getContentAsString(cells[j],true);
147       }
148       content[3] = content[3].match(/^0|L$/i) ? 0 : 1;
149       content[4] = parseInt(content[4]);
150       rowdata.push(content);
151     }
152     for (var i=0; i < rowdata.length; i++) {
153       var moreChildren=(i < rowdata.length-1) && (rowdata[i][0]==rowdata[i+1][0]);
154       this.addNode(rowdata[i][0],rowdata[i][1],rowdata[i][2],rowdata[i][3],rowdata[i][4],rowdata[i][5],!moreChildren);
155     }
156   },
157
158   addNode: function(parentId, nodeId, nodeDesc, isContainer, isSelectable, leafIcon, isLast) {
159     var parentNode=Rico.$(this.domID(parentId,'Parent'));
160     var parentChildren=Rico.$(this.domID(parentId,'Children'));
161     var level=parentNode ? parentNode.TreeLevel+1 : 0;
162     //alert("addNode at level " + level + " (" + nodeId + ")")
163     var tab = document.createElement("table");
164     var div = document.createElement("div");
165     div.id=this.domID(nodeId,'Children');
166     div.className='ricoTreeBranch';
167     div.style.display=parentNode ? 'none' : '';
168     tab.border=0;
169     tab.cellSpacing=0;
170     tab.cellPadding=0;
171     tab.id=this.domID(nodeId,'Parent');
172     tab.TreeLevel=level;
173     tab.TreeContainer=isContainer;
174     tab.TreeFetchedChildren=this.dataSource ? false : true;
175     var row=tab.insertRow(0);
176     var td=[];
177     for (var i=0; i<level-1; i++) {
178       td[i]=row.insertCell(-1);
179     }
180     if (level>1) {
181       var tdParent=parentNode.getElementsByTagName('td');
182       for (var i=0; i<level-2; i++) {
183         td[i].innerHTML=tdParent[i].innerHTML;
184       }
185       var img = document.createElement("div");
186       img.className='rico-icon rico-tree-'+(parentChildren.nextSibling && this.options.showLines ? "nodeline" : "nodeblank");
187       td[level-2].appendChild(img);
188     }
189     if (level>0) {
190       var suffix=isLast && this.options.showLines ? 'last' : '';
191       var prefix=this.options.showLines ? 'node' : '';
192       if (this.options.showPlusMinus && isContainer) {
193         var img = document.createElement("div");
194         img.name=nodeId;
195         img.style.cursor='pointer';
196         Rico.eventBind(img, 'click', Rico.eventHandle(this,'clickBranch'));
197         img.className='rico-icon rico-tree-'+prefix+"p"+suffix;
198         row.insertCell(-1).appendChild(img);
199       } else if (this.options.showLines) {
200         var img = document.createElement("div");
201         img.className='rico-icon rico-tree-node'+suffix;
202         row.insertCell(-1).appendChild(img);
203       }
204       if (this.options.showFolders && (isContainer || (leafIcon && leafIcon!='none'))) {
205         var img = document.createElement("div");
206         if (!isContainer) {
207           img.className=leafIcon;
208         } else {
209           img.name=nodeId;
210           img.style.cursor='pointer';
211           Rico.eventBind(img, 'click', Rico.eventHandle(this,'clickBranch'));
212           img.className='rico-icon rico-folderclosed';
213         }
214         row.insertCell(-1).appendChild(img);
215       }
216     }
217     if (isSelectable && this.options.showCheckBox) {
218       var chkbx=document.createElement("input");
219       chkbx.type="checkbox";
220       chkbx.value=nodeId;
221       row.insertCell(-1).appendChild(chkbx);
222     }
223
224     if (isSelectable && !this.options.showCheckBox) {
225       var span=document.createElement('a');
226       if (typeof isSelectable=='string') {
227         span.href=isSelectable;
228       } else {
229         span.href='javascript:void(0)';
230         Rico.eventBind(span, 'click', this.options.defaultAction);
231       }
232       this.hoverSet.add(span);
233     } else {
234       var span=document.createElement('p');
235     }
236     span.id=this.domID(nodeId,'Desc');
237     span.className='ricoTreeLevel'+level;
238     switch (this.options.nodeIdDisplay) {
239       case 'last': nodeDesc+=' ('+nodeId+')'; break;
240       case 'first': nodeDesc=nodeId+' - '+nodeDesc; break;
241       case 'tooltip': span.title=nodeId; break;
242     }
243         span.appendChild(document.createTextNode(nodeDesc));
244     row.insertCell(-1).appendChild(span);
245
246     var parent=parentChildren || this.treeDiv;
247     parent.appendChild(tab);
248     parent.appendChild(div);
249   },
250
251   nodeClick: function(e) {
252     var node=Rico.eventElement(e);
253     if (this.returnValue) {
254       var t=this.domID('','Desc');
255       this.returnValue(node.id.substr(t.length),node.innerHTML);
256     }
257     this.close();
258   },
259
260   saveSelection: function(e) {
261     if (this.returnValue) {
262       this.returnValue(this.getCheckedItems());
263     }
264     this.close();
265   },
266
267   getCheckedItems: function() {
268     var inp=this.treeDiv.getElementsByTagName('input');
269     var vals=[];
270     for (var i=0; i<inp.length; i++) {
271       if (inp[i].type=='checkbox' && inp[i].checked) {
272         vals.push(inp[i].value);
273       }
274     }
275     return vals;
276   },
277
278   setCheckBoxes: function(val) {
279     var inp=this.treeDiv.getElementsByTagName('input');
280     for (var i=0; i<inp.length; i++) {
281       if (inp[i].type=='checkbox') {
282         inp[i].checked=val;
283       }
284     }
285   },
286
287   clrCheckBoxEvent: function(e) {
288     Rico.eventStop(e);
289     this.setCheckBoxes(false);
290   },
291
292   clickBranch: function(e) {
293     var node=Rico.eventElement(e);
294     var tab=Rico.getParentByTagName(node,'table');
295     if (!tab || !tab.TreeContainer) return;
296     var a=tab.id.split('_');
297     a[1]='Children';
298     var childDiv=Rico.$(a.join('_'));
299     Rico.toggle(childDiv);
300     if (node.tagName=='DIV') {
301       var v=Rico.visible(childDiv);
302       if (node.className.match(/node(p|m)(last)?$/)) {
303         node.className=node.className.replace(/nodep|nodem/,'node'+(v ? 'm' : 'p'));
304       } else if (node.className.match(/folder(open|closed)$/)) {
305         node.className=node.className.replace(/folder(open|closed)/,'folder'+(v ? 'open' : 'closed'));
306       } else if (node.className.match(/\b(m|p)$/)) {
307         node.className=node.className.replace(/(p|m)$/,v ? 'm' : 'p');
308       }
309     }
310     if (!tab.TreeFetchedChildren) {
311       tab.TreeFetchedChildren=1;
312       this.loadXMLDoc(node.name);
313     }
314   }
315
316 };