Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / src / widgets / grid / RowSelectionModel.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.grid.RowSelectionModel
9  * @extends Ext.grid.AbstractSelectionModel
10  * The default SelectionModel used by {@link Ext.grid.GridPanel}.
11  * It supports multiple selections and keyboard selection/navigation. The objects stored
12  * as selections and returned by {@link #getSelected}, and {@link #getSelections} are
13  * the {@link Ext.data.Record Record}s which provide the data for the selected rows.
14  * @constructor
15  * @param {Object} config
16  */
17 Ext.grid.RowSelectionModel = Ext.extend(Ext.grid.AbstractSelectionModel,  {
18     /**
19      * @cfg {Boolean} singleSelect
20      * <tt>true</tt> to allow selection of only one row at a time (defaults to <tt>false</tt>
21      * allowing multiple selections)
22      */
23     singleSelect : false,
24     
25     constructor : function(config){
26         Ext.apply(this, config);
27         this.selections = new Ext.util.MixedCollection(false, function(o){
28             return o.id;
29         });
30
31         this.last = false;
32         this.lastActive = false;
33
34         this.addEvents(
35                 /**
36                  * @event selectionchange
37                  * Fires when the selection changes
38                  * @param {SelectionModel} this
39                  */
40                 'selectionchange',
41                 /**
42                  * @event beforerowselect
43                  * Fires before a row is selected, return false to cancel the selection.
44                  * @param {SelectionModel} this
45                  * @param {Number} rowIndex The index to be selected
46                  * @param {Boolean} keepExisting False if other selections will be cleared
47                  * @param {Record} record The record to be selected
48                  */
49                 'beforerowselect',
50                 /**
51                  * @event rowselect
52                  * Fires when a row is selected.
53                  * @param {SelectionModel} this
54                  * @param {Number} rowIndex The selected index
55                  * @param {Ext.data.Record} r The selected record
56                  */
57                 'rowselect',
58                 /**
59                  * @event rowdeselect
60                  * Fires when a row is deselected.  To prevent deselection
61                  * {@link Ext.grid.AbstractSelectionModel#lock lock the selections}. 
62                  * @param {SelectionModel} this
63                  * @param {Number} rowIndex
64                  * @param {Record} record
65                  */
66                 'rowdeselect'
67         );
68         Ext.grid.RowSelectionModel.superclass.constructor.call(this);
69     },
70
71     /**
72      * @cfg {Boolean} moveEditorOnEnter
73      * <tt>false</tt> to turn off moving the editor to the next row down when the enter key is pressed
74      * or the next row up when shift + enter keys are pressed.
75      */
76     // private
77     initEvents : function(){
78
79         if(!this.grid.enableDragDrop && !this.grid.enableDrag){
80             this.grid.on('rowmousedown', this.handleMouseDown, this);
81         }
82
83         this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), {
84             'up' : function(e){
85                 if(!e.shiftKey || this.singleSelect){
86                     this.selectPrevious(false);
87                 }else if(this.last !== false && this.lastActive !== false){
88                     var last = this.last;
89                     this.selectRange(this.last,  this.lastActive-1);
90                     this.grid.getView().focusRow(this.lastActive);
91                     if(last !== false){
92                         this.last = last;
93                     }
94                 }else{
95                     this.selectFirstRow();
96                 }
97             },
98             'down' : function(e){
99                 if(!e.shiftKey || this.singleSelect){
100                     this.selectNext(false);
101                 }else if(this.last !== false && this.lastActive !== false){
102                     var last = this.last;
103                     this.selectRange(this.last,  this.lastActive+1);
104                     this.grid.getView().focusRow(this.lastActive);
105                     if(last !== false){
106                         this.last = last;
107                     }
108                 }else{
109                     this.selectFirstRow();
110                 }
111             },
112             scope: this
113         });
114
115         this.grid.getView().on({
116             scope: this,
117             refresh: this.onRefresh,
118             rowupdated: this.onRowUpdated,
119             rowremoved: this.onRemove
120         });
121     },
122
123     // private
124     onRefresh : function(){
125         var ds = this.grid.store, index;
126         var s = this.getSelections();
127         this.clearSelections(true);
128         for(var i = 0, len = s.length; i < len; i++){
129             var r = s[i];
130             if((index = ds.indexOfId(r.id)) != -1){
131                 this.selectRow(index, true);
132             }
133         }
134         if(s.length != this.selections.getCount()){
135             this.fireEvent('selectionchange', this);
136         }
137     },
138
139     // private
140     onRemove : function(v, index, r){
141         if(this.selections.remove(r) !== false){
142             this.fireEvent('selectionchange', this);
143         }
144     },
145
146     // private
147     onRowUpdated : function(v, index, r){
148         if(this.isSelected(r)){
149             v.onRowSelect(index);
150         }
151     },
152
153     /**
154      * Select records.
155      * @param {Array} records The records to select
156      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep existing selections
157      */
158     selectRecords : function(records, keepExisting){
159         if(!keepExisting){
160             this.clearSelections();
161         }
162         var ds = this.grid.store;
163         for(var i = 0, len = records.length; i < len; i++){
164             this.selectRow(ds.indexOf(records[i]), true);
165         }
166     },
167
168     /**
169      * Gets the number of selected rows.
170      * @return {Number}
171      */
172     getCount : function(){
173         return this.selections.length;
174     },
175
176     /**
177      * Selects the first row in the grid.
178      */
179     selectFirstRow : function(){
180         this.selectRow(0);
181     },
182
183     /**
184      * Select the last row.
185      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep existing selections
186      */
187     selectLastRow : function(keepExisting){
188         this.selectRow(this.grid.store.getCount() - 1, keepExisting);
189     },
190
191     /**
192      * Selects the row immediately following the last selected row.
193      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep existing selections
194      * @return {Boolean} <tt>true</tt> if there is a next row, else <tt>false</tt>
195      */
196     selectNext : function(keepExisting){
197         if(this.hasNext()){
198             this.selectRow(this.last+1, keepExisting);
199             this.grid.getView().focusRow(this.last);
200             return true;
201         }
202         return false;
203     },
204
205     /**
206      * Selects the row that precedes the last selected row.
207      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep existing selections
208      * @return {Boolean} <tt>true</tt> if there is a previous row, else <tt>false</tt>
209      */
210     selectPrevious : function(keepExisting){
211         if(this.hasPrevious()){
212             this.selectRow(this.last-1, keepExisting);
213             this.grid.getView().focusRow(this.last);
214             return true;
215         }
216         return false;
217     },
218
219     /**
220      * Returns true if there is a next record to select
221      * @return {Boolean}
222      */
223     hasNext : function(){
224         return this.last !== false && (this.last+1) < this.grid.store.getCount();
225     },
226
227     /**
228      * Returns true if there is a previous record to select
229      * @return {Boolean}
230      */
231     hasPrevious : function(){
232         return !!this.last;
233     },
234
235
236     /**
237      * Returns the selected records
238      * @return {Array} Array of selected records
239      */
240     getSelections : function(){
241         return [].concat(this.selections.items);
242     },
243
244     /**
245      * Returns the first selected record.
246      * @return {Record}
247      */
248     getSelected : function(){
249         return this.selections.itemAt(0);
250     },
251
252     /**
253      * Calls the passed function with each selection. If the function returns
254      * <tt>false</tt>, iteration is stopped and this function returns
255      * <tt>false</tt>. Otherwise it returns <tt>true</tt>.
256      * @param {Function} fn The function to call upon each iteration. It is passed the selected {@link Ext.data.Record Record}.
257      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this RowSelectionModel.
258      * @return {Boolean} true if all selections were iterated
259      */
260     each : function(fn, scope){
261         var s = this.getSelections();
262         for(var i = 0, len = s.length; i < len; i++){
263             if(fn.call(scope || this, s[i], i) === false){
264                 return false;
265             }
266         }
267         return true;
268     },
269
270     /**
271      * Clears all selections if the selection model
272      * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}.
273      * @param {Boolean} fast (optional) <tt>true</tt> to bypass the
274      * conditional checks and events described in {@link #deselectRow}.
275      */
276     clearSelections : function(fast){
277         if(this.isLocked()){
278             return;
279         }
280         if(fast !== true){
281             var ds = this.grid.store;
282             var s = this.selections;
283             s.each(function(r){
284                 this.deselectRow(ds.indexOfId(r.id));
285             }, this);
286             s.clear();
287         }else{
288             this.selections.clear();
289         }
290         this.last = false;
291     },
292
293
294     /**
295      * Selects all rows if the selection model
296      * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}. 
297      */
298     selectAll : function(){
299         if(this.isLocked()){
300             return;
301         }
302         this.selections.clear();
303         for(var i = 0, len = this.grid.store.getCount(); i < len; i++){
304             this.selectRow(i, true);
305         }
306     },
307
308     /**
309      * Returns <tt>true</tt> if there is a selection.
310      * @return {Boolean}
311      */
312     hasSelection : function(){
313         return this.selections.length > 0;
314     },
315
316     /**
317      * Returns <tt>true</tt> if the specified row is selected.
318      * @param {Number/Record} index The record or index of the record to check
319      * @return {Boolean}
320      */
321     isSelected : function(index){
322         var r = Ext.isNumber(index) ? this.grid.store.getAt(index) : index;
323         return (r && this.selections.key(r.id) ? true : false);
324     },
325
326     /**
327      * Returns <tt>true</tt> if the specified record id is selected.
328      * @param {String} id The id of record to check
329      * @return {Boolean}
330      */
331     isIdSelected : function(id){
332         return (this.selections.key(id) ? true : false);
333     },
334
335     // private
336     handleMouseDown : function(g, rowIndex, e){
337         if(e.button !== 0 || this.isLocked()){
338             return;
339         }
340         var view = this.grid.getView();
341         if(e.shiftKey && !this.singleSelect && this.last !== false){
342             var last = this.last;
343             this.selectRange(last, rowIndex, e.ctrlKey);
344             this.last = last; // reset the last
345             view.focusRow(rowIndex);
346         }else{
347             var isSelected = this.isSelected(rowIndex);
348             if(e.ctrlKey && isSelected){
349                 this.deselectRow(rowIndex);
350             }else if(!isSelected || this.getCount() > 1){
351                 this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
352                 view.focusRow(rowIndex);
353             }
354         }
355     },
356
357     /**
358      * Selects multiple rows.
359      * @param {Array} rows Array of the indexes of the row to select
360      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep
361      * existing selections (defaults to <tt>false</tt>)
362      */
363     selectRows : function(rows, keepExisting){
364         if(!keepExisting){
365             this.clearSelections();
366         }
367         for(var i = 0, len = rows.length; i < len; i++){
368             this.selectRow(rows[i], true);
369         }
370     },
371
372     /**
373      * Selects a range of rows if the selection model
374      * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}.
375      * All rows in between startRow and endRow are also selected.
376      * @param {Number} startRow The index of the first row in the range
377      * @param {Number} endRow The index of the last row in the range
378      * @param {Boolean} keepExisting (optional) True to retain existing selections
379      */
380     selectRange : function(startRow, endRow, keepExisting){
381         var i;
382         if(this.isLocked()){
383             return;
384         }
385         if(!keepExisting){
386             this.clearSelections();
387         }
388         if(startRow <= endRow){
389             for(i = startRow; i <= endRow; i++){
390                 this.selectRow(i, true);
391             }
392         }else{
393             for(i = startRow; i >= endRow; i--){
394                 this.selectRow(i, true);
395             }
396         }
397     },
398
399     /**
400      * Deselects a range of rows if the selection model
401      * {@link Ext.grid.AbstractSelectionModel#isLocked is not locked}.  
402      * All rows in between startRow and endRow are also deselected.
403      * @param {Number} startRow The index of the first row in the range
404      * @param {Number} endRow The index of the last row in the range
405      */
406     deselectRange : function(startRow, endRow, preventViewNotify){
407         if(this.isLocked()){
408             return;
409         }
410         for(var i = startRow; i <= endRow; i++){
411             this.deselectRow(i, preventViewNotify);
412         }
413     },
414
415     /**
416      * Selects a row.  Before selecting a row, checks if the selection model
417      * {@link Ext.grid.AbstractSelectionModel#isLocked is locked} and fires the
418      * {@link #beforerowselect} event.  If these checks are satisfied the row
419      * will be selected and followed up by  firing the {@link #rowselect} and
420      * {@link #selectionchange} events.
421      * @param {Number} row The index of the row to select
422      * @param {Boolean} keepExisting (optional) <tt>true</tt> to keep existing selections
423      * @param {Boolean} preventViewNotify (optional) Specify <tt>true</tt> to
424      * prevent notifying the view (disables updating the selected appearance)
425      */
426     selectRow : function(index, keepExisting, preventViewNotify){
427         if(this.isLocked() || (index < 0 || index >= this.grid.store.getCount()) || (keepExisting && this.isSelected(index))){
428             return;
429         }
430         var r = this.grid.store.getAt(index);
431         if(r && this.fireEvent('beforerowselect', this, index, keepExisting, r) !== false){
432             if(!keepExisting || this.singleSelect){
433                 this.clearSelections();
434             }
435             this.selections.add(r);
436             this.last = this.lastActive = index;
437             if(!preventViewNotify){
438                 this.grid.getView().onRowSelect(index);
439             }
440             this.fireEvent('rowselect', this, index, r);
441             this.fireEvent('selectionchange', this);
442         }
443     },
444
445     /**
446      * Deselects a row.  Before deselecting a row, checks if the selection model
447      * {@link Ext.grid.AbstractSelectionModel#isLocked is locked}.
448      * If this check is satisfied the row will be deselected and followed up by
449      * firing the {@link #rowdeselect} and {@link #selectionchange} events.
450      * @param {Number} row The index of the row to deselect
451      * @param {Boolean} preventViewNotify (optional) Specify <tt>true</tt> to
452      * prevent notifying the view (disables updating the selected appearance)
453      */
454     deselectRow : function(index, preventViewNotify){
455         if(this.isLocked()){
456             return;
457         }
458         if(this.last == index){
459             this.last = false;
460         }
461         if(this.lastActive == index){
462             this.lastActive = false;
463         }
464         var r = this.grid.store.getAt(index);
465         if(r){
466             this.selections.remove(r);
467             if(!preventViewNotify){
468                 this.grid.getView().onRowDeselect(index);
469             }
470             this.fireEvent('rowdeselect', this, index, r);
471             this.fireEvent('selectionchange', this);
472         }
473     },
474
475     // private
476     restoreLast : function(){
477         if(this._last){
478             this.last = this._last;
479         }
480     },
481
482     // private
483     acceptsNav : function(row, col, cm){
484         return !cm.isHidden(col) && cm.isCellEditable(col, row);
485     },
486
487     // private
488     onEditorKey : function(field, e){
489         var k = e.getKey(), 
490             newCell, 
491             g = this.grid, 
492             last = g.lastEdit,
493             ed = g.activeEditor,
494             ae, last, r, c;
495         var shift = e.shiftKey;
496         if(k == e.TAB){
497             e.stopEvent();
498             ed.completeEdit();
499             if(shift){
500                 newCell = g.walkCells(ed.row, ed.col-1, -1, this.acceptsNav, this);
501             }else{
502                 newCell = g.walkCells(ed.row, ed.col+1, 1, this.acceptsNav, this);
503             }
504         }else if(k == e.ENTER){
505             if(this.moveEditorOnEnter !== false){
506                 if(shift){
507                     newCell = g.walkCells(last.row - 1, last.col, -1, this.acceptsNav, this);
508                 }else{
509                     newCell = g.walkCells(last.row + 1, last.col, 1, this.acceptsNav, this);
510                 }
511             }
512         }
513         if(newCell){
514             r = newCell[0];
515             c = newCell[1];
516
517             if(last.row != r){
518                 this.selectRow(r); // *** highlight newly-selected cell and update selection
519             }
520
521             if(g.isEditor && g.editing){ // *** handle tabbing while editorgrid is in edit mode
522                 ae = g.activeEditor;
523                 if(ae && ae.field.triggerBlur){
524                     // *** if activeEditor is a TriggerField, explicitly call its triggerBlur() method
525                     ae.field.triggerBlur();
526                 }
527             }
528             g.startEditing(r, c);
529         }
530     },
531     
532     destroy : function(){
533         if(this.rowNav){
534             this.rowNav.disable();
535             this.rowNav = null;
536         }
537         Ext.grid.RowSelectionModel.superclass.destroy.call(this);
538     }
539 });