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