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