Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / widgets / PagingToolbar.js
1 /*!
2  * Ext JS Library 3.0.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.PagingToolbar
9  * @extends Ext.Toolbar
10  * <p>As the amount of records increases, the time required for the browser to render
11  * them increases. Paging is used to reduce the amount of data exchanged with the client.
12  * Note: if there are more records/rows than can be viewed in the available screen area, vertical
13  * scrollbars will be added.</p>
14  * <p>Paging is typically handled on the server side (see exception below). The client sends
15  * parameters to the server side, which the server needs to interpret and then respond with the
16  * approprate data.</p>
17  * <p><b>Ext.PagingToolbar</b> is a specialized toolbar that is bound to a {@link Ext.data.Store}
18  * and provides automatic paging control. This Component {@link Ext.data.Store#load load}s blocks
19  * of data into the <tt>{@link #store}</tt> by passing {@link Ext.data.Store#paramNames paramNames} used for
20  * paging criteria.</p>
21  * <p>PagingToolbar is typically used as one of the Grid's toolbars:</p>
22  * <pre><code>
23 Ext.QuickTips.init(); // to display button quicktips
24
25 var myStore = new Ext.data.Store({
26     ...
27 });
28
29 var myPageSize = 25;  // server script should only send back 25 items
30
31 var grid = new Ext.grid.GridPanel({
32     ...
33     store: myStore,
34     bbar: new Ext.PagingToolbar({
35         {@link #store}: myStore,       // grid and PagingToolbar using same store
36         {@link #displayInfo}: true,
37         {@link #pageSize}: myPageSize,
38         {@link #prependButtons}: true,
39         items: [
40             'text 1'
41         ]
42     })
43 });
44  * </code></pre>
45  *
46  * <p>To use paging, pass the paging requirements to the server when the store is first loaded.</p>
47  * <pre><code>
48 store.load({
49     params: {
50         start: 0,          // specify params for the first page load if using paging
51         limit: myPageSize,
52         foo:   'bar'
53     }
54 });
55  * </code></pre>
56  * <p><u>Paging with Local Data</u></p>
57  * <p>Paging can also be accomplished with local data using extensions:</p>
58  * <div class="mdetail-params"><ul>
59  * <li><a href="http://extjs.com/forum/showthread.php?t=57386">Ext.ux.data.PagingStore</a></li>
60  * <li>Paging Memory Proxy (examples/ux/PagingMemoryProxy.js)</li>
61  * </ul></div>
62  * @constructor
63  * Create a new PagingToolbar
64  * @param {Object} config The config object
65  * @xtype paging
66  */
67 (function() {
68
69 var T = Ext.Toolbar;
70
71 Ext.PagingToolbar = Ext.extend(Ext.Toolbar, {
72     /**
73      * @cfg {Ext.data.Store} store
74      * The {@link Ext.data.Store} the paging toolbar should use as its data source (required).
75      */
76     /**
77      * @cfg {Boolean} displayInfo
78      * <tt>true</tt> to display the displayMsg (defaults to <tt>false</tt>)
79      */
80     /**
81      * @cfg {Number} pageSize
82      * The number of records to display per page (defaults to <tt>20</tt>)
83      */
84     pageSize : 20,
85     /**
86      * @cfg {Boolean} prependButtons
87      * <tt>true</tt> to insert any configured <tt>items</tt> <i>before</i> the paging buttons.
88      * Defaults to <tt>false</tt>.
89      */
90     /**
91      * @cfg {String} displayMsg
92      * The paging status message to display (defaults to <tt>'Displaying {0} - {1} of {2}'</tt>).
93      * Note that this string is formatted using the braced numbers <tt>{0}-{2}</tt> as tokens
94      * that are replaced by the values for start, end and total respectively. These tokens should
95      * be preserved when overriding this string if showing those values is desired.
96      */
97     displayMsg : 'Displaying {0} - {1} of {2}',
98     /**
99      * @cfg {String} emptyMsg
100      * The message to display when no records are found (defaults to 'No data to display')
101      */
102     emptyMsg : 'No data to display',
103     /**
104      * @cfg {String} beforePageText
105      * The text displayed before the input item (defaults to <tt>'Page'</tt>).
106      */
107     beforePageText : 'Page',
108     /**
109      * @cfg {String} afterPageText
110      * Customizable piece of the default paging text (defaults to <tt>'of {0}'</tt>). Note that
111      * this string is formatted using <tt>{0}</tt> as a token that is replaced by the number of
112      * total pages. This token should be preserved when overriding this string if showing the
113      * total page count is desired.
114      */
115     afterPageText : 'of {0}',
116     /**
117      * @cfg {String} firstText
118      * The quicktip text displayed for the first page button (defaults to <tt>'First Page'</tt>).
119      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
120      */
121     firstText : 'First Page',
122     /**
123      * @cfg {String} prevText
124      * The quicktip text displayed for the previous page button (defaults to <tt>'Previous Page'</tt>).
125      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
126      */
127     prevText : 'Previous Page',
128     /**
129      * @cfg {String} nextText
130      * The quicktip text displayed for the next page button (defaults to <tt>'Next Page'</tt>).
131      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
132      */
133     nextText : 'Next Page',
134     /**
135      * @cfg {String} lastText
136      * The quicktip text displayed for the last page button (defaults to <tt>'Last Page'</tt>).
137      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
138      */
139     lastText : 'Last Page',
140     /**
141      * @cfg {String} refreshText
142      * The quicktip text displayed for the Refresh button (defaults to <tt>'Refresh'</tt>).
143      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
144      */
145     refreshText : 'Refresh',
146
147     /**
148      * @deprecated
149      * <b>The defaults for these should be set in the data store.</b>
150      * Object mapping of parameter names used for load calls, initially set to:
151      * <pre>{start: 'start', limit: 'limit'}</pre>
152      */
153
154     /**
155      * The number of records to display per page.  See also <tt>{@link #cursor}</tt>.
156      * @type Number
157      * @property pageSize
158      */
159
160     /**
161      * Indicator for the record position.  This property might be used to get the active page
162      * number for example:<pre><code>
163      * // t is reference to the paging toolbar instance
164      * var activePage = Math.ceil((t.cursor + t.pageSize) / t.pageSize);
165      * </code></pre>
166      * @type Number
167      * @property cursor
168      */
169
170     initComponent : function(){
171         var pagingItems = [this.first = new T.Button({
172             tooltip: this.firstText,
173             overflowText: this.firstText,
174             iconCls: 'x-tbar-page-first',
175             disabled: true,
176             handler: this.moveFirst,
177             scope: this
178         }), this.prev = new T.Button({
179             tooltip: this.prevText,
180             overflowText: this.prevText,
181             iconCls: 'x-tbar-page-prev',
182             disabled: true,
183             handler: this.movePrevious,
184             scope: this
185         }), '-', this.beforePageText,
186         this.inputItem = new Ext.form.NumberField({
187             cls: 'x-tbar-page-number',
188             allowDecimals: false,
189             allowNegative: false,
190             enableKeyEvents: true,
191             selectOnFocus: true,
192             listeners: {
193                 scope: this,
194                 keydown: this.onPagingKeyDown,
195                 blur: this.onPagingBlur
196             }
197         }), this.afterTextItem = new T.TextItem({
198             text: String.format(this.afterPageText, 1)
199         }), '-', this.next = new T.Button({
200             tooltip: this.nextText,
201             overflowText: this.nextText,
202             iconCls: 'x-tbar-page-next',
203             disabled: true,
204             handler: this.moveNext,
205             scope: this
206         }), this.last = new T.Button({
207             tooltip: this.lastText,
208             overflowText: this.lastText,
209             iconCls: 'x-tbar-page-last',
210             disabled: true,
211             handler: this.moveLast,
212             scope: this
213         }), '-', this.refresh = new T.Button({
214             tooltip: this.refreshText,
215             overflowText: this.refreshText,
216             iconCls: 'x-tbar-loading',
217             handler: this.refresh,
218             scope: this
219         })];
220
221
222         var userItems = this.items || this.buttons || [];
223         if (this.prependButtons) {
224             this.items = userItems.concat(pagingItems);
225         }else{
226             this.items = pagingItems.concat(userItems);
227         }
228         delete this.buttons;
229         if(this.displayInfo){
230             this.items.push('->');
231             this.items.push(this.displayItem = new T.TextItem({}));
232         }
233         Ext.PagingToolbar.superclass.initComponent.call(this);
234         this.addEvents(
235             /**
236              * @event change
237              * Fires after the active page has been changed.
238              * @param {Ext.PagingToolbar} this
239              * @param {Object} pageData An object that has these properties:<ul>
240              * <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
241              * returned by the server</div></li>
242              * <li><code>activePage</code> : Number <div class="sub-desc">The current page number</div></li>
243              * <li><code>pages</code> : Number <div class="sub-desc">The total number of pages (calculated from
244              * the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
245              * </ul>
246              */
247             'change',
248             /**
249              * @event beforechange
250              * Fires just before the active page is changed.
251              * Return false to prevent the active page from being changed.
252              * @param {Ext.PagingToolbar} this
253              * @param {Object} params An object hash of the parameters which the PagingToolbar will send when
254              * loading the required page. This will contain:<ul>
255              * <li><code>start</code> : Number <div class="sub-desc">The starting row number for the next page of records to
256              * be retrieved from the server</div></li>
257              * <li><code>limit</code> : Number <div class="sub-desc">The number of records to be retrieved from the server</div></li>
258              * </ul>
259              * <p>(note: the names of the <b>start</b> and <b>limit</b> properties are determined
260              * by the store's {@link Ext.data.Store#paramNames paramNames} property.)</p>
261              * <p>Parameters may be added as required in the event handler.</p>
262              */
263             'beforechange'
264         );
265         this.on('afterlayout', this.onFirstLayout, this, {single: true});
266         this.cursor = 0;
267         this.bindStore(this.store);
268     },
269
270     // private
271     onFirstLayout : function(){
272         if(this.dsLoaded){
273             this.onLoad.apply(this, this.dsLoaded);
274         }
275     },
276
277     // private
278     updateInfo : function(){
279         if(this.displayItem){
280             var count = this.store.getCount();
281             var msg = count == 0 ?
282                 this.emptyMsg :
283                 String.format(
284                     this.displayMsg,
285                     this.cursor+1, this.cursor+count, this.store.getTotalCount()
286                 );
287             this.displayItem.setText(msg);
288         }
289     },
290
291     // private
292     onLoad : function(store, r, o){
293         if(!this.rendered){
294             this.dsLoaded = [store, r, o];
295             return;
296         }
297         var p = this.getParams();
298         this.cursor = (o.params && o.params[p.start]) ? o.params[p.start] : 0;
299         var d = this.getPageData(), ap = d.activePage, ps = d.pages;
300
301         this.afterTextItem.setText(String.format(this.afterPageText, d.pages));
302         this.inputItem.setValue(ap);
303         this.first.setDisabled(ap == 1);
304         this.prev.setDisabled(ap == 1);
305         this.next.setDisabled(ap == ps);
306         this.last.setDisabled(ap == ps);
307         this.refresh.enable();
308         this.updateInfo();
309         this.fireEvent('change', this, d);
310     },
311
312     // private
313     getPageData : function(){
314         var total = this.store.getTotalCount();
315         return {
316             total : total,
317             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
318             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
319         };
320     },
321
322     /**
323      * Change the active page
324      * @param {Integer} page The page to display
325      */
326     changePage : function(page){
327         this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));
328     },
329
330     // private
331     onLoadError : function(){
332         if(!this.rendered){
333             return;
334         }
335         this.refresh.enable();
336     },
337
338     // private
339     readPage : function(d){
340         var v = this.inputItem.getValue(), pageNum;
341         if (!v || isNaN(pageNum = parseInt(v, 10))) {
342             this.inputItem.setValue(d.activePage);
343             return false;
344         }
345         return pageNum;
346     },
347
348     onPagingFocus : function(){
349         this.inputItem.select();
350     },
351
352     //private
353     onPagingBlur : function(e){
354         this.inputItem.setValue(this.getPageData().activePage);
355     },
356
357     // private
358     onPagingKeyDown : function(field, e){
359         var k = e.getKey(), d = this.getPageData(), pageNum;
360         if (k == e.RETURN) {
361             e.stopEvent();
362             pageNum = this.readPage(d);
363             if(pageNum !== false){
364                 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
365                 this.doLoad(pageNum * this.pageSize);
366             }
367         }else if (k == e.HOME || k == e.END){
368             e.stopEvent();
369             pageNum = k == e.HOME ? 1 : d.pages;
370             field.setValue(pageNum);
371         }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){
372             e.stopEvent();
373             if((pageNum = this.readPage(d))){
374                 var increment = e.shiftKey ? 10 : 1;
375                 if(k == e.DOWN || k == e.PAGEDOWN){
376                     increment *= -1;
377                 }
378                 pageNum += increment;
379                 if(pageNum >= 1 & pageNum <= d.pages){
380                     field.setValue(pageNum);
381                 }
382             }
383         }
384     },
385
386     // private
387     getParams : function(){
388         //retain backwards compat, allow params on the toolbar itself, if they exist.
389         return this.paramNames || this.store.paramNames;
390     },
391
392     // private
393     beforeLoad : function(){
394         if(this.rendered && this.refresh){
395             this.refresh.disable();
396         }
397     },
398
399     // private
400     doLoad : function(start){
401         var o = {}, pn = this.getParams();
402         o[pn.start] = start;
403         o[pn.limit] = this.pageSize;
404         if(this.fireEvent('beforechange', this, o) !== false){
405             this.store.load({params:o});
406         }
407     },
408
409     /**
410      * Move to the first page, has the same effect as clicking the 'first' button.
411      */
412     moveFirst : function(){
413         this.doLoad(0);
414     },
415
416     /**
417      * Move to the previous page, has the same effect as clicking the 'previous' button.
418      */
419     movePrevious : function(){
420         this.doLoad(Math.max(0, this.cursor-this.pageSize));
421     },
422
423     /**
424      * Move to the next page, has the same effect as clicking the 'next' button.
425      */
426     moveNext : function(){
427         this.doLoad(this.cursor+this.pageSize);
428     },
429
430     /**
431      * Move to the last page, has the same effect as clicking the 'last' button.
432      */
433     moveLast : function(){
434         var total = this.store.getTotalCount(),
435             extra = total % this.pageSize;
436
437         this.doLoad(extra ? (total - extra) : total - this.pageSize);
438     },
439
440     /**
441      * Refresh the current page, has the same effect as clicking the 'refresh' button.
442      */
443     refresh : function(){
444         this.doLoad(this.cursor);
445     },
446
447     /**
448      * Binds the paging toolbar to the specified {@link Ext.data.Store}
449      * @param {Store} store The store to bind to this toolbar
450      * @param {Boolean} initial (Optional) true to not remove listeners
451      */
452     bindStore : function(store, initial){
453         var doLoad;
454         if(!initial && this.store){
455             this.store.un('beforeload', this.beforeLoad, this);
456             this.store.un('load', this.onLoad, this);
457             this.store.un('exception', this.onLoadError, this);
458             if(store !== this.store && this.store.autoDestroy){
459                 this.store.destroy();
460             }
461         }
462         if(store){
463             store = Ext.StoreMgr.lookup(store);
464             store.on({
465                 scope: this,
466                 beforeload: this.beforeLoad,
467                 load: this.onLoad,
468                 exception: this.onLoadError
469             });
470             doLoad = store.getCount() > 0;
471         }
472         this.store = store;
473         if(doLoad){
474             this.onLoad(store, null, {});
475         }
476     },
477
478     /**
479      * Unbinds the paging toolbar from the specified {@link Ext.data.Store} <b>(deprecated)</b>
480      * @param {Ext.data.Store} store The data store to unbind
481      */
482     unbind : function(store){
483         this.bindStore(null);
484     },
485
486     /**
487      * Binds the paging toolbar to the specified {@link Ext.data.Store} <b>(deprecated)</b>
488      * @param {Ext.data.Store} store The data store to bind
489      */
490     bind : function(store){
491         this.bindStore(store);
492     },
493
494     // private
495     onDestroy : function(){
496         this.bindStore(null);
497         Ext.PagingToolbar.superclass.onDestroy.call(this);
498     }
499 });
500
501 })();
502 Ext.reg('paging', Ext.PagingToolbar);