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