Roo/bootstrap/PagingToolbar.js
[roojs1] / Roo / bootstrap / PagingToolbar.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.bootstrap.PagingToolbar
14  * @extends Roo.Row
15  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
16  * @constructor
17  * Create a new PagingToolbar
18  * @param {Object} config The config object
19  */
20 Roo.bootstrap.PagingToolbar = function(config)
21 {
22     // old args format still supported... - xtype is prefered..
23         // created from xtype...
24     if (this.store) {
25         this.store= Roo.factory(this.store, Roo.data);
26         this.ds = this.store;
27         this.ds.xmodule = this.xmodule || false;
28     }
29     
30     var ds = config.dataSource;
31     Roo.log(config);
32     this.toolbarItems = [];
33     if (config.items) {
34         this.toolbarItems = config.items;
35 //        config.items = [];
36     }
37     
38     Roo.bootstrap.PagingToolbar.superclass.constructor.call(this, config);
39     this.ds = ds;
40     this.cursor = 0;
41     if (ds) { 
42         this.bind(ds);
43     }
44     
45     this.navgroup = new Roo.bootstrap.NavGroup({ cls: 'pagination' });
46     
47 };
48
49 Roo.extend(Roo.bootstrap.PagingToolbar, Roo.bootstrap.NavSimplebar, {
50     /**
51      * @cfg {Roo.data.Store} dataSource
52      * The underlying data store providing the paged data
53      */
54     /**
55      * @cfg {String/HTMLElement/Element} container
56      * container The id or element that will contain the toolbar
57      */
58     /**
59      * @cfg {Boolean} displayInfo
60      * True to display the displayMsg (defaults to false)
61      */
62     /**
63      * @cfg {Number} pageSize
64      * The number of records to display per page (defaults to 20)
65      */
66     pageSize: 20,
67     /**
68      * @cfg {String} displayMsg
69      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
70      */
71     displayMsg : 'Displaying {0} - {1} of {2}',
72     /**
73      * @cfg {String} emptyMsg
74      * The message to display when no records are found (defaults to "No data to display")
75      */
76     emptyMsg : 'No data to display',
77     /**
78      * Customizable piece of the default paging text (defaults to "Page")
79      * @type String
80      */
81     beforePageText : "Page",
82     /**
83      * Customizable piece of the default paging text (defaults to "of %0")
84      * @type String
85      */
86     afterPageText : "of {0}",
87     /**
88      * Customizable piece of the default paging text (defaults to "First Page")
89      * @type String
90      */
91     firstText : "First Page",
92     /**
93      * Customizable piece of the default paging text (defaults to "Previous Page")
94      * @type String
95      */
96     prevText : "Previous Page",
97     /**
98      * Customizable piece of the default paging text (defaults to "Next Page")
99      * @type String
100      */
101     nextText : "Next Page",
102     /**
103      * Customizable piece of the default paging text (defaults to "Last Page")
104      * @type String
105      */
106     lastText : "Last Page",
107     /**
108      * Customizable piece of the default paging text (defaults to "Refresh")
109      * @type String
110      */
111     refreshText : "Refresh",
112
113     buttons : false,
114     // private
115     onRender : function(ct, position) 
116     {
117         Roo.bootstrap.PagingToolbar.superclass.onRender.call(this, ct, position);
118         this.navgroup.parentId = this.id;
119         this.navgroup.onRender(this.el, null);
120         // add the buttons to the navgroup
121         
122         if(this.displayInfo){
123             Roo.log(this.el.select('ul.navbar-nav',true).first());
124             this.el.select('ul.navbar-nav',true).first().createChild({cls:'x-paging-info'});
125             this.displayEl = this.el.select('.x-paging-info', true).first();
126 //            var navel = this.navgroup.addItem( { tagtype : 'span', html : '', cls : 'x-paging-info', preventDefault : true } );
127 //            this.displayEl = navel.el.select('span',true).first();
128         }
129         
130         var _this = this;
131         
132         if(this.buttons){
133             Roo.each(_this.buttons, function(e){
134                Roo.factory(e).onRender(_this.el, null);
135             });
136         }
137             
138         Roo.each(_this.toolbarItems, function(e) {
139             _this.navgroup.addItem(e);
140         });
141         
142         
143         this.first = this.navgroup.addItem({
144             tooltip: this.firstText,
145             cls: "prev",
146             icon : 'fa fa-backward',
147             disabled: true,
148             preventDefault: true,
149             listeners : { click : this.onClick.createDelegate(this, ["first"]) }
150         });
151         
152         this.prev =  this.navgroup.addItem({
153             tooltip: this.prevText,
154             cls: "prev",
155             icon : 'fa fa-step-backward',
156             disabled: true,
157             preventDefault: true,
158             listeners : { click :  this.onClick.createDelegate(this, ["prev"]) }
159         });
160     //this.addSeparator();
161         
162         
163         var field = this.navgroup.addItem( {
164             tagtype : 'span',
165             cls : 'x-paging-position',
166             
167             html : this.beforePageText  +
168                 '<input type="text" size="3" value="1" class="x-grid-page-number">' +
169                 '<span class="x-paging-after">' +  String.format(this.afterPageText, 1) + '</span>'
170          } ); //?? escaped?
171         
172         this.field = field.el.select('input', true).first();
173         this.field.on("keydown", this.onPagingKeydown, this);
174         this.field.on("focus", function(){this.dom.select();});
175     
176     
177         this.afterTextEl =  field.el.select('.x-paging-after',true).first();
178         //this.field.setHeight(18);
179         //this.addSeparator();
180         this.next = this.navgroup.addItem({
181             tooltip: this.nextText,
182             cls: "next",
183             html : ' <i class="fa fa-step-forward">',
184             disabled: true,
185             preventDefault: true,
186             listeners : { click :  this.onClick.createDelegate(this, ["next"]) }
187         });
188         this.last = this.navgroup.addItem({
189             tooltip: this.lastText,
190             icon : 'fa fa-forward',
191             cls: "next",
192             disabled: true,
193             preventDefault: true,
194             listeners : { click :  this.onClick.createDelegate(this, ["last"]) }
195         });
196     //this.addSeparator();
197         this.loading = this.navgroup.addItem({
198             tooltip: this.refreshText,
199             icon: 'fa fa-refresh',
200             preventDefault: true,
201             listeners : { click : this.onClick.createDelegate(this, ["refresh"]) }
202         });
203
204     },
205
206     // private
207     updateInfo : function(){
208         if(this.displayEl){
209             var count = (typeof(this.getCount) == 'undefined') ? this.ds.getCount() : this.getCount();
210             var msg = count == 0 ?
211                 this.emptyMsg :
212                 String.format(
213                     this.displayMsg,
214                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
215                 );
216             this.displayEl.update(msg);
217         }
218     },
219
220     // private
221     onLoad : function(ds, r, o){
222        this.cursor = o.params ? o.params.start : 0;
223        var d = this.getPageData(),
224             ap = d.activePage,
225             ps = d.pages;
226         
227        this.afterTextEl.dom.innerHTML = String.format(this.afterPageText, d.pages);
228        this.field.dom.value = ap;
229        this.first.setDisabled(ap == 1);
230        this.prev.setDisabled(ap == 1);
231        this.next.setDisabled(ap == ps);
232        this.last.setDisabled(ap == ps);
233        this.loading.enable();
234        this.updateInfo();
235     },
236
237     // private
238     getPageData : function(){
239         var total = this.ds.getTotalCount();
240         return {
241             total : total,
242             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
243             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
244         };
245     },
246
247     // private
248     onLoadError : function(){
249         this.loading.enable();
250     },
251
252     // private
253     onPagingKeydown : function(e){
254         var k = e.getKey();
255         var d = this.getPageData();
256         if(k == e.RETURN){
257             var v = this.field.dom.value, pageNum;
258             if(!v || isNaN(pageNum = parseInt(v, 10))){
259                 this.field.dom.value = d.activePage;
260                 return;
261             }
262             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
263             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
264             e.stopEvent();
265         }
266         else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
267         {
268           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
269           this.field.dom.value = pageNum;
270           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
271           e.stopEvent();
272         }
273         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
274         {
275           var v = this.field.dom.value, pageNum; 
276           var increment = (e.shiftKey) ? 10 : 1;
277           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
278             increment *= -1;
279           if(!v || isNaN(pageNum = parseInt(v, 10))) {
280             this.field.dom.value = d.activePage;
281             return;
282           }
283           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
284           {
285             this.field.dom.value = parseInt(v, 10) + increment;
286             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
287             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
288           }
289           e.stopEvent();
290         }
291     },
292
293     // private
294     beforeLoad : function(){
295         if(this.loading){
296             this.loading.disable();
297         }
298     },
299
300     // private
301     onClick : function(which){
302         
303         var ds = this.ds;
304         if (!ds) {
305             return;
306         }
307         
308         switch(which){
309             case "first":
310                 ds.load({params:{start: 0, limit: this.pageSize}});
311             break;
312             case "prev":
313                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
314             break;
315             case "next":
316                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
317             break;
318             case "last":
319                 var total = ds.getTotalCount();
320                 var extra = total % this.pageSize;
321                 var lastStart = extra ? (total - extra) : total-this.pageSize;
322                 ds.load({params:{start: lastStart, limit: this.pageSize}});
323             break;
324             case "refresh":
325                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
326             break;
327         }
328     },
329
330     /**
331      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
332      * @param {Roo.data.Store} store The data store to unbind
333      */
334     unbind : function(ds){
335         ds.un("beforeload", this.beforeLoad, this);
336         ds.un("load", this.onLoad, this);
337         ds.un("loadexception", this.onLoadError, this);
338         ds.un("remove", this.updateInfo, this);
339         ds.un("add", this.updateInfo, this);
340         this.ds = undefined;
341     },
342
343     /**
344      * Binds the paging toolbar to the specified {@link Roo.data.Store}
345      * @param {Roo.data.Store} store The data store to bind
346      */
347     bind : function(ds){
348         ds.on("beforeload", this.beforeLoad, this);
349         ds.on("load", this.onLoad, this);
350         ds.on("loadexception", this.onLoadError, this);
351         ds.on("remove", this.updateInfo, this);
352         ds.on("add", this.updateInfo, this);
353         this.ds = ds;
354     }
355 });