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