Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / Editor.js
1 /**
2  * @class Ext.Editor
3  * @extends Ext.Component
4  *
5  * <p>
6  * The Editor class is used to provide inline editing for elements on the page. The editor
7  * is backed by a {@link Ext.form.field.Field} that will be displayed to edit the underlying content.
8  * The editor is a floating Component, when the editor is shown it is automatically aligned to
9  * display over the top of the bound element it is editing. The Editor contains several options
10  * for how to handle key presses:
11  * <ul>
12  * <li>{@link #completeOnEnter}</li>
13  * <li>{@link #cancelOnEsc}</li>
14  * <li>{@link #swallowKeys}</li>
15  * </ul>
16  * It also has options for how to use the value once the editor has been activated:
17  * <ul>
18  * <li>{@link #revertInvalid}</li>
19  * <li>{@link #ignoreNoChange}</li>
20  * <li>{@link #updateEl}</li>
21  * </ul>
22  * Sample usage:
23  * </p>
24  * <pre><code>
25 var editor = new Ext.Editor({
26     updateEl: true, // update the innerHTML of the bound element when editing completes
27     field: {
28         xtype: 'textfield'
29     }
30 });
31 var el = Ext.get('my-text'); // The element to 'edit'
32 editor.startEdit(el); // The value of the field will be taken as the innerHTML of the element.
33  * </code></pre>
34  * {@img Ext.Editor/Ext.Editor.png Ext.Editor component}
35  *
36  * @constructor
37  * Create a new Editor
38  * @param {Object} config The config object
39  * @xtype editor
40  */
41 Ext.define('Ext.Editor', {
42
43     /* Begin Definitions */
44
45     extend: 'Ext.Component',
46
47     alias: 'widget.editor',
48
49     requires: ['Ext.layout.component.Editor'],
50
51     /* End Definitions */
52
53    componentLayout: 'editor',
54
55     /**
56     * @cfg {Ext.form.field.Field} field
57     * The Field object (or descendant) or config object for field
58     */
59
60     /**
61      * @cfg {Boolean} allowBlur
62      * True to {@link #completeEdit complete the editing process} if in edit mode when the
63      * field is blurred. Defaults to <tt>true</tt>.
64      */
65     allowBlur: true,
66
67     /**
68      * @cfg {Boolean/Object} autoSize
69      * True for the editor to automatically adopt the size of the underlying field. Otherwise, an object
70      * can be passed to indicate where to get each dimension. The available properties are 'boundEl' and
71      * 'field'. If a dimension is not specified, it will use the underlying height/width specified on
72      * the editor object.
73      * Examples:
74      * <pre><code>
75 autoSize: true // The editor will be sized to the height/width of the field
76
77 height: 21,
78 autoSize: {
79     width: 'boundEl' // The width will be determined by the width of the boundEl, the height from the editor (21)
80 }
81
82 autoSize: {
83     width: 'field', // Width from the field
84     height: 'boundEl' // Height from the boundEl
85 }
86      * </pre></code>
87      */
88
89     /**
90      * @cfg {Boolean} revertInvalid
91      * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
92      * validation fails (defaults to true)
93      */
94     revertInvalid: true,
95
96     /**
97      * @cfg {Boolean} ignoreNoChange
98      * True to skip the edit completion process (no save, no events fired) if the user completes an edit and
99      * the value has not changed (defaults to false).  Applies only to string values - edits for other data types
100      * will never be ignored.
101      */
102
103     /**
104      * @cfg {Boolean} hideEl
105      * False to keep the bound element visible while the editor is displayed (defaults to true)
106      */
107
108     /**
109      * @cfg {Mixed} value
110      * The data value of the underlying field (defaults to "")
111      */
112     value : '',
113
114     /**
115      * @cfg {String} alignment
116      * The position to align to (see {@link Ext.core.Element#alignTo} for more details, defaults to "c-c?").
117      */
118     alignment: 'c-c?',
119
120     /**
121      * @cfg {Array} offsets
122      * The offsets to use when aligning (see {@link Ext.core.Element#alignTo} for more details. Defaults to <tt>[0, 0]</tt>.
123      */
124     offsets: [0, 0],
125
126     /**
127      * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
128      * for bottom-right shadow (defaults to "frame")
129      */
130     shadow : 'frame',
131
132     /**
133      * @cfg {Boolean} constrain True to constrain the editor to the viewport
134      */
135     constrain : false,
136
137     /**
138      * @cfg {Boolean} swallowKeys Handle the keydown/keypress events so they don't propagate (defaults to true)
139      */
140     swallowKeys : true,
141
142     /**
143      * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed. Defaults to <tt>true</tt>.
144      */
145     completeOnEnter : true,
146
147     /**
148      * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed. Defaults to <tt>true</tt>.
149      */
150     cancelOnEsc : true,
151
152     /**
153      * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
154      */
155     updateEl : false,
156
157     /**
158      * @cfg {Mixed} parentEl An element to render to. Defaults to the <tt>document.body</tt>.
159      */
160
161     // private overrides
162     hidden: true,
163     baseCls: Ext.baseCSSPrefix + 'editor',
164
165     initComponent : function() {
166         var me = this,
167             field = me.field = Ext.ComponentManager.create(me.field, 'textfield');
168
169         Ext.apply(field, {
170             inEditor: true,
171             msgTarget: field.msgTarget == 'title' ? 'title' :  'qtip'
172         });
173         me.mon(field, {
174             scope: me,
175             blur: {
176                 fn: me.onBlur,
177                 // slight delay to avoid race condition with startEdits (e.g. grid view refresh)
178                 delay: 1
179             },
180             specialkey: me.onSpecialKey
181         });
182
183         if (field.grow) {
184             me.mon(field, 'autosize', me.onAutoSize,  me, {delay: 1});
185         }
186         me.floating = {
187             constrain: me.constrain
188         };
189
190         me.callParent(arguments);
191
192         me.addEvents(
193             /**
194              * @event beforestartedit
195              * Fires when editing is initiated, but before the value changes.  Editing can be canceled by returning
196              * false from the handler of this event.
197              * @param {Ext.Editor} this
198              * @param {Ext.core.Element} boundEl The underlying element bound to this editor
199              * @param {Mixed} value The field value being set
200              */
201             'beforestartedit',
202             /**
203              * @event startedit
204              * Fires when this editor is displayed
205              * @param {Ext.Editor} this
206              * @param {Ext.core.Element} boundEl The underlying element bound to this editor
207              * @param {Mixed} value The starting field value
208              */
209             'startedit',
210             /**
211              * @event beforecomplete
212              * Fires after a change has been made to the field, but before the change is reflected in the underlying
213              * field.  Saving the change to the field can be canceled by returning false from the handler of this event.
214              * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
215              * event will not fire since no edit actually occurred.
216              * @param {Editor} this
217              * @param {Mixed} value The current field value
218              * @param {Mixed} startValue The original field value
219              */
220             'beforecomplete',
221             /**
222              * @event complete
223              * Fires after editing is complete and any changed value has been written to the underlying field.
224              * @param {Ext.Editor} this
225              * @param {Mixed} value The current field value
226              * @param {Mixed} startValue The original field value
227              */
228             'complete',
229             /**
230              * @event canceledit
231              * Fires after editing has been canceled and the editor's value has been reset.
232              * @param {Ext.Editor} this
233              * @param {Mixed} value The user-entered field value that was discarded
234              * @param {Mixed} startValue The original field value that was set back into the editor after cancel
235              */
236             'canceledit',
237             /**
238              * @event specialkey
239              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.  You can check
240              * {@link Ext.EventObject#getKey} to determine which key was pressed.
241              * @param {Ext.Editor} this
242              * @param {Ext.form.field.Field} The field attached to this editor
243              * @param {Ext.EventObject} event The event object
244              */
245             'specialkey'
246         );
247     },
248
249     // private
250     onAutoSize: function(){
251         this.doComponentLayout();
252     },
253
254     // private
255     onRender : function(ct, position) {
256         var me = this,
257             field = me.field;
258
259         me.callParent(arguments);
260
261         field.render(me.el);
262         //field.hide();
263         // Ensure the field doesn't get submitted as part of any form
264         field.inputEl.dom.name = '';
265         if (me.swallowKeys) {
266             field.inputEl.swallowEvent([
267                 'keypress', // *** Opera
268                 'keydown'   // *** all other browsers
269             ]);
270         }
271     },
272
273     // private
274     onSpecialKey : function(field, event) {
275         var me = this,
276             key = event.getKey(),
277             complete = me.completeOnEnter && key == event.ENTER,
278             cancel = me.cancelOnEsc && key == event.ESC;
279
280         if (complete || cancel) {
281             event.stopEvent();
282             // Must defer this slightly to prevent exiting edit mode before the field's own
283             // key nav can handle the enter key, e.g. selecting an item in a combobox list
284             Ext.defer(function() {
285                 if (complete) {
286                     me.completeEdit();
287                 } else {
288                     me.cancelEdit();
289                 }
290                 if (field.triggerBlur) {
291                     field.triggerBlur();
292                 }
293             }, 10);
294         }
295
296         this.fireEvent('specialkey', this, field, event);
297     },
298
299     /**
300      * Starts the editing process and shows the editor.
301      * @param {Mixed} el The element to edit
302      * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
303       * to the innerHTML of el.
304      */
305     startEdit : function(el, value) {
306         var me = this,
307             field = me.field;
308
309         me.completeEdit();
310         me.boundEl = Ext.get(el);
311         value = Ext.isDefined(value) ? value : me.boundEl.dom.innerHTML;
312
313         if (!me.rendered) {
314             me.render(me.parentEl || document.body);
315         }
316
317         if (me.fireEvent('beforestartedit', me, me.boundEl, value) !== false) {
318             me.startValue = value;
319             me.show();
320             field.reset();
321             field.setValue(value);
322             me.realign(true);
323             field.focus(false, 10);
324             if (field.autoSize) {
325                 field.autoSize();
326             }
327             me.editing = true;
328         }
329     },
330
331     /**
332      * Realigns the editor to the bound field based on the current alignment config value.
333      * @param {Boolean} autoSize (optional) True to size the field to the dimensions of the bound element.
334      */
335     realign : function(autoSize) {
336         var me = this;
337         if (autoSize === true) {
338             me.doComponentLayout();
339         }
340         me.alignTo(me.boundEl, me.alignment, me.offsets);
341     },
342
343     /**
344      * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
345      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
346      */
347     completeEdit : function(remainVisible) {
348         var me = this,
349             field = me.field,
350             value;
351
352         if (!me.editing) {
353             return;
354         }
355
356         // Assert combo values first
357         if (field.assertValue) {
358             field.assertValue();
359         }
360
361         value = me.getValue();
362         if (!field.isValid()) {
363             if (me.revertInvalid !== false) {
364                 me.cancelEdit(remainVisible);
365             }
366             return;
367         }
368
369         if (String(value) === String(me.startValue) && me.ignoreNoChange) {
370             me.hideEdit(remainVisible);
371             return;
372         }
373
374         if (me.fireEvent('beforecomplete', me, value, me.startValue) !== false) {
375             // Grab the value again, may have changed in beforecomplete
376             value = me.getValue();
377             if (me.updateEl && me.boundEl) {
378                 me.boundEl.update(value);
379             }
380             me.hideEdit(remainVisible);
381             me.fireEvent('complete', me, value, me.startValue);
382         }
383     },
384
385     // private
386     onShow : function() {
387         var me = this;
388
389         me.callParent(arguments);
390         if (me.hideEl !== false) {
391             me.boundEl.hide();
392         }
393         me.fireEvent("startedit", me.boundEl, me.startValue);
394     },
395
396     /**
397      * Cancels the editing process and hides the editor without persisting any changes.  The field value will be
398      * reverted to the original starting value.
399      * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
400      * cancel (defaults to false)
401      */
402     cancelEdit : function(remainVisible) {
403         var me = this,
404             startValue = me.startValue,
405             value;
406
407         if (me.editing) {
408             value = me.getValue();
409             me.setValue(startValue);
410             me.hideEdit(remainVisible);
411             me.fireEvent('canceledit', me, value, startValue);
412         }
413     },
414
415     // private
416     hideEdit: function(remainVisible) {
417         if (remainVisible !== true) {
418             this.editing = false;
419             this.hide();
420         }
421     },
422
423     // private
424     onBlur : function() {
425         var me = this;
426
427         // selectSameEditor flag allows the same editor to be started without onBlur firing on itself
428         if(me.allowBlur === true && me.editing && me.selectSameEditor !== true) {
429             me.completeEdit();
430         }
431     },
432
433     // private
434     onHide : function() {
435         var me = this,
436             field = me.field;
437
438         if (me.editing) {
439             me.completeEdit();
440             return;
441         }
442         field.blur();
443         if (field.collapse) {
444             field.collapse();
445         }
446
447         //field.hide();
448         if (me.hideEl !== false) {
449             me.boundEl.show();
450         }
451         me.callParent(arguments);
452     },
453
454     /**
455      * Sets the data value of the editor
456      * @param {Mixed} value Any valid value supported by the underlying field
457      */
458     setValue : function(value) {
459         this.field.setValue(value);
460     },
461
462     /**
463      * Gets the data value of the editor
464      * @return {Mixed} The data value
465      */
466     getValue : function() {
467         return this.field.getValue();
468     },
469
470     beforeDestroy : function() {
471         var me = this;
472
473         Ext.destroy(me.field);
474         delete me.field;
475         delete me.parentEl;
476         delete me.boundEl;
477
478         me.callParent(arguments);
479     }
480 });