Roo/grid/Grid.js
[roojs1] / Roo / grid / Grid.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.grid.Grid
14  * @extends Roo.util.Observable
15  * This class represents the primary interface of a component based grid control.
16  * <br><br>Usage:<pre><code>
17  var grid = new Roo.grid.Grid("my-container-id", {
18      ds: myDataStore,
19      cm: myColModel,
20      selModel: mySelectionModel,
21      autoSizeColumns: true,
22      monitorWindowResize: false,
23      trackMouseOver: true
24  });
25  // set any options
26  grid.render();
27  * </code></pre>
28  * <b>Common Problems:</b><br/>
29  * - Grid does not resize properly when going smaller: Setting overflow hidden on the container
30  * element will correct this<br/>
31  * - If you get el.style[camel]= NaNpx or -2px or something related, be certain you have given your container element
32  * dimensions. The grid adapts to your container's size, if your container has no size defined then the results
33  * are unpredictable.<br/>
34  * - Do not render the grid into an element with display:none. Try using visibility:hidden. Otherwise there is no way for the
35  * grid to calculate dimensions/offsets.<br/>
36   * @constructor
37  * @param {String/HTMLElement/Roo.Element} container The element into which this grid will be rendered -
38  * The container MUST have some type of size defined for the grid to fill. The container will be
39  * automatically set to position relative if it isn't already.
40  * @param {Object} config A config object that sets properties on this grid.
41  */
42 Roo.grid.Grid = function(container, config){
43         // initialize the container
44         this.container = Roo.get(container);
45         this.container.update("");
46         this.container.setStyle("overflow", "hidden");
47     this.container.addClass('x-grid-container');
48
49     this.id = this.container.id;
50
51     Roo.apply(this, config);
52     // check and correct shorthanded configs
53     if(this.ds){
54         this.dataSource = this.ds;
55         delete this.ds;
56     }
57     if(this.cm){
58         this.colModel = this.cm;
59         delete this.cm;
60     }
61     if(this.sm){
62         this.selModel = this.sm;
63         delete this.sm;
64     }
65
66     if (this.selModel) {
67         this.selModel = Roo.factory(this.selModel, Roo.grid);
68         this.sm = this.selModel;
69         this.sm.xmodule = this.xmodule || false;
70     }
71     if (typeof(this.colModel.config) == 'undefined') {
72         this.colModel = new Roo.grid.ColumnModel(this.colModel);
73         this.cm = this.colModel;
74         this.cm.xmodule = this.xmodule || false;
75     }
76     if (this.dataSource) {
77         this.dataSource= Roo.factory(this.dataSource, Roo.data);
78         this.ds = this.dataSource;
79         this.ds.xmodule = this.xmodule || false;
80          
81     }
82     
83     
84     
85     if(this.width){
86         this.container.setWidth(this.width);
87     }
88
89     if(this.height){
90         this.container.setHeight(this.height);
91     }
92     /** @private */
93         this.addEvents({
94         // raw events
95         /**
96          * @event click
97          * The raw click event for the entire grid.
98          * @param {Roo.EventObject} e
99          */
100         "click" : true,
101         /**
102          * @event dblclick
103          * The raw dblclick event for the entire grid.
104          * @param {Roo.EventObject} e
105          */
106         "dblclick" : true,
107         /**
108          * @event contextmenu
109          * The raw contextmenu event for the entire grid.
110          * @param {Roo.EventObject} e
111          */
112         "contextmenu" : true,
113         /**
114          * @event mousedown
115          * The raw mousedown event for the entire grid.
116          * @param {Roo.EventObject} e
117          */
118         "mousedown" : true,
119         /**
120          * @event mouseup
121          * The raw mouseup event for the entire grid.
122          * @param {Roo.EventObject} e
123          */
124         "mouseup" : true,
125         /**
126          * @event mouseover
127          * The raw mouseover event for the entire grid.
128          * @param {Roo.EventObject} e
129          */
130         "mouseover" : true,
131         /**
132          * @event mouseout
133          * The raw mouseout event for the entire grid.
134          * @param {Roo.EventObject} e
135          */
136         "mouseout" : true,
137         /**
138          * @event keypress
139          * The raw keypress event for the entire grid.
140          * @param {Roo.EventObject} e
141          */
142         "keypress" : true,
143         /**
144          * @event keydown
145          * The raw keydown event for the entire grid.
146          * @param {Roo.EventObject} e
147          */
148         "keydown" : true,
149
150         // custom events
151
152         /**
153          * @event cellclick
154          * Fires when a cell is clicked
155          * @param {Grid} this
156          * @param {Number} rowIndex
157          * @param {Number} columnIndex
158          * @param {Roo.EventObject} e
159          */
160         "cellclick" : true,
161         /**
162          * @event celldblclick
163          * Fires when a cell is double clicked
164          * @param {Grid} this
165          * @param {Number} rowIndex
166          * @param {Number} columnIndex
167          * @param {Roo.EventObject} e
168          */
169         "celldblclick" : true,
170         /**
171          * @event rowclick
172          * Fires when a row is clicked
173          * @param {Grid} this
174          * @param {Number} rowIndex
175          * @param {Roo.EventObject} e
176          */
177         "rowclick" : true,
178         /**
179          * @event rowdblclick
180          * Fires when a row is double clicked
181          * @param {Grid} this
182          * @param {Number} rowIndex
183          * @param {Roo.EventObject} e
184          */
185         "rowdblclick" : true,
186         /**
187          * @event headerclick
188          * Fires when a header is clicked
189          * @param {Grid} this
190          * @param {Number} columnIndex
191          * @param {Roo.EventObject} e
192          */
193         "headerclick" : true,
194         /**
195          * @event headerdblclick
196          * Fires when a header cell is double clicked
197          * @param {Grid} this
198          * @param {Number} columnIndex
199          * @param {Roo.EventObject} e
200          */
201         "headerdblclick" : true,
202         /**
203          * @event rowcontextmenu
204          * Fires when a row is right clicked
205          * @param {Grid} this
206          * @param {Number} rowIndex
207          * @param {Roo.EventObject} e
208          */
209         "rowcontextmenu" : true,
210         /**
211          * @event cellcontextmenu
212          * Fires when a cell is right clicked
213          * @param {Grid} this
214          * @param {Number} rowIndex
215          * @param {Number} cellIndex
216          * @param {Roo.EventObject} e
217          */
218          "cellcontextmenu" : true,
219         /**
220          * @event headercontextmenu
221          * Fires when a header is right clicked
222          * @param {Grid} this
223          * @param {Number} columnIndex
224          * @param {Roo.EventObject} e
225          */
226         "headercontextmenu" : true,
227         /**
228          * @event bodyscroll
229          * Fires when the body element is scrolled
230          * @param {Number} scrollLeft
231          * @param {Number} scrollTop
232          */
233         "bodyscroll" : true,
234         /**
235          * @event columnresize
236          * Fires when the user resizes a column
237          * @param {Number} columnIndex
238          * @param {Number} newSize
239          */
240         "columnresize" : true,
241         /**
242          * @event columnmove
243          * Fires when the user moves a column
244          * @param {Number} oldIndex
245          * @param {Number} newIndex
246          */
247         "columnmove" : true,
248         /**
249          * @event startdrag
250          * Fires when row(s) start being dragged
251          * @param {Grid} this
252          * @param {Roo.GridDD} dd The drag drop object
253          * @param {event} e The raw browser event
254          */
255         "startdrag" : true,
256         /**
257          * @event enddrag
258          * Fires when a drag operation is complete
259          * @param {Grid} this
260          * @param {Roo.GridDD} dd The drag drop object
261          * @param {event} e The raw browser event
262          */
263         "enddrag" : true,
264         /**
265          * @event dragdrop
266          * Fires when dragged row(s) are dropped on a valid DD target
267          * @param {Grid} this
268          * @param {Roo.GridDD} dd The drag drop object
269          * @param {String} targetId The target drag drop object
270          * @param {event} e The raw browser event
271          */
272         "dragdrop" : true,
273         /**
274          * @event dragover
275          * Fires while row(s) are being dragged. "targetId" is the id of the Yahoo.util.DD object the selected rows are being dragged over.
276          * @param {Grid} this
277          * @param {Roo.GridDD} dd The drag drop object
278          * @param {String} targetId The target drag drop object
279          * @param {event} e The raw browser event
280          */
281         "dragover" : true,
282         /**
283          * @event dragenter
284          *  Fires when the dragged row(s) first cross another DD target while being dragged
285          * @param {Grid} this
286          * @param {Roo.GridDD} dd The drag drop object
287          * @param {String} targetId The target drag drop object
288          * @param {event} e The raw browser event
289          */
290         "dragenter" : true,
291         /**
292          * @event dragout
293          * Fires when the dragged row(s) leave another DD target while being dragged
294          * @param {Grid} this
295          * @param {Roo.GridDD} dd The drag drop object
296          * @param {String} targetId The target drag drop object
297          * @param {event} e The raw browser event
298          */
299         "dragout" : true,
300         /**
301          * @event rowclass
302          * Fires when a row is rendered, so you can change add a style to it.
303          * @param {GridView} gridview   The grid view
304          * @param {Object} rowcfg   contains record  rowIndex and rowClass - set rowClass to add a style.
305          */
306         'rowclass' : true,
307
308         /**
309          * @event render
310          * Fires when the grid is rendered
311          * @param {Grid} grid
312          */
313         'render' : true
314     });
315
316     Roo.grid.Grid.superclass.constructor.call(this);
317 };
318 Roo.extend(Roo.grid.Grid, Roo.util.Observable, {
319     
320     /**
321          * @cfg {Roo.grid.AbstractSelectionModel} sm The selection Model (default = Roo.grid.RowSelectionModel)
322          */
323         /**
324          * @cfg {Roo.grid.GridView} view  The view that renders the grid (default = Roo.grid.GridView)
325          */
326         /**
327          * @cfg {Roo.grid.ColumnModel} cm[] The columns of the grid
328          */
329         /**
330      * @cfg {String} ddGroup - drag drop group.
331      */
332       /**
333      * @cfg {String} dragGroup - drag group (?? not sure if needed.)
334      */
335
336     /**
337      * @cfg {Number} minColumnWidth The minimum width a column can be resized to. Default is 25.
338      */
339     minColumnWidth : 25,
340
341     /**
342      * @cfg {Boolean} autoSizeColumns True to automatically resize the columns to fit their content
343      * <b>on initial render.</b> It is more efficient to explicitly size the columns
344      * through the ColumnModel's {@link Roo.grid.ColumnModel#width} config option.  Default is false.
345      */
346     autoSizeColumns : false,
347
348     /**
349      * @cfg {Boolean} autoSizeHeaders True to measure headers with column data when auto sizing columns. Default is true.
350      */
351     autoSizeHeaders : true,
352
353     /**
354      * @cfg {Boolean} monitorWindowResize True to autoSize the grid when the window resizes. Default is true.
355      */
356     monitorWindowResize : true,
357
358     /**
359      * @cfg {Boolean} maxRowsToMeasure If autoSizeColumns is on, maxRowsToMeasure can be used to limit the number of
360      * rows measured to get a columns size. Default is 0 (all rows).
361      */
362     maxRowsToMeasure : 0,
363
364     /**
365      * @cfg {Boolean} trackMouseOver True to highlight rows when the mouse is over. Default is true.
366      */
367     trackMouseOver : true,
368
369     /**
370     * @cfg {Boolean} enableDrag  True to enable drag of rows. Default is false. (double check if this is needed?)
371     */
372       /**
373     * @cfg {Boolean} enableDrop  True to enable drop of elements. Default is false. (double check if this is needed?)
374     */
375     
376     /**
377     * @cfg {Boolean} enableDragDrop True to enable drag and drop of rows. Default is false.
378     */
379     enableDragDrop : false,
380     
381     /**
382     * @cfg {Boolean} enableColumnMove True to enable drag and drop reorder of columns. Default is true.
383     */
384     enableColumnMove : true,
385     
386     /**
387     * @cfg {Boolean} enableColumnHide True to enable hiding of columns with the header context menu. Default is true.
388     */
389     enableColumnHide : true,
390     
391     /**
392     * @cfg {Boolean} enableRowHeightSync True to manually sync row heights across locked and not locked rows. Default is false.
393     */
394     enableRowHeightSync : false,
395     
396     /**
397     * @cfg {Boolean} stripeRows True to stripe the rows.  Default is true.
398     */
399     stripeRows : true,
400     
401     /**
402     * @cfg {Boolean} autoHeight True to fit the height of the grid container to the height of the data. Default is false.
403     */
404     autoHeight : false,
405
406     /**
407      * @cfg {String} autoExpandColumn The id (or dataIndex) of a column in this grid that should expand to fill unused space. This id can not be 0. Default is false.
408      */
409     autoExpandColumn : false,
410
411     /**
412     * @cfg {Number} autoExpandMin The minimum width the autoExpandColumn can have (if enabled).
413     * Default is 50.
414     */
415     autoExpandMin : 50,
416
417     /**
418     * @cfg {Number} autoExpandMax The maximum width the autoExpandColumn can have (if enabled). Default is 1000.
419     */
420     autoExpandMax : 1000,
421
422     /**
423     * @cfg {Object} view The {@link Roo.grid.GridView} used by the grid. This can be set before a call to render().
424     */
425     view : null,
426
427     /**
428     * @cfg {Object} loadMask An {@link Roo.LoadMask} config or true to mask the grid while loading. Default is false.
429     */
430     loadMask : false,
431     /**
432     * @cfg {Roo.dd.DropTarget} dropTarget An {@link Roo.dd.DropTarget} config
433     */
434     dropTarget: false,
435     
436    
437     
438     // private
439     rendered : false,
440
441     /**
442     * @cfg {Boolean} autoWidth True to set the grid's width to the default total width of the grid's columns instead
443     * of a fixed width. Default is false.
444     */
445     /**
446     * @cfg {Number} maxHeight Sets the maximum height of the grid - ignored if autoHeight is not on.
447     */
448     
449     
450     /**
451     * @cfg {String} ddText Configures the text is the drag proxy (defaults to "%0 selected row(s)").
452     * %0 is replaced with the number of selected rows.
453     */
454     ddText : "{0} selected row{1}",
455     
456     
457     /**
458      * Called once after all setup has been completed and the grid is ready to be rendered.
459      * @return {Roo.grid.Grid} this
460      */
461     render : function()
462     {
463         var c = this.container;
464         // try to detect autoHeight/width mode
465         if((!c.dom.offsetHeight || c.dom.offsetHeight < 20) || c.getStyle("height") == "auto"){
466             this.autoHeight = true;
467         }
468         var view = this.getView();
469         view.init(this);
470
471         c.on("click", this.onClick, this);
472         c.on("dblclick", this.onDblClick, this);
473         c.on("contextmenu", this.onContextMenu, this);
474         c.on("keydown", this.onKeyDown, this);
475         if (Roo.isTouch) {
476             c.on("touchstart", this.onTouchStart, this);
477         }
478
479         this.relayEvents(c, ["mousedown","mouseup","mouseover","mouseout","keypress"]);
480
481         this.getSelectionModel().init(this);
482
483         view.render();
484
485         if(this.loadMask){
486             this.loadMask = new Roo.LoadMask(this.container,
487                     Roo.apply({store:this.dataSource}, this.loadMask));
488         }
489         
490         
491         if (this.toolbar && this.toolbar.xtype) {
492             this.toolbar.container = this.getView().getHeaderPanel(true);
493             this.toolbar = new Roo.Toolbar(this.toolbar);
494         }
495         if (this.footer && this.footer.xtype) {
496             this.footer.dataSource = this.getDataSource();
497             this.footer.container = this.getView().getFooterPanel(true);
498             this.footer = Roo.factory(this.footer, Roo);
499         }
500         if (this.dropTarget && this.dropTarget.xtype) {
501             delete this.dropTarget.xtype;
502             this.dropTarget =  new Roo.dd.DropTarget(this.getView().mainBody, this.dropTarget);
503         }
504         
505         
506         this.rendered = true;
507         this.fireEvent('render', this);
508         return this;
509     },
510
511     /**
512      * Reconfigures the grid to use a different Store and Column Model.
513      * The View will be bound to the new objects and refreshed.
514      * @param {Roo.data.Store} dataSource The new {@link Roo.data.Store} object
515      * @param {Roo.grid.ColumnModel} The new {@link Roo.grid.ColumnModel} object
516      */
517     reconfigure : function(dataSource, colModel){
518         if(this.loadMask){
519             this.loadMask.destroy();
520             this.loadMask = new Roo.LoadMask(this.container,
521                     Roo.apply({store:dataSource}, this.loadMask));
522         }
523         this.view.bind(dataSource, colModel);
524         this.dataSource = dataSource;
525         this.colModel = colModel;
526         this.view.refresh(true);
527     },
528     /**
529      * addColumns
530      * Add's a column, default at the end..
531      
532      * @param {int} position to add (default end)
533      * @param {Array} of objects of column configuration see {@link Roo.grid.ColumnModel} 
534      */
535     addColumns : function(pos, ar)
536     {
537         
538         for (var i =0;i< ar.length;i++) {
539             var cfg = ar[i];
540             cfg.id = typeof(cfg.id) == 'undefined' ? Roo.id() : cfg.id; // don't normally use this..
541             this.cm.lookup[cfg.id] = cfg;
542         }
543         
544         
545         if (typeof(pos) == 'undefined' || pos >= this.cm.config.length) {
546             pos = this.cm.config.length; //this.cm.config.push(cfg);
547         } 
548         pos = Math.max(0,pos);
549         ar.unshift(0);
550         ar.unshift(pos);
551         this.cm.config.splice.apply(this.cm.config, ar);
552         
553         
554         
555         this.view.generateRules(this.cm);
556         this.view.refresh(true);
557         
558     },
559     
560     
561     
562     
563     // private
564     onKeyDown : function(e){
565         this.fireEvent("keydown", e);
566     },
567
568     /**
569      * Destroy this grid.
570      * @param {Boolean} removeEl True to remove the element
571      */
572     destroy : function(removeEl, keepListeners){
573         if(this.loadMask){
574             this.loadMask.destroy();
575         }
576         var c = this.container;
577         c.removeAllListeners();
578         this.view.destroy();
579         this.colModel.purgeListeners();
580         if(!keepListeners){
581             this.purgeListeners();
582         }
583         c.update("");
584         if(removeEl === true){
585             c.remove();
586         }
587     },
588
589     // private
590     processEvent : function(name, e){
591         // does this fire select???
592         //Roo.log('grid:processEvent '  + name);
593         
594         if (name != 'touchstart' ) {
595             this.fireEvent(name, e);    
596         }
597         
598         var t = e.getTarget();
599         var v = this.view;
600         var header = v.findHeaderIndex(t);
601         if(header !== false){
602             var ename = name == 'touchstart' ? 'click' : name;
603              
604             this.fireEvent("header" + ename, this, header, e);
605         }else{
606             var row = v.findRowIndex(t);
607             var cell = v.findCellIndex(t);
608             if (name == 'touchstart') {
609                 // first touch is always a click.
610                 // hopefull this happens after selection is updated.?
611                 name = false;
612                 
613                 if (typeof(this.selModel.getSelectedCell) != 'undefined') {
614                     var cs = this.selModel.getSelectedCell();
615                     if (row == cs[0] && cell == cs[1]){
616                         name = 'dblclick';
617                     }
618                 }
619                 if (typeof(this.selModel.getSelections) != 'undefined') {
620                     var cs = this.selModel.getSelections();
621                     var ds = this.dataSource;
622                     if (cs.length == 1 && ds.getAt(row) == cs[0]){
623                         name = 'dblclick';
624                     }
625                 }
626                 if (!name) {
627                     return;
628                 }
629             }
630             
631             
632             if(row !== false){
633                 this.fireEvent("row" + name, this, row, e);
634                 if(cell !== false){
635                     this.fireEvent("cell" + name, this, row, cell, e);
636                 }
637             }
638         }
639     },
640
641     // private
642     onClick : function(e){
643         this.processEvent("click", e);
644     },
645    // private
646     onTouchStart : function(e){
647         this.processEvent("touchstart", e);
648     },
649
650     // private
651     onContextMenu : function(e, t){
652         this.processEvent("contextmenu", e);
653     },
654
655     // private
656     onDblClick : function(e){
657         this.processEvent("dblclick", e);
658     },
659
660     // private
661     walkCells : function(row, col, step, fn, scope){
662         var cm = this.colModel, clen = cm.getColumnCount();
663         var ds = this.dataSource, rlen = ds.getCount(), first = true;
664         if(step < 0){
665             if(col < 0){
666                 row--;
667                 first = false;
668             }
669             while(row >= 0){
670                 if(!first){
671                     col = clen-1;
672                 }
673                 first = false;
674                 while(col >= 0){
675                     if(fn.call(scope || this, row, col, cm) === true){
676                         return [row, col];
677                     }
678                     col--;
679                 }
680                 row--;
681             }
682         } else {
683             if(col >= clen){
684                 row++;
685                 first = false;
686             }
687             while(row < rlen){
688                 if(!first){
689                     col = 0;
690                 }
691                 first = false;
692                 while(col < clen){
693                     if(fn.call(scope || this, row, col, cm) === true){
694                         return [row, col];
695                     }
696                     col++;
697                 }
698                 row++;
699             }
700         }
701         return null;
702     },
703
704     // private
705     getSelections : function(){
706         return this.selModel.getSelections();
707     },
708
709     /**
710      * Causes the grid to manually recalculate its dimensions. Generally this is done automatically,
711      * but if manual update is required this method will initiate it.
712      */
713     autoSize : function(){
714         if(this.rendered){
715             this.view.layout();
716             if(this.view.adjustForScroll){
717                 this.view.adjustForScroll();
718             }
719         }
720     },
721
722     /**
723      * Returns the grid's underlying element.
724      * @return {Element} The element
725      */
726     getGridEl : function(){
727         return this.container;
728     },
729
730     // private for compatibility, overridden by editor grid
731     stopEditing : function(){},
732
733     /**
734      * Returns the grid's SelectionModel.
735      * @return {SelectionModel}
736      */
737     getSelectionModel : function(){
738         if(!this.selModel){
739             this.selModel = new Roo.grid.RowSelectionModel();
740         }
741         return this.selModel;
742     },
743
744     /**
745      * Returns the grid's DataSource.
746      * @return {DataSource}
747      */
748     getDataSource : function(){
749         return this.dataSource;
750     },
751
752     /**
753      * Returns the grid's ColumnModel.
754      * @return {ColumnModel}
755      */
756     getColumnModel : function(){
757         return this.colModel;
758     },
759
760     /**
761      * Returns the grid's GridView object.
762      * @return {GridView}
763      */
764     getView : function(){
765         if(!this.view){
766             this.view = new Roo.grid.GridView(this.viewConfig);
767             this.relayEvents(this.view, [
768                 "beforerowremoved", "beforerowsinserted",
769                 "beforerefresh", "rowremoved",
770                 "rowsinserted", "rowupdated" ,"refresh"
771             ]);
772         }
773         return this.view;
774     },
775     /**
776      * Called to get grid's drag proxy text, by default returns this.ddText.
777      * Override this to put something different in the dragged text.
778      * @return {String}
779      */
780     getDragDropText : function(){
781         var count = this.selModel.getCount();
782         return String.format(this.ddText, count, count == 1 ? '' : 's');
783     }
784 });