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