initial import
[roojs1] / Roo / View.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Roo.View
14  * @extends Roo.util.Observable
15  * Create a "View" for an element based on a data model or UpdateManager and the supplied DomHelper template. 
16  * This class also supports single and multi selection modes. <br>
17  * Create a data model bound view:
18  <pre><code>
19  var store = new Roo.data.Store(...);
20
21  var view = new Roo.View("my-element",
22  '&lt;div id="{0}"&gt;{2} - {1}&lt;/div&gt;', // auto create template
23  {
24  singleSelect: true,
25  selectedClass: "ydataview-selected",
26  store: store
27  });
28
29  // listen for node click?
30  view.on("click", function(vw, index, node, e){
31  alert('Node "' + node.id + '" at index: ' + index + " was clicked.");
32  });
33
34  // load XML data
35  dataModel.load("foobar.xml");
36  </code></pre>
37  For an example of creating a JSON/UpdateManager view, see {@link Roo.JsonView}.
38  * <br><br>
39  * <b>Note: The root of your template must be a single node. Table/row implementations may work but are not supported due to
40  * IE"s limited insertion support with tables and Opera"s faulty event bubbling.</b>
41  * @constructor
42  * Create a new View
43  * @param {String/HTMLElement/Element} container The container element where the view is to be rendered.
44  * @param {String/DomHelper.Template} tpl The rendering template or a string to create a template with
45  * @param {Object} config The config object
46  */
47 Roo.View = function(container, tpl, config){
48     this.el = Roo.get(container);
49     if(typeof tpl == "string"){
50         tpl = new Roo.Template(tpl);
51     }
52     tpl.compile();
53     /**
54      * The template used by this View
55      * @type {Roo.DomHelper.Template}
56      */
57     this.tpl = tpl;
58
59     Roo.apply(this, config);
60
61     /** @private */
62     this.addEvents({
63     /**
64      * @event beforeclick
65      * Fires before a click is processed. Returns false to cancel the default action.
66      * @param {Roo.View} this
67      * @param {Number} index The index of the target node
68      * @param {HTMLElement} node The target node
69      * @param {Roo.EventObject} e The raw event object
70      */
71         "beforeclick" : true,
72     /**
73      * @event click
74      * Fires when a template node is clicked.
75      * @param {Roo.View} this
76      * @param {Number} index The index of the target node
77      * @param {HTMLElement} node The target node
78      * @param {Roo.EventObject} e The raw event object
79      */
80         "click" : true,
81     /**
82      * @event dblclick
83      * Fires when a template node is double clicked.
84      * @param {Roo.View} this
85      * @param {Number} index The index of the target node
86      * @param {HTMLElement} node The target node
87      * @param {Roo.EventObject} e The raw event object
88      */
89         "dblclick" : true,
90     /**
91      * @event contextmenu
92      * Fires when a template node is right clicked.
93      * @param {Roo.View} this
94      * @param {Number} index The index of the target node
95      * @param {HTMLElement} node The target node
96      * @param {Roo.EventObject} e The raw event object
97      */
98         "contextmenu" : true,
99     /**
100      * @event selectionchange
101      * Fires when the selected nodes change.
102      * @param {Roo.View} this
103      * @param {Array} selections Array of the selected nodes
104      */
105         "selectionchange" : true,
106
107     /**
108      * @event beforeselect
109      * Fires before a selection is made. If any handlers return false, the selection is cancelled.
110      * @param {Roo.View} this
111      * @param {HTMLElement} node The node to be selected
112      * @param {Array} selections Array of currently selected nodes
113      */
114         "beforeselect" : true
115     });
116
117     this.el.on({
118         "click": this.onClick,
119         "dblclick": this.onDblClick,
120         "contextmenu": this.onContextMenu,
121         scope:this
122     });
123
124     this.selections = [];
125     this.nodes = [];
126     this.cmp = new Roo.CompositeElementLite([]);
127     if(this.store){
128         this.store = Roo.factory(this.store, Roo.data);
129         this.setStore(this.store, true);
130     }
131     Roo.View.superclass.constructor.call(this);
132 };
133
134 Roo.extend(Roo.View, Roo.util.Observable, {
135     /**
136      * The css class to add to selected nodes
137      * @type {Roo.DomHelper.Template}
138      */
139     selectedClass : "x-view-selected",
140     
141     emptyText : "",
142     /**
143      * Returns the element this view is bound to.
144      * @return {Roo.Element}
145      */
146     getEl : function(){
147         return this.el;
148     },
149
150     /**
151      * Refreshes the view.
152      */
153     refresh : function(){
154         var t = this.tpl;
155         this.clearSelections();
156         this.el.update("");
157         var html = [];
158         var records = this.store.getRange();
159         if(records.length < 1){
160             this.el.update(this.emptyText);
161             return;
162         }
163         for(var i = 0, len = records.length; i < len; i++){
164             var data = this.prepareData(records[i].data, i, records[i]);
165             html[html.length] = t.apply(data);
166         }
167         this.el.update(html.join(""));
168         this.nodes = this.el.dom.childNodes;
169         this.updateIndexes(0);
170     },
171
172     /**
173      * Function to override to reformat the data that is sent to
174      * the template for each node.
175      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
176      * a JSON object for an UpdateManager bound view).
177      */
178     prepareData : function(data){
179         return data;
180     },
181
182     onUpdate : function(ds, record){
183         this.clearSelections();
184         var index = this.store.indexOf(record);
185         var n = this.nodes[index];
186         this.tpl.insertBefore(n, this.prepareData(record.data));
187         n.parentNode.removeChild(n);
188         this.updateIndexes(index, index);
189     },
190
191     onAdd : function(ds, records, index){
192         this.clearSelections();
193         if(this.nodes.length == 0){
194             this.refresh();
195             return;
196         }
197         var n = this.nodes[index];
198         for(var i = 0, len = records.length; i < len; i++){
199             var d = this.prepareData(records[i].data);
200             if(n){
201                 this.tpl.insertBefore(n, d);
202             }else{
203                 this.tpl.append(this.el, d);
204             }
205         }
206         this.updateIndexes(index);
207     },
208
209     onRemove : function(ds, record, index){
210         this.clearSelections();
211         this.el.dom.removeChild(this.nodes[index]);
212         this.updateIndexes(index);
213     },
214
215     /**
216      * Refresh an individual node.
217      * @param {Number} index
218      */
219     refreshNode : function(index){
220         this.onUpdate(this.store, this.store.getAt(index));
221     },
222
223     updateIndexes : function(startIndex, endIndex){
224         var ns = this.nodes;
225         startIndex = startIndex || 0;
226         endIndex = endIndex || ns.length - 1;
227         for(var i = startIndex; i <= endIndex; i++){
228             ns[i].nodeIndex = i;
229         }
230     },
231
232     /**
233      * Changes the data store this view uses and refresh the view.
234      * @param {Store} store
235      */
236     setStore : function(store, initial){
237         if(!initial && this.store){
238             this.store.un("datachanged", this.refresh);
239             this.store.un("add", this.onAdd);
240             this.store.un("remove", this.onRemove);
241             this.store.un("update", this.onUpdate);
242             this.store.un("clear", this.refresh);
243         }
244         if(store){
245           
246             store.on("datachanged", this.refresh, this);
247             store.on("add", this.onAdd, this);
248             store.on("remove", this.onRemove, this);
249             store.on("update", this.onUpdate, this);
250             store.on("clear", this.refresh, this);
251         }
252         
253         if(store){
254             this.refresh();
255         }
256     },
257
258     /**
259      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
260      * @param {HTMLElement} node
261      * @return {HTMLElement} The template node
262      */
263     findItemFromChild : function(node){
264         var el = this.el.dom;
265         if(!node || node.parentNode == el){
266                     return node;
267             }
268             var p = node.parentNode;
269             while(p && p != el){
270             if(p.parentNode == el){
271                 return p;
272             }
273             p = p.parentNode;
274         }
275             return null;
276     },
277
278     /** @ignore */
279     onClick : function(e){
280         var item = this.findItemFromChild(e.getTarget());
281         if(item){
282             var index = this.indexOf(item);
283             if(this.onItemClick(item, index, e) !== false){
284                 this.fireEvent("click", this, index, item, e);
285             }
286         }else{
287             this.clearSelections();
288         }
289     },
290
291     /** @ignore */
292     onContextMenu : function(e){
293         var item = this.findItemFromChild(e.getTarget());
294         if(item){
295             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
296         }
297     },
298
299     /** @ignore */
300     onDblClick : function(e){
301         var item = this.findItemFromChild(e.getTarget());
302         if(item){
303             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
304         }
305     },
306
307     onItemClick : function(item, index, e){
308         if(this.fireEvent("beforeclick", this, index, item, e) === false){
309             return false;
310         }
311         if(this.multiSelect || this.singleSelect){
312             if(this.multiSelect && e.shiftKey && this.lastSelection){
313                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
314             }else{
315                 this.select(item, this.multiSelect && e.ctrlKey);
316                 this.lastSelection = item;
317             }
318             e.preventDefault();
319         }
320         return true;
321     },
322
323     /**
324      * Get the number of selected nodes.
325      * @return {Number}
326      */
327     getSelectionCount : function(){
328         return this.selections.length;
329     },
330
331     /**
332      * Get the currently selected nodes.
333      * @return {Array} An array of HTMLElements
334      */
335     getSelectedNodes : function(){
336         return this.selections;
337     },
338
339     /**
340      * Get the indexes of the selected nodes.
341      * @return {Array}
342      */
343     getSelectedIndexes : function(){
344         var indexes = [], s = this.selections;
345         for(var i = 0, len = s.length; i < len; i++){
346             indexes.push(s[i].nodeIndex);
347         }
348         return indexes;
349     },
350
351     /**
352      * Clear all selections
353      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
354      */
355     clearSelections : function(suppressEvent){
356         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
357             this.cmp.elements = this.selections;
358             this.cmp.removeClass(this.selectedClass);
359             this.selections = [];
360             if(!suppressEvent){
361                 this.fireEvent("selectionchange", this, this.selections);
362             }
363         }
364     },
365
366     /**
367      * Returns true if the passed node is selected
368      * @param {HTMLElement/Number} node The node or node index
369      * @return {Boolean}
370      */
371     isSelected : function(node){
372         var s = this.selections;
373         if(s.length < 1){
374             return false;
375         }
376         node = this.getNode(node);
377         return s.indexOf(node) !== -1;
378     },
379
380     /**
381      * Selects nodes.
382      * @param {Array/HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node, id of a template node or an array of any of those to select
383      * @param {Boolean} keepExisting (optional) true to keep existing selections
384      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
385      */
386     select : function(nodeInfo, keepExisting, suppressEvent){
387         if(nodeInfo instanceof Array){
388             if(!keepExisting){
389                 this.clearSelections(true);
390             }
391             for(var i = 0, len = nodeInfo.length; i < len; i++){
392                 this.select(nodeInfo[i], true, true);
393             }
394         } else{
395             var node = this.getNode(nodeInfo);
396             if(node && !this.isSelected(node)){
397                 if(!keepExisting){
398                     this.clearSelections(true);
399                 }
400                 if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
401                     Roo.fly(node).addClass(this.selectedClass);
402                     this.selections.push(node);
403                     if(!suppressEvent){
404                         this.fireEvent("selectionchange", this, this.selections);
405                     }
406                 }
407             }
408         }
409     },
410
411     /**
412      * Gets a template node.
413      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
414      * @return {HTMLElement} The node or null if it wasn't found
415      */
416     getNode : function(nodeInfo){
417         if(typeof nodeInfo == "string"){
418             return document.getElementById(nodeInfo);
419         }else if(typeof nodeInfo == "number"){
420             return this.nodes[nodeInfo];
421         }
422         return nodeInfo;
423     },
424
425     /**
426      * Gets a range template nodes.
427      * @param {Number} startIndex
428      * @param {Number} endIndex
429      * @return {Array} An array of nodes
430      */
431     getNodes : function(start, end){
432         var ns = this.nodes;
433         start = start || 0;
434         end = typeof end == "undefined" ? ns.length - 1 : end;
435         var nodes = [];
436         if(start <= end){
437             for(var i = start; i <= end; i++){
438                 nodes.push(ns[i]);
439             }
440         } else{
441             for(var i = start; i >= end; i--){
442                 nodes.push(ns[i]);
443             }
444         }
445         return nodes;
446     },
447
448     /**
449      * Finds the index of the passed node
450      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
451      * @return {Number} The index of the node or -1
452      */
453     indexOf : function(node){
454         node = this.getNode(node);
455         if(typeof node.nodeIndex == "number"){
456             return node.nodeIndex;
457         }
458         var ns = this.nodes;
459         for(var i = 0, len = ns.length; i < len; i++){
460             if(ns[i] == node){
461                 return i;
462             }
463         }
464         return -1;
465     }
466 });