Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / pkgs / pkg-grid-grouping-debug.js
1 /*!
2  * Ext JS Library 3.1.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     /**\r
144      * @cfg {String} groupMode Indicates how to construct the group identifier. <tt>'value'</tt> constructs the id using\r
145      * raw value, <tt>'display'</tt> constructs the id using the rendered value. Defaults to <tt>'value'</tt>.\r
146      */\r
147     groupMode: 'value',\r
148 \r
149     /**\r
150      * @cfg {Function} groupRenderer This property must be configured in the {@link Ext.grid.Column} for\r
151      * each column.\r
152      */\r
153 \r
154     // private\r
155     gidSeed : 1000,\r
156 \r
157     // private\r
158     initTemplates : function(){\r
159         Ext.grid.GroupingView.superclass.initTemplates.call(this);\r
160         this.state = {};\r
161 \r
162         var sm = this.grid.getSelectionModel();\r
163         sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect',\r
164                 this.onBeforeRowSelect, this);\r
165 \r
166         if(!this.startGroup){\r
167             this.startGroup = new Ext.XTemplate(\r
168                 '<div id="{groupId}" class="x-grid-group {cls}">',\r
169                     '<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">', this.groupTextTpl ,'</div></div>',\r
170                     '<div id="{groupId}-bd" class="x-grid-group-body">'\r
171             );\r
172         }\r
173         this.startGroup.compile();\r
174         if(!this.endGroup){\r
175             this.endGroup = '</div></div>';\r
176         }\r
177 \r
178         this.endGroup = '</div></div>';\r
179     },\r
180 \r
181     // private\r
182     findGroup : function(el){\r
183         return Ext.fly(el).up('.x-grid-group', this.mainBody.dom);\r
184     },\r
185 \r
186     // private\r
187     getGroups : function(){\r
188         return this.hasRows() ? this.mainBody.dom.childNodes : [];\r
189     },\r
190 \r
191     // private\r
192     onAdd : function(){\r
193         if(this.enableGrouping && !this.ignoreAdd){\r
194             var ss = this.getScrollState();\r
195             this.refresh();\r
196             this.restoreScroll(ss);\r
197         }else if(!this.enableGrouping){\r
198             Ext.grid.GroupingView.superclass.onAdd.apply(this, arguments);\r
199         }\r
200     },\r
201 \r
202     // private\r
203     onRemove : function(ds, record, index, isUpdate){\r
204         Ext.grid.GroupingView.superclass.onRemove.apply(this, arguments);\r
205         var g = document.getElementById(record._groupId);\r
206         if(g && g.childNodes[1].childNodes.length < 1){\r
207             Ext.removeNode(g);\r
208         }\r
209         this.applyEmptyText();\r
210     },\r
211 \r
212     // private\r
213     refreshRow : function(record){\r
214         if(this.ds.getCount()==1){\r
215             this.refresh();\r
216         }else{\r
217             this.isUpdating = true;\r
218             Ext.grid.GroupingView.superclass.refreshRow.apply(this, arguments);\r
219             this.isUpdating = false;\r
220         }\r
221     },\r
222 \r
223     // private\r
224     beforeMenuShow : function(){\r
225         var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false;\r
226         if((item = items.get('groupBy'))){\r
227             item.setDisabled(disabled);\r
228         }\r
229         if((item = items.get('showGroups'))){\r
230             item.setDisabled(disabled);\r
231         item.setChecked(this.enableGrouping, true);\r
232         }\r
233     },\r
234 \r
235     // private\r
236     renderUI : function(){\r
237         Ext.grid.GroupingView.superclass.renderUI.call(this);\r
238         this.mainBody.on('mousedown', this.interceptMouse, this);\r
239 \r
240         if(this.enableGroupingMenu && this.hmenu){\r
241             this.hmenu.add('-',{\r
242                 itemId:'groupBy',\r
243                 text: this.groupByText,\r
244                 handler: this.onGroupByClick,\r
245                 scope: this,\r
246                 iconCls:'x-group-by-icon'\r
247             });\r
248             if(this.enableNoGroups){\r
249                 this.hmenu.add({\r
250                     itemId:'showGroups',\r
251                     text: this.showGroupsText,\r
252             checked: true,\r
253                     checkHandler: this.onShowGroupsClick,\r
254                     scope: this\r
255                 });\r
256             }\r
257             this.hmenu.on('beforeshow', this.beforeMenuShow, this);\r
258         }\r
259     },\r
260 \r
261     processEvent: function(name, e){\r
262         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);\r
263         if(hd){\r
264             // group value is at the end of the string\r
265             var field = this.getGroupField(),\r
266                 prefix = this.getPrefix(field),\r
267                 groupValue = hd.id.substring(prefix.length);\r
268 \r
269             // remove trailing '-hd'\r
270             groupValue = groupValue.substr(0, groupValue.length - 3);\r
271             if(groupValue){\r
272                 this.grid.fireEvent('group' + name, this.grid, field, groupValue, e);\r
273             }\r
274         }\r
275 \r
276     },\r
277 \r
278     // private\r
279     onGroupByClick : function(){\r
280     this.enableGrouping = true;\r
281         this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));\r
282         this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups\r
283     this.refresh();\r
284     },\r
285 \r
286     // private\r
287     onShowGroupsClick : function(mi, checked){\r
288     this.enableGrouping = checked;\r
289         if(checked){\r
290             this.onGroupByClick();\r
291         }else{\r
292             this.grid.store.clearGrouping();\r
293         }\r
294     },\r
295 \r
296     /**\r
297      * Toggle the group that contains the specific row.\r
298      * @param {Number} rowIndex The row inside the group\r
299      * @param {Boolean} expanded (optional)\r
300      */\r
301     toggleRowIndex : function(rowIndex, expanded){\r
302         if(!this.enableGrouping){\r
303             return;\r
304         }\r
305         var row = this.getRow(rowIndex);\r
306         if(row){\r
307             this.toggleGroup(this.findGroup(row), expanded);\r
308         }\r
309     },\r
310 \r
311     /**\r
312      * Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed.\r
313      * @param {String} groupId The groupId assigned to the group (see getGroupId)\r
314      * @param {Boolean} expanded (optional)\r
315      */\r
316     toggleGroup : function(group, expanded){\r
317         var gel = Ext.get(group);\r
318         expanded = Ext.isDefined(expanded) ? expanded : gel.hasClass('x-grid-group-collapsed');\r
319         if(this.state[gel.id] !== expanded){\r
320             this.grid.stopEditing(true);\r
321             this.state[gel.id] = expanded;\r
322             gel[expanded ? 'removeClass' : 'addClass']('x-grid-group-collapsed');\r
323         }\r
324     },\r
325 \r
326     /**\r
327      * Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed.\r
328      * @param {Boolean} expanded (optional)\r
329      */\r
330     toggleAllGroups : function(expanded){\r
331         var groups = this.getGroups();\r
332         for(var i = 0, len = groups.length; i < len; i++){\r
333             this.toggleGroup(groups[i], expanded);\r
334         }\r
335     },\r
336 \r
337     /**\r
338      * Expands all grouped rows.\r
339      */\r
340     expandAllGroups : function(){\r
341         this.toggleAllGroups(true);\r
342     },\r
343 \r
344     /**\r
345      * Collapses all grouped rows.\r
346      */\r
347     collapseAllGroups : function(){\r
348         this.toggleAllGroups(false);\r
349     },\r
350 \r
351     // private\r
352     interceptMouse : function(e){\r
353         var hd = e.getTarget('.x-grid-group-hd', this.mainBody);\r
354         if(hd){\r
355             e.stopEvent();\r
356             this.toggleGroup(hd.parentNode);\r
357         }\r
358     },\r
359 \r
360     // private\r
361     getGroup : function(v, r, groupRenderer, rowIndex, colIndex, ds){\r
362         var g = groupRenderer ? groupRenderer(v, {}, r, rowIndex, colIndex, ds) : String(v);\r
363         if(g === '' || g === '&#160;'){\r
364             g = this.cm.config[colIndex].emptyGroupText || this.emptyGroupText;\r
365         }\r
366         return g;\r
367     },\r
368 \r
369     // private\r
370     getGroupField : function(){\r
371         return this.grid.store.getGroupState();\r
372     },\r
373 \r
374     // private\r
375     afterRender : function(){\r
376         Ext.grid.GroupingView.superclass.afterRender.call(this);\r
377         if(this.grid.deferRowRender){\r
378             this.updateGroupWidths();\r
379         }\r
380     },\r
381 \r
382     // private\r
383     renderRows : function(){\r
384         var groupField = this.getGroupField();\r
385         var eg = !!groupField;\r
386         // if they turned off grouping and the last grouped field is hidden\r
387         if(this.hideGroupedColumn) {\r
388             var colIndex = this.cm.findColumnIndex(groupField),\r
389                 hasLastGroupField = Ext.isDefined(this.lastGroupField);\r
390             if(!eg && hasLastGroupField){\r
391                 this.mainBody.update('');\r
392                 this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false);\r
393                 delete this.lastGroupField;\r
394             }else if (eg && !hasLastGroupField){\r
395                 this.lastGroupField = groupField;\r
396                 this.cm.setHidden(colIndex, true);\r
397             }else if (eg && hasLastGroupField && groupField !== this.lastGroupField) {\r
398                 this.mainBody.update('');\r
399                 var oldIndex = this.cm.findColumnIndex(this.lastGroupField);\r
400                 this.cm.setHidden(oldIndex, false);\r
401                 this.lastGroupField = groupField;\r
402                 this.cm.setHidden(colIndex, true);\r
403             }\r
404         }\r
405         return Ext.grid.GroupingView.superclass.renderRows.apply(\r
406                     this, arguments);\r
407     },\r
408 \r
409     // private\r
410     doRender : function(cs, rs, ds, startRow, colCount, stripe){\r
411         if(rs.length < 1){\r
412             return '';\r
413         }\r
414         var groupField = this.getGroupField(),\r
415             colIndex = this.cm.findColumnIndex(groupField),\r
416             g;\r
417 \r
418         this.enableGrouping = (this.enableGrouping === false) ? false : !!groupField;\r
419 \r
420         if(!this.enableGrouping || this.isUpdating){\r
421             return Ext.grid.GroupingView.superclass.doRender.apply(\r
422                     this, arguments);\r
423         }\r
424         var gstyle = 'width:' + this.getTotalWidth() + ';',\r
425             cfg = this.cm.config[colIndex],\r
426             groupRenderer = cfg.groupRenderer || cfg.renderer,\r
427             prefix = this.showGroupName ? (cfg.groupName || cfg.header)+': ' : '',\r
428             groups = [],\r
429             curGroup, i, len, gid;\r
430 \r
431         for(i = 0, len = rs.length; i < len; i++){\r
432             var rowIndex = startRow + i,\r
433                 r = rs[i],\r
434                 gvalue = r.data[groupField];\r
435 \r
436                 g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds);\r
437             if(!curGroup || curGroup.group != g){\r
438                 gid = this.constructId(gvalue, groupField, colIndex);\r
439                 // if state is defined use it, however state is in terms of expanded\r
440                 // so negate it, otherwise use the default.\r
441                 this.state[gid] = !(Ext.isDefined(this.state[gid]) ? !this.state[gid] : this.startCollapsed);\r
442                 curGroup = {\r
443                     group: g,\r
444                     gvalue: gvalue,\r
445                     text: prefix + g,\r
446                     groupId: gid,\r
447                     startRow: rowIndex,\r
448                     rs: [r],\r
449                     cls: this.state[gid] ? '' : 'x-grid-group-collapsed',\r
450                     style: gstyle\r
451                 };\r
452                 groups.push(curGroup);\r
453             }else{\r
454                 curGroup.rs.push(r);\r
455             }\r
456             r._groupId = gid;\r
457         }\r
458 \r
459         var buf = [];\r
460         for(i = 0, len = groups.length; i < len; i++){\r
461             g = groups[i];\r
462             this.doGroupStart(buf, g, cs, ds, colCount);\r
463             buf[buf.length] = Ext.grid.GroupingView.superclass.doRender.call(\r
464                     this, cs, g.rs, ds, g.startRow, colCount, stripe);\r
465 \r
466             this.doGroupEnd(buf, g, cs, ds, colCount);\r
467         }\r
468         return buf.join('');\r
469     },\r
470 \r
471     /**\r
472      * Dynamically tries to determine the groupId of a specific value\r
473      * @param {String} value\r
474      * @return {String} The group id\r
475      */\r
476     getGroupId : function(value){\r
477         var field = this.getGroupField();\r
478         return this.constructId(value, field, this.cm.findColumnIndex(field));\r
479     },\r
480 \r
481     // private\r
482     constructId : function(value, field, idx){\r
483         var cfg = this.cm.config[idx],\r
484             groupRenderer = cfg.groupRenderer || cfg.renderer,\r
485             val = (this.groupMode == 'value') ? value : this.getGroup(value, {data:{}}, groupRenderer, 0, idx, this.ds);\r
486 \r
487         return this.getPrefix(field) + Ext.util.Format.htmlEncode(val);\r
488     },\r
489 \r
490     // private\r
491     getPrefix: function(field){\r
492         return this.grid.getGridEl().id + '-gp-' + field + '-';\r
493     },\r
494 \r
495     // private\r
496     doGroupStart : function(buf, g, cs, ds, colCount){\r
497         buf[buf.length] = this.startGroup.apply(g);\r
498     },\r
499 \r
500     // private\r
501     doGroupEnd : function(buf, g, cs, ds, colCount){\r
502         buf[buf.length] = this.endGroup;\r
503     },\r
504 \r
505     // private\r
506     getRows : function(){\r
507         if(!this.enableGrouping){\r
508             return Ext.grid.GroupingView.superclass.getRows.call(this);\r
509         }\r
510         var r = [];\r
511         var g, gs = this.getGroups();\r
512         for(var i = 0, len = gs.length; i < len; i++){\r
513             g = gs[i].childNodes[1].childNodes;\r
514             for(var j = 0, jlen = g.length; j < jlen; j++){\r
515                 r[r.length] = g[j];\r
516             }\r
517         }\r
518         return r;\r
519     },\r
520 \r
521     // private\r
522     updateGroupWidths : function(){\r
523         if(!this.enableGrouping || !this.hasRows()){\r
524             return;\r
525         }\r
526         var tw = Math.max(this.cm.getTotalWidth(), this.el.dom.offsetWidth-this.getScrollOffset()) +'px';\r
527         var gs = this.getGroups();\r
528         for(var i = 0, len = gs.length; i < len; i++){\r
529             gs[i].firstChild.style.width = tw;\r
530         }\r
531     },\r
532 \r
533     // private\r
534     onColumnWidthUpdated : function(col, w, tw){\r
535         Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this, col, w, tw);\r
536         this.updateGroupWidths();\r
537     },\r
538 \r
539     // private\r
540     onAllColumnWidthsUpdated : function(ws, tw){\r
541         Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this, ws, tw);\r
542         this.updateGroupWidths();\r
543     },\r
544 \r
545     // private\r
546     onColumnHiddenUpdated : function(col, hidden, tw){\r
547         Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this, col, hidden, tw);\r
548         this.updateGroupWidths();\r
549     },\r
550 \r
551     // private\r
552     onLayout : function(){\r
553         this.updateGroupWidths();\r
554     },\r
555 \r
556     // private\r
557     onBeforeRowSelect : function(sm, rowIndex){\r
558         this.toggleRowIndex(rowIndex, true);\r
559     }\r
560 });\r
561 // private\r
562 Ext.grid.GroupingView.GROUP_ID = 1000;