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