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