Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / examples / ux / RowEditor.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 Ext.ns('Ext.ux.grid');
8
9 /**
10  * @class Ext.ux.grid.RowEditor
11  * @extends Ext.Panel 
12  * Plugin (ptype = 'roweditor') that adds the ability to rapidly edit full rows in a grid.
13  * A validation mode may be enabled which uses AnchorTips to notify the user of all
14  * validation errors at once.
15  * 
16  * @ptype roweditor
17  */
18 Ext.ux.grid.RowEditor = Ext.extend(Ext.Panel, {
19     floating: true,
20     shadow: false,
21     layout: 'hbox',
22     cls: 'x-small-editor',
23     buttonAlign: 'center',
24     baseCls: 'x-row-editor',
25     elements: 'header,footer,body',
26     frameWidth: 5,
27     buttonPad: 3,
28     clicksToEdit: 'auto',
29     monitorValid: true,
30     focusDelay: 250,
31     errorSummary: true,
32     
33     saveText: 'Save',
34     cancelText: 'Cancel',
35     commitChangesText: 'You need to commit or cancel your changes',
36     errorText: 'Errors',
37
38     defaults: {
39         normalWidth: true
40     },
41
42     initComponent: function(){
43         Ext.ux.grid.RowEditor.superclass.initComponent.call(this);
44         this.addEvents(
45             /**
46              * @event beforeedit
47              * Fired before the row editor is activated.
48              * If the listener returns <tt>false</tt> the editor will not be activated.
49              * @param {Ext.ux.grid.RowEditor} roweditor This object
50              * @param {Number} rowIndex The rowIndex of the row just edited
51              */
52             'beforeedit',
53             /**
54              * @event canceledit
55              * Fired when the editor is cancelled.
56              * @param {Ext.ux.grid.RowEditor} roweditor This object
57              * @param {Boolean} forced True if the cancel button is pressed, false is the editor was invalid. 
58              */
59             'canceledit',
60             /**
61              * @event validateedit
62              * Fired after a row is edited and passes validation.
63              * If the listener returns <tt>false</tt> changes to the record will not be set.
64              * @param {Ext.ux.grid.RowEditor} roweditor This object
65              * @param {Object} changes Object with changes made to the record.
66              * @param {Ext.data.Record} r The Record that was edited.
67              * @param {Number} rowIndex The rowIndex of the row just edited
68              */
69             'validateedit',
70             /**
71              * @event afteredit
72              * Fired after a row is edited and passes validation.  This event is fired
73              * after the store's update event is fired with this edit.
74              * @param {Ext.ux.grid.RowEditor} roweditor This object
75              * @param {Object} changes Object with changes made to the record.
76              * @param {Ext.data.Record} r The Record that was edited.
77              * @param {Number} rowIndex The rowIndex of the row just edited
78              */
79             'afteredit'
80         );
81     },
82
83     init: function(grid){
84         this.grid = grid;
85         this.ownerCt = grid;
86         if(this.clicksToEdit === 2){
87             grid.on('rowdblclick', this.onRowDblClick, this);
88         }else{
89             grid.on('rowclick', this.onRowClick, this);
90             if(Ext.isIE){
91                 grid.on('rowdblclick', this.onRowDblClick, this);
92             }
93         }
94
95         // stopEditing without saving when a record is removed from Store.
96         grid.getStore().on('remove', function() {
97             this.stopEditing(false);
98         },this);
99
100         grid.on({
101             scope: this,
102             keydown: this.onGridKey,
103             columnresize: this.verifyLayout,
104             columnmove: this.refreshFields,
105             reconfigure: this.refreshFields,
106                 beforedestroy : this.beforedestroy,
107                 destroy : this.destroy,
108             bodyscroll: {
109                 buffer: 250,
110                 fn: this.positionButtons
111             }
112         });
113         grid.getColumnModel().on('hiddenchange', this.verifyLayout, this, {delay:1});
114         grid.getView().on('refresh', this.stopEditing.createDelegate(this, []));
115     },
116
117     beforedestroy: function() {
118         this.grid.getStore().un('remove', this.onStoreRemove, this);
119         this.stopEditing(false);
120         Ext.destroy(this.btns);
121     },
122
123     refreshFields: function(){
124         this.initFields();
125         this.verifyLayout();
126     },
127
128     isDirty: function(){
129         var dirty;
130         this.items.each(function(f){
131             if(String(this.values[f.id]) !== String(f.getValue())){
132                 dirty = true;
133                 return false;
134             }
135         }, this);
136         return dirty;
137     },
138
139     startEditing: function(rowIndex, doFocus){
140         if(this.editing && this.isDirty()){
141             this.showTooltip(this.commitChangesText);
142             return;
143         }
144         if(Ext.isObject(rowIndex)){
145             rowIndex = this.grid.getStore().indexOf(rowIndex);
146         }
147         if(this.fireEvent('beforeedit', this, rowIndex) !== false){
148             this.editing = true;
149             var g = this.grid, view = g.getView(),
150                 row = view.getRow(rowIndex),
151                 record = g.store.getAt(rowIndex);
152                 
153             this.record = record;
154             this.rowIndex = rowIndex;
155             this.values = {};
156             if(!this.rendered){
157                 this.render(view.getEditorParent());
158             }
159             var w = Ext.fly(row).getWidth();
160             this.setSize(w);
161             if(!this.initialized){
162                 this.initFields();
163             }
164             var cm = g.getColumnModel(), fields = this.items.items, f, val;
165             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
166                 val = this.preEditValue(record, cm.getDataIndex(i));
167                 f = fields[i];
168                 f.setValue(val);
169                 this.values[f.id] = Ext.isEmpty(val) ? '' : val;
170             }
171             this.verifyLayout(true);
172             if(!this.isVisible()){
173                 this.setPagePosition(Ext.fly(row).getXY());
174             } else{
175                 this.el.setXY(Ext.fly(row).getXY(), {duration:0.15});
176             }
177             if(!this.isVisible()){
178                 this.show().doLayout();
179             }
180             if(doFocus !== false){
181                 this.doFocus.defer(this.focusDelay, this);
182             }
183         }
184     },
185
186     stopEditing : function(saveChanges){
187         this.editing = false;
188         if(!this.isVisible()){
189             return;
190         }
191         if(saveChanges === false || !this.isValid()){
192             this.hide();
193             this.fireEvent('canceledit', this, saveChanges === false);
194             return;
195         }
196         var changes = {}, 
197             r = this.record, 
198             hasChange = false,
199             cm = this.grid.colModel, 
200             fields = this.items.items;
201         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
202             if(!cm.isHidden(i)){
203                 var dindex = cm.getDataIndex(i);
204                 if(!Ext.isEmpty(dindex)){
205                     var oldValue = r.data[dindex],
206                         value = this.postEditValue(fields[i].getValue(), oldValue, r, dindex);
207                     if(String(oldValue) !== String(value)){
208                         changes[dindex] = value;
209                         hasChange = true;
210                     }
211                 }
212             }
213         }
214         if(hasChange && this.fireEvent('validateedit', this, changes, r, this.rowIndex) !== false){
215             r.beginEdit();
216             Ext.iterate(changes, function(name, value){
217                 r.set(name, value);
218             });
219             r.endEdit();
220             this.fireEvent('afteredit', this, changes, r, this.rowIndex);
221         }
222         this.hide();
223     },
224
225     verifyLayout: function(force){
226         if(this.el && (this.isVisible() || force === true)){
227             var row = this.grid.getView().getRow(this.rowIndex);
228             this.setSize(Ext.fly(row).getWidth(), Ext.fly(row).getHeight() + 9);
229             var cm = this.grid.colModel, fields = this.items.items;
230             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
231                 if(!cm.isHidden(i)){
232                     var adjust = 0;
233                     if(i === (len - 1)){
234                         adjust += 3; // outer padding
235                     } else{
236                         adjust += 1;
237                     }
238                     fields[i].show();
239                     fields[i].setWidth(cm.getColumnWidth(i) - adjust);
240                 } else{
241                     fields[i].hide();
242                 }
243             }
244             this.doLayout();
245             this.positionButtons();
246         }
247     },
248
249     slideHide : function(){
250         this.hide();
251     },
252
253     initFields: function(){
254         var cm = this.grid.getColumnModel(), pm = Ext.layout.ContainerLayout.prototype.parseMargins;
255         this.removeAll(false);
256         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
257             var c = cm.getColumnAt(i),
258                 ed = c.getEditor();
259             if(!ed){
260                 ed = c.displayEditor || new Ext.form.DisplayField();
261             }
262             if(i == 0){
263                 ed.margins = pm('0 1 2 1');
264             } else if(i == len - 1){
265                 ed.margins = pm('0 0 2 1');
266             } else{
267                 ed.margins = pm('0 1 2');
268             }
269             ed.setWidth(cm.getColumnWidth(i));
270             ed.column = c;
271             if(ed.ownerCt !== this){
272                 ed.on('focus', this.ensureVisible, this);
273                 ed.on('specialkey', this.onKey, this);
274             }
275             this.insert(i, ed);
276         }
277         this.initialized = true;
278     },
279
280     onKey: function(f, e){
281         if(e.getKey() === e.ENTER){
282             this.stopEditing(true);
283             e.stopPropagation();
284         }
285     },
286
287     onGridKey: function(e){
288         if(e.getKey() === e.ENTER && !this.isVisible()){
289             var r = this.grid.getSelectionModel().getSelected();
290             if(r){
291                 var index = this.grid.store.indexOf(r);
292                 this.startEditing(index);
293                 e.stopPropagation();
294             }
295         }
296     },
297
298     ensureVisible: function(editor){
299         if(this.isVisible()){
300              this.grid.getView().ensureVisible(this.rowIndex, this.grid.colModel.getIndexById(editor.column.id), true);
301         }
302     },
303
304     onRowClick: function(g, rowIndex, e){
305         if(this.clicksToEdit == 'auto'){
306             var li = this.lastClickIndex;
307             this.lastClickIndex = rowIndex;
308             if(li != rowIndex && !this.isVisible()){
309                 return;
310             }
311         }
312         this.startEditing(rowIndex, false);
313         this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
314     },
315
316     onRowDblClick: function(g, rowIndex, e){
317         this.startEditing(rowIndex, false);
318         this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
319     },
320
321     onRender: function(){
322         Ext.ux.grid.RowEditor.superclass.onRender.apply(this, arguments);
323         this.el.swallowEvent(['keydown', 'keyup', 'keypress']);
324         this.btns = new Ext.Panel({
325             baseCls: 'x-plain',
326             cls: 'x-btns',
327             elements:'body',
328             layout: 'table',
329             width: (this.minButtonWidth * 2) + (this.frameWidth * 2) + (this.buttonPad * 4), // width must be specified for IE
330             items: [{
331                 ref: 'saveBtn',
332                 itemId: 'saveBtn',
333                 xtype: 'button',
334                 text: this.saveText,
335                 width: this.minButtonWidth,
336                 handler: this.stopEditing.createDelegate(this, [true])
337             }, {
338                 xtype: 'button',
339                 text: this.cancelText,
340                 width: this.minButtonWidth,
341                 handler: this.stopEditing.createDelegate(this, [false])
342             }]
343         });
344         this.btns.render(this.bwrap);
345     },
346
347     afterRender: function(){
348         Ext.ux.grid.RowEditor.superclass.afterRender.apply(this, arguments);
349         this.positionButtons();
350         if(this.monitorValid){
351             this.startMonitoring();
352         }
353     },
354
355     onShow: function(){
356         if(this.monitorValid){
357             this.startMonitoring();
358         }
359         Ext.ux.grid.RowEditor.superclass.onShow.apply(this, arguments);
360     },
361
362     onHide: function(){
363         Ext.ux.grid.RowEditor.superclass.onHide.apply(this, arguments);
364         this.stopMonitoring();
365         this.grid.getView().focusRow(this.rowIndex);
366     },
367
368     positionButtons: function(){
369         if(this.btns){
370             var g = this.grid,
371                 h = this.el.dom.clientHeight,
372                 view = g.getView(),
373                 scroll = view.scroller.dom.scrollLeft,
374                 bw = this.btns.getWidth(),
375                 width = Math.min(g.getWidth(), g.getColumnModel().getTotalWidth());
376                 
377             this.btns.el.shift({left: (width/2)-(bw/2)+scroll, top: h - 2, stopFx: true, duration:0.2});
378         }
379     },
380
381     // private
382     preEditValue : function(r, field){
383         var value = r.data[field];
384         return this.autoEncode && typeof value === 'string' ? Ext.util.Format.htmlDecode(value) : value;
385     },
386
387     // private
388     postEditValue : function(value, originalValue, r, field){
389         return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlEncode(value) : value;
390     },
391
392     doFocus: function(pt){
393         if(this.isVisible()){
394             var index = 0,
395                 cm = this.grid.getColumnModel(),
396                 c;
397             if(pt){
398                 index = this.getTargetColumnIndex(pt);
399             }
400             for(var i = index||0, len = cm.getColumnCount(); i < len; i++){
401                 c = cm.getColumnAt(i);
402                 if(!c.hidden && c.getEditor()){
403                     c.getEditor().focus();
404                     break;
405                 }
406             }
407         }
408     },
409
410     getTargetColumnIndex: function(pt){
411         var grid = this.grid, 
412             v = grid.view,
413             x = pt.left,
414             cms = grid.colModel.config,
415             i = 0, 
416             match = false;
417         for(var len = cms.length, c; c = cms[i]; i++){
418             if(!c.hidden){
419                 if(Ext.fly(v.getHeaderCell(i)).getRegion().right >= x){
420                     match = i;
421                     break;
422                 }
423             }
424         }
425         return match;
426     },
427
428     startMonitoring : function(){
429         if(!this.bound && this.monitorValid){
430             this.bound = true;
431             Ext.TaskMgr.start({
432                 run : this.bindHandler,
433                 interval : this.monitorPoll || 200,
434                 scope: this
435             });
436         }
437     },
438
439     stopMonitoring : function(){
440         this.bound = false;
441         if(this.tooltip){
442             this.tooltip.hide();
443         }
444     },
445
446     isValid: function(){
447         var valid = true;
448         this.items.each(function(f){
449             if(!f.isValid(true)){
450                 valid = false;
451                 return false;
452             }
453         });
454         return valid;
455     },
456
457     // private
458     bindHandler : function(){
459         if(!this.bound){
460             return false; // stops binding
461         }
462         var valid = this.isValid();
463         if(!valid && this.errorSummary){
464             this.showTooltip(this.getErrorText().join(''));
465         }
466         this.btns.saveBtn.setDisabled(!valid);
467         this.fireEvent('validation', this, valid);
468     },
469
470     showTooltip: function(msg){
471         var t = this.tooltip;
472         if(!t){
473             t = this.tooltip = new Ext.ToolTip({
474                 maxWidth: 600,
475                 cls: 'errorTip',
476                 width: 300,
477                 title: this.errorText,
478                 autoHide: false,
479                 anchor: 'left',
480                 anchorToTarget: true,
481                 mouseOffset: [40,0]
482             });
483         }
484         var v = this.grid.getView(),
485             top = parseInt(this.el.dom.style.top, 10),
486             scroll = v.scroller.dom.scrollTop,
487             h = this.el.getHeight();
488                 
489         if(top + h >= scroll){
490             t.initTarget(this.items.last().getEl());
491             if(!t.rendered){
492                 t.show();
493                 t.hide();
494             }
495             t.body.update(msg);
496             t.doAutoWidth(20);
497             t.show();
498         }else if(t.rendered){
499             t.hide();
500         }
501     },
502
503     getErrorText: function(){
504         var data = ['<ul>'];
505         this.items.each(function(f){
506             if(!f.isValid(true)){
507                 data.push('<li>', f.getActiveError(), '</li>');
508             }
509         });
510         data.push('</ul>');
511         return data;
512     }
513 });
514 Ext.preg('roweditor', Ext.ux.grid.RowEditor);