Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / pkgs / pkg-grid-grouping-debug.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.grid.GroupingView
9  * @extends Ext.grid.GridView
10  * Adds the ability for single level grouping to the grid. A {@link Ext.data.GroupingStore GroupingStore}
11  * must be used to enable grouping.  Some grouping characteristics may also be configured at the
12  * {@link Ext.grid.Column Column level}<div class="mdetail-params"><ul>
13  * <li><code>{@link Ext.grid.Column#emptyGroupText emptyGroupText}</code></li>
14  * <li><code>{@link Ext.grid.Column#groupable groupable}</code></li>
15  * <li><code>{@link Ext.grid.Column#groupName groupName}</code></li>
16  * <li><code>{@link Ext.grid.Column#groupRender groupRender}</code></li>
17  * </ul></div>
18  * <p>Sample usage:</p>
19  * <pre><code>
20 var grid = new Ext.grid.GridPanel({
21     // A groupingStore is required for a GroupingView
22     store: new {@link Ext.data.GroupingStore}({
23         autoDestroy: true,
24         reader: reader,
25         data: xg.dummyData,
26         sortInfo: {field: 'company', direction: 'ASC'},
27         {@link Ext.data.GroupingStore#groupOnSort groupOnSort}: true,
28         {@link Ext.data.GroupingStore#remoteGroup remoteGroup}: true,
29         {@link Ext.data.GroupingStore#groupField groupField}: 'industry'
30     }),
31     colModel: new {@link Ext.grid.ColumnModel}({
32         columns:[
33             {id:'company',header: 'Company', width: 60, dataIndex: 'company'},
34             // {@link Ext.grid.Column#groupable groupable}, {@link Ext.grid.Column#groupName groupName}, {@link Ext.grid.Column#groupRender groupRender} are also configurable at column level
35             {header: 'Price', renderer: Ext.util.Format.usMoney, dataIndex: 'price', {@link Ext.grid.Column#groupable groupable}: false},
36             {header: 'Change', dataIndex: 'change', renderer: Ext.util.Format.usMoney},
37             {header: 'Industry', dataIndex: 'industry'},
38             {header: 'Last Updated', renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
39         ],
40         defaults: {
41             sortable: true,
42             menuDisabled: false,
43             width: 20
44         }
45     }),
46
47     view: new Ext.grid.GroupingView({
48         {@link Ext.grid.GridView#forceFit forceFit}: true,
49         // custom grouping text template to display the number of items per group
50         {@link #groupTextTpl}: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
51     }),
52
53     frame:true,
54     width: 700,
55     height: 450,
56     collapsible: true,
57     animCollapse: false,
58     title: 'Grouping Example',
59     iconCls: 'icon-grid',
60     renderTo: document.body
61 });
62  * </code></pre>
63  * @constructor
64  * @param {Object} config
65  */
66 Ext.grid.GroupingView = Ext.extend(Ext.grid.GridView, {
67
68     /**
69      * @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column
70      * (defaults to 'Group By This Field').
71      */
72     groupByText : 'Group By This Field',
73     /**
74      * @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping
75      * (defaults to 'Show in Groups').
76      */
77     showGroupsText : 'Show in Groups',
78     /**
79      * @cfg {Boolean} hideGroupedColumn <tt>true</tt> to hide the column that is currently grouped (defaults to <tt>false</tt>)
80      */
81     hideGroupedColumn : false,
82     /**
83      * @cfg {Boolean} showGroupName If <tt>true</tt> will display a prefix plus a ': ' before the group field value
84      * in the group header line.  The prefix will consist of the <tt><b>{@link Ext.grid.Column#groupName groupName}</b></tt>
85      * (or the configured <tt><b>{@link Ext.grid.Column#header header}</b></tt> if not provided) configured in the
86      * {@link Ext.grid.Column} for each set of grouped rows (defaults to <tt>true</tt>).
87      */
88     showGroupName : true,
89     /**
90      * @cfg {Boolean} startCollapsed <tt>true</tt> to start all groups collapsed (defaults to <tt>false</tt>)
91      */
92     startCollapsed : false,
93     /**
94      * @cfg {Boolean} enableGrouping <tt>false</tt> to disable grouping functionality (defaults to <tt>true</tt>)
95      */
96     enableGrouping : true,
97     /**
98      * @cfg {Boolean} enableGroupingMenu <tt>true</tt> to enable the grouping control in the column menu (defaults to <tt>true</tt>)
99      */
100     enableGroupingMenu : true,
101     /**
102      * @cfg {Boolean} enableNoGroups <tt>true</tt> to allow the user to turn off grouping (defaults to <tt>true</tt>)
103      */
104     enableNoGroups : true,
105     /**
106      * @cfg {String} emptyGroupText The text to display when there is an empty group value (defaults to <tt>'(None)'</tt>).
107      * May also be specified per column, see {@link Ext.grid.Column}.{@link Ext.grid.Column#emptyGroupText emptyGroupText}.
108      */
109     emptyGroupText : '(None)',
110     /**
111      * @cfg {Boolean} ignoreAdd <tt>true</tt> to skip refreshing the view when new rows are added (defaults to <tt>false</tt>)
112      */
113     ignoreAdd : false,
114     /**
115      * @cfg {String} groupTextTpl The template used to render the group header (defaults to <tt>'{text}'</tt>).
116      * This is used to format an object which contains the following properties:
117      * <div class="mdetail-params"><ul>
118      * <li><b>group</b> : String<p class="sub-desc">The <i>rendered</i> value of the group field.
119      * By default this is the unchanged value of the group field. If a <tt><b>{@link Ext.grid.Column#groupRenderer groupRenderer}</b></tt>
120      * is specified, it is the result of a call to that function.</p></li>
121      * <li><b>gvalue</b> : Object<p class="sub-desc">The <i>raw</i> value of the group field.</p></li>
122      * <li><b>text</b> : String<p class="sub-desc">The configured header (as described in <tt>{@link #showGroupName})</tt>
123      * if <tt>{@link #showGroupName}</tt> is <tt>true</tt>) plus the <i>rendered</i> group field value.</p></li>
124      * <li><b>groupId</b> : String<p class="sub-desc">A unique, generated ID which is applied to the
125      * View Element which contains the group.</p></li>
126      * <li><b>startRow</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li>
127      * <li><b>rs</b> : Array<p class="sub-desc">Contains a single element: The Record providing the data
128      * for the row which caused group change.</p></li>
129      * <li><b>cls</b> : String<p class="sub-desc">The generated class name string to apply to the group header Element.</p></li>
130      * <li><b>style</b> : String<p class="sub-desc">The inline style rules to apply to the group header Element.</p></li>
131      * </ul></div></p>
132      * See {@link Ext.XTemplate} for information on how to format data using a template. Possible usage:<pre><code>
133 var grid = new Ext.grid.GridPanel({
134     ...
135     view: new Ext.grid.GroupingView({
136         groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
137     }),
138 });
139      * </code></pre>
140      */
141     groupTextTpl : '{text}',
142
143     /**
144      * @cfg {String} groupMode Indicates how to construct the group identifier. <tt>'value'</tt> constructs the id using
145      * raw value, <tt>'display'</tt> constructs the id using the rendered value. Defaults to <tt>'value'</tt>.
146      */
147     groupMode: 'value',
148
149     /**
150      * @cfg {Function} groupRenderer This property must be configured in the {@link Ext.grid.Column} for
151      * each column.
152      */
153
154     // private
155     initTemplates : function(){
156         Ext.grid.GroupingView.superclass.initTemplates.call(this);
157         this.state = {};
158
159         var sm = this.grid.getSelectionModel();
160         sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect',
161                 this.onBeforeRowSelect, this);
162
163         if(!this.startGroup){
164             this.startGroup = new Ext.XTemplate(
165                 '<div id="{groupId}" class="x-grid-group {cls}">',
166                     '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">', this.groupTextTpl ,'</div></div>',
167                     '<div id="{groupId}-bd" class="x-grid-group-body">'
168             );
169         }
170         this.startGroup.compile();
171
172         if (!this.endGroup) {
173             this.endGroup = '</div></div>';
174         }
175     },
176
177     // private
178     findGroup : function(el){
179         return Ext.fly(el).up('.x-grid-group', this.mainBody.dom);
180     },
181
182     // private
183     getGroups : function(){
184         return this.hasRows() ? this.mainBody.dom.childNodes : [];
185     },
186
187     // private
188     onAdd : function(ds, records, index) {
189         if (this.canGroup() && !this.ignoreAdd) {
190             var ss = this.getScrollState();
191             this.fireEvent('beforerowsinserted', ds, index, index + (records.length-1));
192             this.refresh();
193             this.restoreScroll(ss);
194             this.fireEvent('rowsinserted', ds, index, index + (records.length-1));
195         } else if (!this.canGroup()) {
196             Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments);
197         }
198     },
199
200     // private
201     onRemove : function(ds, record, index, isUpdate){
202         Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments);
203         var g = document.getElementById(record._groupId);
204         if(g && g.childNodes[1].childNodes.length < 1){
205             Ext.removeNode(g);
206         }
207         this.applyEmptyText();
208     },
209
210     // private
211     refreshRow : function(record){
212         if(this.ds.getCount()==1){
213             this.refresh();
214         }else{
215             this.isUpdating = true;
216             Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments);
217             this.isUpdating = false;
218         }
219     },
220
221     // private
222     beforeMenuShow : function(){
223         var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false;
224         if((item = items.get('groupBy'))){
225             item.setDisabled(disabled);
226         }
227         if((item = items.get('showGroups'))){
228             item.setDisabled(disabled);
229             item.setChecked(this.enableGrouping, true);
230         }
231     },
232
233     // private
234     renderUI : function(){
235         Ext.grid.GroupingView.superclass.renderUI.call(this);
236         this.mainBody.on('mousedown', this.interceptMouse, this);
237
238         if(this.enableGroupingMenu && this.hmenu){
239             this.hmenu.add('-',{
240                 itemId:'groupBy',
241                 text: this.groupByText,
242                 handler: this.onGroupByClick,
243                 scope: this,
244                 iconCls:'x-group-by-icon'
245             });
246             if(this.enableNoGroups){
247                 this.hmenu.add({
248                     itemId:'showGroups',
249                     text: this.showGroupsText,
250                     checked: true,
251                     checkHandler: this.onShowGroupsClick,
252                     scope: this
253                 });
254             }
255             this.hmenu.on('beforeshow', this.beforeMenuShow, this);
256         }
257     },
258
259     processEvent: function(name, e){
260         Ext.grid.GroupingView.superclass.processEvent.call(this, name, e);
261         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
262         if(hd){
263             // group value is at the end of the string
264             var field = this.getGroupField(),
265                 prefix = this.getPrefix(field),
266                 groupValue = hd.id.substring(prefix.length);
267
268             // remove trailing '-hd'
269             groupValue = groupValue.substr(0, groupValue.length - 3);
270             if(groupValue){
271                 this.grid.fireEvent('group' + name, this.grid, field, groupValue, e);
272             }
273         }
274
275     },
276
277     // private
278     onGroupByClick : function(){
279         this.enableGrouping = true;
280         this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
281         this.grid.fireEvent('groupchange', this, this.grid.store.getGroupState());
282         this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups
283         this.refresh();
284     },
285
286     // private
287     onShowGroupsClick : function(mi, checked){
288         this.enableGrouping = checked;
289         if(checked){
290             this.onGroupByClick();
291         }else{
292             this.grid.store.clearGrouping();
293             this.grid.fireEvent('groupchange', this, null);
294         }
295     },
296
297     /**
298      * Toggle the group that contains the specific row.
299      * @param {Number} rowIndex The row inside the group
300      * @param {Boolean} expanded (optional)
301      */
302     toggleRowIndex : function(rowIndex, expanded){
303         if(!this.canGroup()){
304             return;
305         }
306         var row = this.getRow(rowIndex);
307         if(row){
308             this.toggleGroup(this.findGroup(row), expanded);
309         }
310     },
311
312     /**
313      * Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed.
314      * @param {String} groupId The groupId assigned to the group (see getGroupId)
315      * @param {Boolean} expanded (optional)
316      */
317     toggleGroup : function(group, expanded){
318         var gel = Ext.get(group);
319         expanded = Ext.isDefined(expanded) ? expanded : gel.hasClass('x-grid-group-collapsed');
320         if(this.state[gel.id] !== expanded){
321             this.grid.stopEditing(true);
322             this.state[gel.id] = expanded;
323             gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed');
324         }
325     },
326
327     /**
328      * Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed.
329      * @param {Boolean} expanded (optional)
330      */
331     toggleAllGroups : function(expanded){
332         var groups = this.getGroups();
333         for(var i = 0, len = groups.length; i < len; i++){
334             this.toggleGroup(groups[i], expanded);
335         }
336     },
337
338     /**
339      * Expands all grouped rows.
340      */
341     expandAllGroups : function(){
342         this.toggleAllGroups(true);
343     },
344
345     /**
346      * Collapses all grouped rows.
347      */
348     collapseAllGroups : function(){
349         this.toggleAllGroups(false);
350     },
351
352     // private
353     interceptMouse : function(e){
354         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
355         if(hd){
356             e.stopEvent();
357             this.toggleGroup(hd.parentNode);
358         }
359     },
360
361     // private
362     getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){
363         var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v);
364         if(g === '' || g === '&#160;'){
365             g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText;
366         }
367         return g;
368     },
369
370     // private
371     getGroupField : function(){
372         return this.grid.store.getGroupState();
373     },
374
375     // private
376     afterRender : function(){
377         if(!this.ds || !this.cm){
378             return;
379         }
380         Ext.grid.GroupingView.superclass.afterRender.call(this);
381         if(this.grid.deferRowRender){
382             this.updateGroupWidths();
383         }
384     },
385
386     // private
387     renderRows : function(){
388         var groupField = this.getGroupField();
389         var eg = !!groupField;
390         // if they turned off grouping and the last grouped field is hidden
391         if(this.hideGroupedColumn) {
392             var colIndex = this.cm.findColumnIndex(groupField),
393                 hasLastGroupField = Ext.isDefined(this.lastGroupField);
394             if(!eg && hasLastGroupField){
395                 this.mainBody.update('');
396                 this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false);
397                 delete this.lastGroupField;
398             }else if (eg && !hasLastGroupField){
399                 this.lastGroupField = groupField;
400                 this.cm.setHidden(colIndex, true);
401             }else if (eg && hasLastGroupField && groupField !== this.lastGroupField) {
402                 this.mainBody.update('');
403                 var oldIndex = this.cm.findColumnIndex(this.lastGroupField);
404                 this.cm.setHidden(oldIndex, false);
405                 this.lastGroupField = groupField;
406                 this.cm.setHidden(colIndex, true);
407             }
408         }
409         return Ext.grid.GroupingView.superclass.renderRows.apply(
410                     this, arguments);
411     },
412
413     // private
414     doRender : function(cs, rs, ds, startRow, colCount, stripe){
415         if(rs.length < 1){
416             return '';
417         }
418
419         if(!this.canGroup() || this.isUpdating){
420             return Ext.grid.GroupingView.superclass.doRender.apply(this, arguments);
421         }
422
423         var groupField = this.getGroupField(),
424             colIndex = this.cm.findColumnIndex(groupField),
425             g,
426             gstyle = 'width:' + this.getTotalWidth() + ';',
427             cfg = this.cm.config[colIndex],
428             groupRenderer = cfg.groupRenderer || cfg.renderer,
429             prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : '',
430             groups = [],
431             curGroup, i, len, gid;
432
433         for(i = 0, len = rs.length; i < len; i++){
434             var rowIndex = startRow + i,
435                 r = rs[i],
436                 gvalue = r.data[groupField];
437
438                 g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds);
439             if(!curGroup || curGroup.group != g){
440                 gid = this.constructId(gvalue, groupField, colIndex);
441                 // if state is defined use it, however state is in terms of expanded
442                 // so negate it, otherwise use the default.
443                 this.state[gid] = !(Ext.isDefined(this.state[gid]) ? !this.state[gid] : this.startCollapsed);
444                 curGroup = {
445                     group: g,
446                     gvalue: gvalue,
447                     text: prefix + g,
448                     groupId: gid,
449                     startRow: rowIndex,
450                     rs: [r],
451                     cls: this.state[gid] ? '' : 'x-grid-group-collapsed',
452                     style: gstyle
453                 };
454                 groups.push(curGroup);
455             }else{
456                 curGroup.rs.push(r);
457             }
458             r._groupId = gid;
459         }
460
461         var buf = [];
462         for(i = 0, len = groups.length; i < len; i++){
463             g = groups[i];
464             this.doGroupStart(buf, g, cs, ds, colCount);
465             buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call(
466                     this, cs, g.rs, ds, g.startRow, colCount, stripe);
467
468             this.doGroupEnd(buf, g, cs, ds, colCount);
469         }
470         return buf.join('');
471     },
472
473     /**
474      * Dynamically tries to determine the groupId of a specific value
475      * @param {String} value
476      * @return {String} The group id
477      */
478     getGroupId : function(value){
479         var field = this.getGroupField();
480         return this.constructId(value, field, this.cm.findColumnIndex(field));
481     },
482
483     // private
484     constructId : function(value, field, idx){
485         var cfg = this.cm.config[idx],
486             groupRenderer = cfg.groupRenderer || cfg.renderer,
487             val = (this.groupMode == 'value') ? value : this.getGroup(value, {data:{}}, groupRenderer, 0, idx, this.ds);
488
489         return this.getPrefix(field) + Ext.util.Format.htmlEncode(val);
490     },
491
492     // private
493     canGroup  : function(){
494         return this.enableGrouping && !!this.getGroupField();
495     },
496
497     // private
498     getPrefix: function(field){
499         return this.grid.getGridEl().id + '-gp-' + field + '-';
500     },
501
502     // private
503     doGroupStart : function(buf, g, cs, ds, colCount){
504         buf[buf.length] = this.startGroup.apply(g);
505     },
506
507     // private
508     doGroupEnd : function(buf, g, cs, ds, colCount){
509         buf[buf.length] = this.endGroup;
510     },
511
512     // private
513     getRows : function(){
514         if(!this.canGroup()){
515             return Ext.grid.GroupingView.superclass.getRows.call(this);
516         }
517         var r = [],
518             gs = this.getGroups(),
519             g,
520             i = 0,
521             len = gs.length,
522             j,
523             jlen;
524         for(; i < len; ++i){
525             g = gs[i].childNodes[1];
526             if(g){
527                 g = g.childNodes;
528                 for(j = 0, jlen = g.length; j < jlen; ++j){
529                     r[r.length] = g[j];
530                 }
531             }
532         }
533         return r;
534     },
535
536     // private
537     updateGroupWidths : function(){
538         if(!this.canGroup() || !this.hasRows()){
539             return;
540         }
541         var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.getScrollOffset()) +'px';
542         var gs = this.getGroups();
543         for(var i = 0, len = gs.length; i < len; i++){
544             gs[i].firstChild.style.width = tw;
545         }
546     },
547
548     // private
549     onColumnWidthUpdated : function(col, w, tw){
550         Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw);
551         this.updateGroupWidths();
552     },
553
554     // private
555     onAllColumnWidthsUpdated : function(ws, tw){
556         Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw);
557         this.updateGroupWidths();
558     },
559
560     // private
561     onColumnHiddenUpdated : function(col, hidden, tw){
562         Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw);
563         this.updateGroupWidths();
564     },
565
566     // private
567     onLayout : function(){
568         this.updateGroupWidths();
569     },
570
571     // private
572     onBeforeRowSelect : function(sm, rowIndex){
573         this.toggleRowIndex(rowIndex, true);
574     }
575 });
576 // private
577 Ext.grid.GroupingView.GROUP_ID = 1000;