Upgrade to ExtJS 4.0.7 - Released 10/19/2011
[extjs.git] / src / ProgressBar.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * An updateable progress bar component. The progress bar supports two different modes: manual and automatic.
17  *
18  * In manual mode, you are responsible for showing, updating (via {@link #updateProgress}) and clearing the progress bar
19  * as needed from your own code. This method is most appropriate when you want to show progress throughout an operation
20  * that has predictable points of interest at which you can update the control.
21  *
22  * In automatic mode, you simply call {@link #wait} and let the progress bar run indefinitely, only clearing it once the
23  * operation is complete. You can optionally have the progress bar wait for a specific amount of time and then clear
24  * itself. Automatic mode is most appropriate for timed operations or asynchronous operations in which you have no need
25  * for indicating intermediate progress.
26  *
27  *     @example
28  *     var p = Ext.create('Ext.ProgressBar', {
29  *        renderTo: Ext.getBody(),
30  *        width: 300
31  *     });
32  *
33  *     // Wait for 5 seconds, then update the status el (progress bar will auto-reset)
34  *     p.wait({
35  *         interval: 500, //bar will move fast!
36  *         duration: 50000,
37  *         increment: 15,
38  *         text: 'Updating...',
39  *         scope: this,
40  *         fn: function(){
41  *             p.updateText('Done!');
42  *         }
43  *     });
44  */
45 Ext.define('Ext.ProgressBar', {
46     extend: 'Ext.Component',
47     alias: 'widget.progressbar',
48
49     requires: [
50         'Ext.Template',
51         'Ext.CompositeElement',
52         'Ext.TaskManager',
53         'Ext.layout.component.ProgressBar'
54     ],
55
56     uses: ['Ext.fx.Anim'],
57
58    /**
59     * @cfg {Number} [value=0]
60     * A floating point value between 0 and 1 (e.g., .5)
61     */
62
63    /**
64     * @cfg {String} [text='']
65     * The progress bar text (defaults to '')
66     */
67
68    /**
69     * @cfg {String/HTMLElement/Ext.Element} textEl
70     * The element to render the progress text to (defaults to the progress bar's internal text element)
71     */
72
73    /**
74     * @cfg {String} id
75     * The progress bar element's id (defaults to an auto-generated id)
76     */
77
78    /**
79     * @cfg {String} [baseCls='x-progress']
80     * The base CSS class to apply to the progress bar's wrapper element.
81     */
82     baseCls: Ext.baseCSSPrefix + 'progress',
83
84     config: {
85         /**
86         * @cfg {Boolean} animate
87         * True to animate the progress bar during transitions
88         */
89         animate: false,
90
91         /**
92          * @cfg {String} text
93          * The text shown in the progress bar
94          */
95         text: ''
96     },
97
98     // private
99     waitTimer: null,
100
101     renderTpl: [
102         '<div class="{baseCls}-text {baseCls}-text-back">',
103             '<div>&#160;</div>',
104         '</div>',
105         '<div id="{id}-bar" class="{baseCls}-bar">',
106             '<div class="{baseCls}-text">',
107                 '<div>&#160;</div>',
108             '</div>',
109         '</div>'
110     ],
111
112     componentLayout: 'progressbar',
113
114     // private
115     initComponent: function() {
116         this.callParent();
117
118         this.addChildEls('bar');
119
120         this.addEvents(
121             /**
122              * @event update
123              * Fires after each update interval
124              * @param {Ext.ProgressBar} this
125              * @param {Number} value The current progress value
126              * @param {String} text The current progress text
127              */
128             "update"
129         );
130     },
131
132     afterRender : function() {
133         var me = this;
134
135         // This produces a composite w/2 el's (which is why we cannot use childEls or
136         // renderSelectors):
137         me.textEl = me.textEl ? Ext.get(me.textEl) : me.el.select('.' + me.baseCls + '-text');
138
139         me.callParent(arguments);
140
141         if (me.value) {
142             me.updateProgress(me.value, me.text);
143         }
144         else {
145             me.updateText(me.text);
146         }
147     },
148
149     /**
150      * Updates the progress bar value, and optionally its text. If the text argument is not specified, any existing text
151      * value will be unchanged. To blank out existing text, pass ''. Note that even if the progress bar value exceeds 1,
152      * it will never automatically reset -- you are responsible for determining when the progress is complete and
153      * calling {@link #reset} to clear and/or hide the control.
154      * @param {Number} [value=0] A floating point value between 0 and 1 (e.g., .5)
155      * @param {String} [text=''] The string to display in the progress text element
156      * @param {Boolean} [animate=false] Whether to animate the transition of the progress bar. If this value is not
157      * specified, the default for the class is used
158      * @return {Ext.ProgressBar} this
159      */
160     updateProgress: function(value, text, animate) {
161         var me = this,
162             newWidth;
163             
164         me.value = value || 0;
165         if (text) {
166             me.updateText(text);
167         }
168         if (me.rendered && !me.isDestroyed) {
169             if (me.isVisible(true)) {
170                 newWidth = Math.floor(me.value * me.el.getWidth(true));
171                 if (Ext.isForcedBorderBox) {
172                     newWidth += me.bar.getBorderWidth("lr");
173                 }
174                 if (animate === true || (animate !== false && me.animate)) {
175                     me.bar.stopAnimation();
176                     me.bar.animate(Ext.apply({
177                         to: {
178                             width: newWidth + 'px'
179                         }
180                     }, me.animate));
181                 } else {
182                     me.bar.setWidth(newWidth);
183                 }
184             } else {
185                 // force a layout when we're visible again
186                 me.doComponentLayout();
187             }
188         }
189         me.fireEvent('update', me, me.value, text);
190         return me;
191     },
192
193     /**
194      * Updates the progress bar text. If specified, textEl will be updated, otherwise the progress bar itself will
195      * display the updated text.
196      * @param {String} [text=''] The string to display in the progress text element
197      * @return {Ext.ProgressBar} this
198      */
199     updateText: function(text) {
200         var me = this;
201         
202         me.text = text;
203         if (me.rendered) {
204             me.textEl.update(me.text);
205         }
206         return me;
207     },
208
209     applyText : function(text) {
210         this.updateText(text);
211     },
212
213     /**
214      * Initiates an auto-updating progress bar. A duration can be specified, in which case the progress bar will
215      * automatically reset after a fixed amount of time and optionally call a callback function if specified. If no
216      * duration is passed in, then the progress bar will run indefinitely and must be manually cleared by calling
217      * {@link #reset}.
218      *
219      * Example usage:
220      *
221      *     var p = new Ext.ProgressBar({
222      *        renderTo: 'my-el'
223      *     });
224      *
225      *     //Wait for 5 seconds, then update the status el (progress bar will auto-reset)
226      *     var p = Ext.create('Ext.ProgressBar', {
227      *        renderTo: Ext.getBody(),
228      *        width: 300
229      *     });
230      *
231      *     //Wait for 5 seconds, then update the status el (progress bar will auto-reset)
232      *     p.wait({
233      *        interval: 500, //bar will move fast!
234      *        duration: 50000,
235      *        increment: 15,
236      *        text: 'Updating...',
237      *        scope: this,
238      *        fn: function(){
239      *           p.updateText('Done!');
240      *        }
241      *     });
242      *
243      *     //Or update indefinitely until some async action completes, then reset manually
244      *     p.wait();
245      *     myAction.on('complete', function(){
246      *         p.reset();
247      *         p.updateText('Done!');
248      *     });
249      *
250      * @param {Object} config (optional) Configuration options
251      * @param {Number} config.duration The length of time in milliseconds that the progress bar should
252      * run before resetting itself (defaults to undefined, in which case it will run indefinitely
253      * until reset is called)
254      * @param {Number} config.interval The length of time in milliseconds between each progress update
255      * (defaults to 1000 ms)
256      * @param {Boolean} config.animate Whether to animate the transition of the progress bar. If this
257      * value is not specified, the default for the class is used.
258      * @param {Number} config.increment The number of progress update segments to display within the
259      * progress bar (defaults to 10).  If the bar reaches the end and is still updating, it will
260      * automatically wrap back to the beginning.
261      * @param {String} config.text Optional text to display in the progress bar element (defaults to '').
262      * @param {Function} config.fn A callback function to execute after the progress bar finishes auto-
263      * updating.  The function will be called with no arguments.  This function will be ignored if
264      * duration is not specified since in that case the progress bar can only be stopped programmatically,
265      * so any required function should be called by the same code after it resets the progress bar.
266      * @param {Object} config.scope The scope that is passed to the callback function (only applies when
267      * duration and fn are both passed).
268      * @return {Ext.ProgressBar} this
269      */
270     wait: function(o) {
271         var me = this;
272             
273         if (!me.waitTimer) {
274             scope = me;
275             o = o || {};
276             me.updateText(o.text);
277             me.waitTimer = Ext.TaskManager.start({
278                 run: function(i){
279                     var inc = o.increment || 10;
280                     i -= 1;
281                     me.updateProgress(((((i+inc)%inc)+1)*(100/inc))*0.01, null, o.animate);
282                 },
283                 interval: o.interval || 1000,
284                 duration: o.duration,
285                 onStop: function(){
286                     if (o.fn) {
287                         o.fn.apply(o.scope || me);
288                     }
289                     me.reset();
290                 },
291                 scope: scope
292             });
293         }
294         return me;
295     },
296
297     /**
298      * Returns true if the progress bar is currently in a {@link #wait} operation
299      * @return {Boolean} True if waiting, else false
300      */
301     isWaiting: function(){
302         return this.waitTimer !== null;
303     },
304
305     /**
306      * Resets the progress bar value to 0 and text to empty string. If hide = true, the progress bar will also be hidden
307      * (using the {@link #hideMode} property internally).
308      * @param {Boolean} [hide=false] True to hide the progress bar.
309      * @return {Ext.ProgressBar} this
310      */
311     reset: function(hide){
312         var me = this;
313         
314         me.updateProgress(0);
315         me.clearTimer();
316         if (hide === true) {
317             me.hide();
318         }
319         return me;
320     },
321
322     // private
323     clearTimer: function(){
324         var me = this;
325         
326         if (me.waitTimer) {
327             me.waitTimer.onStop = null; //prevent recursion
328             Ext.TaskManager.stop(me.waitTimer);
329             me.waitTimer = null;
330         }
331     },
332
333     onDestroy: function(){
334         var me = this;
335         
336         me.clearTimer();
337         if (me.rendered) {
338             if (me.textEl.isComposite) {
339                 me.textEl.clear();
340             }
341             Ext.destroyMembers(me, 'textEl', 'progressBar');
342         }
343         me.callParent();
344     }
345 });
346