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