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     this.wrapEl  = this.el.wrap().wrap();
63     ///this.el = this.wrapEla.appendChild(document.createElement("div"));
64     
65     
66     if(typeof(this.tpl) == "string"){
67         Roo.log(this.tpl);
68         this.tpl = new Roo.Template(this.tpl);
69         Roo.log(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     Roo.log(this.tpl);
79     
80      
81     /** @private */
82     this.addEvents({
83         /**
84          * @event beforeclick
85          * Fires before a click is processed. Returns false to cancel the default action.
86          * @param {Roo.View} this
87          * @param {Number} index The index of the target node
88          * @param {HTMLElement} node The target node
89          * @param {Roo.EventObject} e The raw event object
90          */
91             "beforeclick" : true,
92         /**
93          * @event click
94          * Fires when a template node is clicked.
95          * @param {Roo.View} this
96          * @param {Number} index The index of the target node
97          * @param {HTMLElement} node The target node
98          * @param {Roo.EventObject} e The raw event object
99          */
100             "click" : true,
101         /**
102          * @event dblclick
103          * Fires when a template node is double clicked.
104          * @param {Roo.View} this
105          * @param {Number} index The index of the target node
106          * @param {HTMLElement} node The target node
107          * @param {Roo.EventObject} e The raw event object
108          */
109             "dblclick" : true,
110         /**
111          * @event contextmenu
112          * Fires when a template node is right clicked.
113          * @param {Roo.View} this
114          * @param {Number} index The index of the target node
115          * @param {HTMLElement} node The target node
116          * @param {Roo.EventObject} e The raw event object
117          */
118             "contextmenu" : true,
119         /**
120          * @event selectionchange
121          * Fires when the selected nodes change.
122          * @param {Roo.View} this
123          * @param {Array} selections Array of the selected nodes
124          */
125             "selectionchange" : true,
126     
127         /**
128          * @event beforeselect
129          * Fires before a selection is made. If any handlers return false, the selection is cancelled.
130          * @param {Roo.View} this
131          * @param {HTMLElement} node The node to be selected
132          * @param {Array} selections Array of currently selected nodes
133          */
134             "beforeselect" : true,
135         /**
136          * @event preparedata
137          * Fires on every row to render, to allow you to change the data.
138          * @param {Roo.View} this
139          * @param {Object} data to be rendered (change this)
140          */
141           "preparedata" : true
142           
143           
144         });
145
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     
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             html[html.length] = Roo.util.Format.trim(
285                 this.dataName ?
286                     t.applySubtemplate(this.dataName, data, this.store.meta) :
287                     t.apply(data)
288             );
289         }
290         
291         
292         
293         el.update(html.join(""));
294         this.nodes = el.dom.childNodes;
295         this.updateIndexes(0);
296     },
297     
298
299     /**
300      * Function to override to reformat the data that is sent to
301      * the template for each node.
302      * DEPRICATED - use the preparedata event handler.
303      * @param {Array/Object} data The raw data (array of colData for a data model bound view or
304      * a JSON object for an UpdateManager bound view).
305      */
306     prepareData : function(data, index, record)
307     {
308         this.fireEvent("preparedata", this, data, index, record);
309         return data;
310     },
311
312     onUpdate : function(ds, record){
313          Roo.log('on update');   
314         this.clearSelections();
315         var index = this.store.indexOf(record);
316         var n = this.nodes[index];
317         this.tpl.insertBefore(n, this.prepareData(record.data, index, record));
318         n.parentNode.removeChild(n);
319         this.updateIndexes(index, index);
320     },
321
322     
323     
324 // --------- FIXME     
325     onAdd : function(ds, records, index)
326     {
327         Roo.log(['on Add', ds, records, index] );        
328         this.clearSelections();
329         if(this.nodes.length == 0){
330             this.refresh();
331             return;
332         }
333         var n = this.nodes[index];
334         for(var i = 0, len = records.length; i < len; i++){
335             var d = this.prepareData(records[i].data, i, records[i]);
336             if(n){
337                 this.tpl.insertBefore(n, d);
338             }else{
339                 
340                 this.tpl.append(this.el, d);
341             }
342         }
343         this.updateIndexes(index);
344     },
345
346     onRemove : function(ds, record, index){
347         Roo.log('onRemove');
348         this.clearSelections();
349         var el = this.dataName  ?
350             this.el.child('.roo-tpl-' + this.dataName) :
351             this.el; 
352         
353         el.dom.removeChild(this.nodes[index]);
354         this.updateIndexes(index);
355     },
356
357     /**
358      * Refresh an individual node.
359      * @param {Number} index
360      */
361     refreshNode : function(index){
362         this.onUpdate(this.store, this.store.getAt(index));
363     },
364
365     updateIndexes : function(startIndex, endIndex){
366         var ns = this.nodes;
367         startIndex = startIndex || 0;
368         endIndex = endIndex || ns.length - 1;
369         for(var i = startIndex; i <= endIndex; i++){
370             ns[i].nodeIndex = i;
371         }
372     },
373
374     /**
375      * Changes the data store this view uses and refresh the view.
376      * @param {Store} store
377      */
378     setStore : function(store, initial){
379         if(!initial && this.store){
380             this.store.un("datachanged", this.refresh);
381             this.store.un("add", this.onAdd);
382             this.store.un("remove", this.onRemove);
383             this.store.un("update", this.onUpdate);
384             this.store.un("clear", this.refresh);
385             this.store.un("beforeload", this.onBeforeLoad);
386             this.store.un("load", this.onLoad);
387             this.store.un("loadexception", this.onLoad);
388         }
389         if(store){
390           
391             store.on("datachanged", this.refresh, this);
392             store.on("add", this.onAdd, this);
393             store.on("remove", this.onRemove, this);
394             store.on("update", this.onUpdate, this);
395             store.on("clear", this.refresh, this);
396             store.on("beforeload", this.onBeforeLoad, this);
397             store.on("load", this.onLoad, this);
398             store.on("loadexception", this.onLoad, this);
399         }
400         
401         if(store){
402             this.refresh();
403         }
404     },
405     /**
406      * onbeforeLoad - masks the loading area.
407      *
408      */
409     onBeforeLoad : function(store,opts)
410     {
411          Roo.log('onBeforeLoad');   
412         if (!opts.add) {
413             this.el.update("");
414         }
415         this.el.mask(this.mask ? this.mask : "Loading" ); 
416     },
417     onLoad : function ()
418     {
419         this.el.unmask();
420     },
421     
422
423     /**
424      * Returns the template node the passed child belongs to or null if it doesn't belong to one.
425      * @param {HTMLElement} node
426      * @return {HTMLElement} The template node
427      */
428     findItemFromChild : function(node){
429         var el = this.dataName  ?
430             this.el.child('.roo-tpl-' + this.dataName,true) :
431             this.el.dom; 
432         
433         if(!node || node.parentNode == el){
434                     return node;
435             }
436             var p = node.parentNode;
437             while(p && p != el){
438             if(p.parentNode == el){
439                 return p;
440             }
441             p = p.parentNode;
442         }
443             return null;
444     },
445
446     /** @ignore */
447     onClick : function(e){
448         var item = this.findItemFromChild(e.getTarget());
449         if(item){
450             var index = this.indexOf(item);
451             if(this.onItemClick(item, index, e) !== false){
452                 this.fireEvent("click", this, index, item, e);
453             }
454         }else{
455             this.clearSelections();
456         }
457     },
458
459     /** @ignore */
460     onContextMenu : function(e){
461         var item = this.findItemFromChild(e.getTarget());
462         if(item){
463             this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
464         }
465     },
466
467     /** @ignore */
468     onDblClick : function(e){
469         var item = this.findItemFromChild(e.getTarget());
470         if(item){
471             this.fireEvent("dblclick", this, this.indexOf(item), item, e);
472         }
473     },
474
475     onItemClick : function(item, index, e)
476     {
477         if(this.fireEvent("beforeclick", this, index, item, e) === false){
478             return false;
479         }
480         if (this.toggleSelect) {
481             var m = this.isSelected(item) ? 'unselect' : 'select';
482             Roo.log(m);
483             var _t = this;
484             _t[m](item, true, false);
485             return true;
486         }
487         if(this.multiSelect || this.singleSelect){
488             if(this.multiSelect && e.shiftKey && this.lastSelection){
489                 this.select(this.getNodes(this.indexOf(this.lastSelection), index), false);
490             }else{
491                 this.select(item, this.multiSelect && e.ctrlKey);
492                 this.lastSelection = item;
493             }
494             
495             if(!this.tickable){
496                 e.preventDefault();
497             }
498             
499         }
500         return true;
501     },
502
503     /**
504      * Get the number of selected nodes.
505      * @return {Number}
506      */
507     getSelectionCount : function(){
508         return this.selections.length;
509     },
510
511     /**
512      * Get the currently selected nodes.
513      * @return {Array} An array of HTMLElements
514      */
515     getSelectedNodes : function(){
516         return this.selections;
517     },
518
519     /**
520      * Get the indexes of the selected nodes.
521      * @return {Array}
522      */
523     getSelectedIndexes : function(){
524         var indexes = [], s = this.selections;
525         for(var i = 0, len = s.length; i < len; i++){
526             indexes.push(s[i].nodeIndex);
527         }
528         return indexes;
529     },
530
531     /**
532      * Clear all selections
533      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange event
534      */
535     clearSelections : function(suppressEvent){
536         if(this.nodes && (this.multiSelect || this.singleSelect) && this.selections.length > 0){
537             this.cmp.elements = this.selections;
538             this.cmp.removeClass(this.selectedClass);
539             this.selections = [];
540             if(!suppressEvent){
541                 this.fireEvent("selectionchange", this, this.selections);
542             }
543         }
544     },
545
546     /**
547      * Returns true if the passed node is selected
548      * @param {HTMLElement/Number} node The node or node index
549      * @return {Boolean}
550      */
551     isSelected : function(node){
552         var s = this.selections;
553         if(s.length < 1){
554             return false;
555         }
556         node = this.getNode(node);
557         return s.indexOf(node) !== -1;
558     },
559
560     /**
561      * Selects nodes.
562      * @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
563      * @param {Boolean} keepExisting (optional) true to keep existing selections
564      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
565      */
566     select : function(nodeInfo, keepExisting, suppressEvent){
567         if(nodeInfo instanceof Array){
568             if(!keepExisting){
569                 this.clearSelections(true);
570             }
571             for(var i = 0, len = nodeInfo.length; i < len; i++){
572                 this.select(nodeInfo[i], true, true);
573             }
574             return;
575         } 
576         var node = this.getNode(nodeInfo);
577         if(!node || this.isSelected(node)){
578             return; // already selected.
579         }
580         if(!keepExisting){
581             this.clearSelections(true);
582         }
583         if(this.fireEvent("beforeselect", this, node, this.selections) !== false){
584             Roo.fly(node).addClass(this.selectedClass);
585             this.selections.push(node);
586             if(!suppressEvent){
587                 this.fireEvent("selectionchange", this, this.selections);
588             }
589         }
590         
591         
592     },
593       /**
594      * Unselects nodes.
595      * @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
596      * @param {Boolean} keepExisting (optional) true IGNORED (for campatibility with select)
597      * @param {Boolean} suppressEvent (optional) true to skip firing of the selectionchange vent
598      */
599     unselect : function(nodeInfo, keepExisting, suppressEvent)
600     {
601         if(nodeInfo instanceof Array){
602             Roo.each(this.selections, function(s) {
603                 this.unselect(s, nodeInfo);
604             }, this);
605             return;
606         }
607         var node = this.getNode(nodeInfo);
608         if(!node || !this.isSelected(node)){
609             Roo.log("not selected");
610             return; // not selected.
611         }
612         // fireevent???
613         var ns = [];
614         Roo.each(this.selections, function(s) {
615             if (s == node ) {
616                 Roo.fly(node).removeClass(this.selectedClass);
617
618                 return;
619             }
620             ns.push(s);
621         },this);
622         
623         this.selections= ns;
624         this.fireEvent("selectionchange", this, this.selections);
625     },
626
627     /**
628      * Gets a template node.
629      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
630      * @return {HTMLElement} The node or null if it wasn't found
631      */
632     getNode : function(nodeInfo){
633         if(typeof nodeInfo == "string"){
634             return document.getElementById(nodeInfo);
635         }else if(typeof nodeInfo == "number"){
636             return this.nodes[nodeInfo];
637         }
638         return nodeInfo;
639     },
640
641     /**
642      * Gets a range template nodes.
643      * @param {Number} startIndex
644      * @param {Number} endIndex
645      * @return {Array} An array of nodes
646      */
647     getNodes : function(start, end){
648         var ns = this.nodes;
649         start = start || 0;
650         end = typeof end == "undefined" ? ns.length - 1 : end;
651         var nodes = [];
652         if(start <= end){
653             for(var i = start; i <= end; i++){
654                 nodes.push(ns[i]);
655             }
656         } else{
657             for(var i = start; i >= end; i--){
658                 nodes.push(ns[i]);
659             }
660         }
661         return nodes;
662     },
663
664     /**
665      * Finds the index of the passed node
666      * @param {HTMLElement/String/Number} nodeInfo An HTMLElement template node, index of a template node or the id of a template node
667      * @return {Number} The index of the node or -1
668      */
669     indexOf : function(node){
670         node = this.getNode(node);
671         if(typeof node.nodeIndex == "number"){
672             return node.nodeIndex;
673         }
674         var ns = this.nodes;
675         for(var i = 0, len = ns.length; i < len; i++){
676             if(ns[i] == node){
677                 return i;
678             }
679         }
680         return -1;
681     }
682 });