PageRenderTime 48ms CodeModel.GetById 32ms app.highlight 13ms RepoModel.GetById 0ms app.codeStats 0ms

/ext-4.1.0_b3/src/Editor.js

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