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