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