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