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