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({
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     if ( this.footer && this.footer.xtype) {
74          
75          
76         
77         this.wrapEl = this.el.wrap();
78
79         this.footer.dataSource = this.store
80         this.footer.container = this.wrapEl;
81         this.footer = Roo.factory(this.footer, Roo);
82     }
83
84      
85     /** @private */
86     this.addEvents({
87         /**
88          * @event beforeclick
89          * Fires before a click is processed. Returns false to cancel the default action.
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             "beforeclick" : true,
96         /**
97          * @event click
98          * Fires when a template node is 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             "click" : true,
105         /**
106          * @event dblclick
107          * Fires when a template node is double 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             "dblclick" : true,
114         /**
115          * @event contextmenu
116          * Fires when a template node is right clicked.
117          * @param {Roo.View} this
118          * @param {Number} index The index of the target node
119          * @param {HTMLElement} node The target node
120          * @param {Roo.EventObject} e The raw event object
121          */
122             "contextmenu" : true,
123         /**
124          * @event selectionchange
125          * Fires when the selected nodes change.
126          * @param {Roo.View} this
127          * @param {Array} selections Array of the selected nodes
128          */
129             "selectionchange" : true,
130     
131         /**
132          * @event beforeselect
133          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
134          * @param {Roo.View} this
135          * @param {HTMLElement} node The node to be selected
136          * @param {Array} selections Array of currently selected nodes
137          */
138             "beforeselect" : true,
139         /**
140          * @event preparedata
141          * Fires on every row to render, to allow you to change the data.
142          * @param {Roo.View} this
143          * @param {Object} data to be rendered (change this)
144          */
145           "preparedata" : true
146         });
147
148     this.el.on({
149         "click": this.onClick,
150         "dblclick": this.onDblClick,
151         "contextmenu": this.onContextMenu,
152         scope:this
153     });
154
155     this.selections = [];
156     this.nodes = [];
157     this.cmp = new Roo.CompositeElementLite([]);
158     if(this.store){
159         this.store = Roo.factory(this.store, Roo.data);
160         this.setStore(this.store, true);
161     }
162     Roo.View.superclass.constructor.call(this);
163     
164     
165      
166     
167 };
168
169 Roo.extend(Roo.View, Roo.util.Observable, {
170     
171      /**
172      * @cfg {Roo.data.Store} store Data store to load data from.
173      */
174     store : false,
175     
176     /**
177      * @cfg {String|Roo.Element} el The container element.
178      */
179     el : '',
180     
181     /**
182      * @cfg {String|Roo.Template} tpl The template used by this View 
183      */
184     tpl : false,
185     /**
186      * @cfg {String} dataName the named area of the template to use as the data area
187      *                          Works with domtemplates roo-name="name"
188      */
189     dataName: false,
190     /**
191      * @cfg {String} selectedClass The css class to add to selected nodes
192      */
193     selectedClass : "x-view-selected",
194      /**
195      * @cfg {String} emptyText The empty text to show when nothing is loaded.
196      */
197     emptyText : "",
198     
199     /**
200      * @cfg {String} text to display on mask (default Loading)
201      */
202     mask : false,
203     /**
204      * @cfg {Boolean} multiSelect Allow multiple selection
205      */
206     multiSelect : false,
207     /**
208      * @cfg {Boolean} singleSelect Allow single selection
209      */
210     singleSelect:  false,
211     
212     /**
213      * @cfg {Boolean} toggleSelect - selecting 
214      */
215     toggleSelect : false,
216     
217     /**
218      * Returns the element this view is bound to.
219      * @return {Roo.Element}
220      */
221     getEl : function(){
222         return this.el;
223     },
224     
225     render : function(a,b, panel)
226     {
227         
228        
229
230     },
231     
232
233     /**
234      * Refreshes the view. - called by datachanged on the store. - do not call directly.
235      */
236     refresh : function(){
237         var t = this.tpl;
238         
239         // if we are using something like 'domtemplate', then
240         // the what gets used is:
241         // t.applySubtemplate(NAME, data, wrapping data..)
242         // the outer template then get' applied with
243         //     the store 'extra data'
244         // and the body get's added to the
245         //      roo-name="data" node?
246         //      <span class='roo-tpl-{name}'></span> ?????
247         
248         
249         
250         this.clearSelections();
251         this.el.update("");
252         var html = [];
253         var records = this.store.getRange();
254         if(records.length < 1) {
255             
256             // is this valid??  = should it render a template??
257             
258             this.el.update(this.emptyText);
259             return;
260         }
261         var el = this.el;
262         if (this.dataName) {
263             this.el.update(t.apply(this.store.meta)); //????
264             el = this.el.child('.roo-tpl-' + this.dataName);
265         }
266         
267         for(var i = 0, len = records.length; i < len; i++){
268             var data = this.prepareData(records[i].data, i, records[i]);
269             this.fireEvent("preparedata", this, data, i, records[i]);
270             html[html.length] = Roo.util.Format.trim(
271                 this.dataName ?
272                     t.applySubtemplate(this.dataName, data, this.store.meta) :
273                     t.apply(data)
274             );
275         }
276         
277         
278         
279         el.update(html.join(""));
280         this.nodes = el.dom.childNodes;
281         this.updateIndexes(0);
282     },
283
284     /**
285      * Function to override to reformat the data that is sent to
286      * the template for each node.
287      * DEPRICATED - use the preparedata event handler.
288      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
289      * a JSON object for an UpdateManager bound view).
290      */
291     prepareData : function(data, index, record)
292     {
293         this.fireEvent("preparedata", this, data, index, record);
294         return data;
295     },
296
297     onUpdate : function(ds, record){
298         this.clearSelections();
299         var index = this.store.indexOf(record);
300         var n = this.nodes[index];
301         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
302         n.parentNode.removeChild(n);
303         this.updateIndexes(index, index);
304     },
305
306     
307     
308 // --------- FIXME     
309     onAdd : function(ds, records, index)
310     {
311         this.clearSelections();
312         if(this.nodes.length == 0){
313             this.refresh();
314             return;
315         }
316         var n = this.nodes[index];
317         for(var i = 0, len = records.length; i < len; i++){
318             var d = this.prepareData(records[i].data, i, records[i]);
319             if(n){
320                 this.tpl.insertBefore(n, d);
321             }else{
322                 
323                 this.tpl.append(this.el, d);
324             }
325         }
326         this.updateIndexes(index);
327     },
328
329     onRemove : function(ds, record, index){
330         this.clearSelections();
331         var el = this.dataName  ?
332             this.el.child('.roo-tpl-' + this.dataName) :
333             this.el; 
334         el.dom.removeChild(this.nodes[index]);
335         this.updateIndexes(index);
336     },
337
338     /**
339      * Refresh an individual node.
340      * @param {Number} index
341      */
342     refreshNode : function(index){
343         this.onUpdate(this.store, this.store.getAt(index));
344     },
345
346     updateIndexes : function(startIndex, endIndex){
347         var ns = this.nodes;
348         startIndex = startIndex || 0;
349         endIndex = endIndex || ns.length - 1;
350         for(var i = startIndex; i <= endIndex; i++){
351             ns[i].nodeIndex = i;
352         }
353     },
354
355     /**
356      * Changes the data store this view uses and refresh the view.
357      * @param {Store} store
358      */
359     setStore : function(store, initial){
360         if(!initial && this.store){
361             this.store.un("datachanged", this.refresh);
362             this.store.un("add", this.onAdd);
363             this.store.un("remove", this.onRemove);
364             this.store.un("update", this.onUpdate);
365             this.store.un("clear", this.refresh);
366             this.store.un("beforeload", this.onBeforeLoad);
367             this.store.un("load", this.onLoad);
368             this.store.un("loadexception", this.onLoad);
369         }
370         if(store){
371           
372             store.on("datachanged", this.refresh, this);
373             store.on("add", this.onAdd, this);
374             store.on("remove", this.onRemove, this);
375             store.on("update", this.onUpdate, this);
376             store.on("clear", this.refresh, this);
377             store.on("beforeload", this.onBeforeLoad, this);
378             store.on("load", this.onLoad, this);
379             store.on("loadexception", this.onLoad, this);
380         }
381         
382         if(store){
383             this.refresh();
384         }
385     },
386     /**
387      * onbeforeLoad - masks the loading area.
388      *
389      */
390     onBeforeLoad : function()
391     {
392         this.el.update("");
393         this.el.mask(this.mask ? this.mask : "Loading" ); 
394     },
395     onLoad : function ()
396     {
397         this.el.unmask();
398     },
399     
400
401     /**
402      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
403      * @param {HTMLElement} node
404      * @return {HTMLElement} The template node
405      */
406     findItemFromChild : function(node){
407         var el = this.dataName  ?
408             this.el.child('.roo-tpl-' + this.dataName,true) :
409             this.el.dom; 
410         
411         if(!node || node.parentNode == el){
412                     return node;
413             }
414             var p = node.parentNode;
415             while(p && p != el){
416             if(p.parentNode == el){
417                 return p;
418             }
419             p = p.parentNode;
420         }
421             return null;
422     },
423
424     /** @ignore */
425     onClick : function(e){
426         var item = this.findItemFromChild(e.getTarget());
427         if(item){
428             var index = this.indexOf(item);
429             if(this.onItemClick(item, index, e) !== false){
430                 this.fireEvent("click", this, index, item, e);
431             }
432         }else{
433             this.clearSelections();
434         }
435     },
436
437     /** @ignore */
438     onContextMenu : function(e){
439         var item = this.findItemFromChild(e.getTarget());
440         if(item){
441             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
442         }
443     },
444
445     /** @ignore */
446     onDblClick : function(e){
447         var item = this.findItemFromChild(e.getTarget());
448         if(item){
449             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
450         }
451     },
452
453     onItemClick : function(item, index, e)
454     {
455         if(this.fireEvent("beforeclick", this, index, item, e) === false){
456             return false;
457         }
458         if (this.toggleSelect) {
459             var m = this.isSelected(item) ? 'unselect' : 'select';
460             Roo.log(m);
461             var _t = this;
462             _t[m](item, true, false);
463             return true;
464         }
465         if(this.multiSelect || this.singleSelect){
466             if(this.multiSelect && e.shiftKey && this.lastSelection){
467                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
468             }else{
469                 this.select(item, this.multiSelect && e.ctrlKey);
470                 this.lastSelection = item;
471             }
472             e.preventDefault();
473         }
474         return true;
475     },
476
477     /**
478      * Get the number of selected nodes.
479      * @return {Number}
480      */
481     getSelectionCount : function(){
482         return this.selections.length;
483     },
484
485     /**
486      * Get the currently selected nodes.
487      * @return {Array} An array of HTMLElements
488      */
489     getSelectedNodes : function(){
490         return this.selections;
491     },
492
493     /**
494      * Get the indexes of the selected nodes.
495      * @return {Array}
496      */
497     getSelectedIndexes : function(){
498         var indexes = [], s = this.selections;
499         for(var i = 0, len = s.length; i < len; i++){
500             indexes.push(s[i].nodeIndex);
501         }
502         return indexes;
503     },
504
505     /**
506      * Clear all selections
507      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
508      */
509     clearSelections : function(suppressEvent){
510         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
511             this.cmp.elements = this.selections;
512             this.cmp.removeClass(this.selectedClass);
513             this.selections = [];
514             if(!suppressEvent){
515                 this.fireEvent("selectionchange", this, this.selections);
516             }
517         }
518     },
519
520     /**
521      * Returns true if the passed node is selected
522      * @param {HTMLElement/Number} node The node or node index
523      * @return {Boolean}
524      */
525     isSelected : function(node){
526         var s = this.selections;
527         if(s.length < 1){
528             return false;
529         }
530         node = this.getNode(node);
531         return s.indexOf(node) !== -1;
532     },
533
534     /**
535      * Selects nodes.
536      * @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
537      * @param {Boolean} keepExisting (optional) true to keep existing selections
538      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
539      */
540     select : function(nodeInfo, keepExisting, suppressEvent){
541         if(nodeInfo instanceof Array){
542             if(!keepExisting){
543                 this.clearSelections(true);
544             }
545             for(var i = 0, len = nodeInfo.length; i < len; i++){
546                 this.select(nodeInfo[i], true, true);
547             }
548             return;
549         } 
550         var node = this.getNode(nodeInfo);
551         if(!node || this.isSelected(node)){
552             return; // already selected.
553         }
554         if(!keepExisting){
555             this.clearSelections(true);
556         }
557         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
558             Roo.fly(node).addClass(this.selectedClass);
559             this.selections.push(node);
560             if(!suppressEvent){
561                 this.fireEvent("selectionchange", this, this.selections);
562             }
563         }
564         
565         
566     },
567       /**
568      * Unselects nodes.
569      * @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
570      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
571      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
572      */
573     unselect : function(nodeInfo, keepExisting, suppressEvent)
574     {
575         if(nodeInfo instanceof Array){
576             Roo.each(this.selections, function(s) {
577                 this.unselect(s, nodeInfo);
578             }, this);
579             return;
580         }
581         var node = this.getNode(nodeInfo);
582         if(!node || !this.isSelected(node)){
583             Roo.log("not selected");
584             return; // not selected.
585         }
586         // fireevent???
587         var ns = [];
588         Roo.each(this.selections, function(s) {
589             if (s == node ) {
590                 Roo.fly(node).removeClass(this.selectedClass);
591
592                 return;
593             }
594             ns.push(s);
595         },this);
596         
597         this.selections= ns;
598         this.fireEvent("selectionchange", this, this.selections);
599     },
600
601     /**
602      * Gets a template node.
603      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
604      * @return {HTMLElement} The node or null if it wasn't found
605      */
606     getNode : function(nodeInfo){
607         if(typeof nodeInfo == "string"){
608             return document.getElementById(nodeInfo);
609         }else if(typeof nodeInfo == "number"){
610             return this.nodes[nodeInfo];
611         }
612         return nodeInfo;
613     },
614
615     /**
616      * Gets a range template nodes.
617      * @param {Number} startIndex
618      * @param {Number} endIndex
619      * @return {Array} An array of nodes
620      */
621     getNodes : function(start, end){
622         var ns = this.nodes;
623         start = start || 0;
624         end = typeof end == "undefined" ? ns.length - 1 : end;
625         var nodes = [];
626         if(start <= end){
627             for(var i = start; i <= end; i++){
628                 nodes.push(ns[i]);
629             }
630         } else{
631             for(var i = start; i >= end; i--){
632                 nodes.push(ns[i]);
633             }
634         }
635         return nodes;
636     },
637
638     /**
639      * Finds the index of the passed node
640      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
641      * @return {Number} The index of the node or -1
642      */
643     indexOf : function(node){
644         node = this.getNode(node);
645         if(typeof node.nodeIndex == "number"){
646             return node.nodeIndex;
647         }
648         var ns = this.nodes;
649         for(var i = 0, len = ns.length; i < len; i++){
650             if(ns[i] == node){
651                 return i;
652             }
653         }
654         return -1;
655     }
656 });