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