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