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