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