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