Upgrade to ExtJS 3.2.2 - Released 06/02/2010
[extjs.git] / pkgs / pkg-toolbars-debug.js
1 /*!
2  * Ext JS Library 3.2.2
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.Toolbar
9  * @extends Ext.Container
10  * <p>Basic Toolbar class. Although the <tt>{@link Ext.Container#defaultType defaultType}</tt> for Toolbar
11  * is <tt>{@link Ext.Button button}</tt>, Toolbar elements (child items for the Toolbar container) may
12  * be virtually any type of Component. Toolbar elements can be created explicitly via their constructors,
13  * or implicitly via their xtypes, and can be <tt>{@link #add}</tt>ed dynamically.</p>
14  * <p>Some items have shortcut strings for creation:</p>
15  * <pre>
16 <u>Shortcut</u>  <u>xtype</u>          <u>Class</u>                  <u>Description</u>
17 '->'      'tbfill'       {@link Ext.Toolbar.Fill}       begin using the right-justified button container
18 '-'       'tbseparator'  {@link Ext.Toolbar.Separator}  add a vertical separator bar between toolbar items
19 ' '       'tbspacer'     {@link Ext.Toolbar.Spacer}     add horiztonal space between elements
20  * </pre>
21  *
22  * Example usage of various elements:
23  * <pre><code>
24 var tb = new Ext.Toolbar({
25     renderTo: document.body,
26     width: 600,
27     height: 100,
28     items: [
29         {
30             // xtype: 'button', // default for Toolbars, same as 'tbbutton'
31             text: 'Button'
32         },
33         {
34             xtype: 'splitbutton', // same as 'tbsplitbutton'
35             text: 'Split Button'
36         },
37         // begin using the right-justified button container
38         '->', // same as {xtype: 'tbfill'}, // Ext.Toolbar.Fill
39         {
40             xtype: 'textfield',
41             name: 'field1',
42             emptyText: 'enter search term'
43         },
44         // add a vertical separator bar between toolbar items
45         '-', // same as {xtype: 'tbseparator'} to create Ext.Toolbar.Separator
46         'text 1', // same as {xtype: 'tbtext', text: 'text1'} to create Ext.Toolbar.TextItem
47         {xtype: 'tbspacer'},// same as ' ' to create Ext.Toolbar.Spacer
48         'text 2',
49         {xtype: 'tbspacer', width: 50}, // add a 50px space
50         'text 3'
51     ]
52 });
53  * </code></pre>
54  * Example adding a ComboBox within a menu of a button:
55  * <pre><code>
56 // ComboBox creation
57 var combo = new Ext.form.ComboBox({
58     store: new Ext.data.ArrayStore({
59         autoDestroy: true,
60         fields: ['initials', 'fullname'],
61         data : [
62             ['FF', 'Fred Flintstone'],
63             ['BR', 'Barney Rubble']
64         ]
65     }),
66     displayField: 'fullname',
67     typeAhead: true,
68     mode: 'local',
69     forceSelection: true,
70     triggerAction: 'all',
71     emptyText: 'Select a name...',
72     selectOnFocus: true,
73     width: 135,
74     getListParent: function() {
75         return this.el.up('.x-menu');
76     },
77     iconCls: 'no-icon' //use iconCls if placing within menu to shift to right side of menu
78 });
79
80 // put ComboBox in a Menu
81 var menu = new Ext.menu.Menu({
82     id: 'mainMenu',
83     items: [
84         combo // A Field in a Menu
85     ]
86 });
87
88 // add a Button with the menu
89 tb.add({
90         text:'Button w/ Menu',
91         menu: menu  // assign menu by instance
92     });
93 tb.doLayout();
94  * </code></pre>
95  * @constructor
96  * Creates a new Toolbar
97  * @param {Object/Array} config A config object or an array of buttons to <tt>{@link #add}</tt>
98  * @xtype toolbar
99  */
100 Ext.Toolbar = function(config){
101     if(Ext.isArray(config)){
102         config = {items: config, layout: 'toolbar'};
103     } else {
104         config = Ext.apply({
105             layout: 'toolbar'
106         }, config);
107         if(config.buttons) {
108             config.items = config.buttons;
109         }
110     }
111     Ext.Toolbar.superclass.constructor.call(this, config);
112 };
113
114 (function(){
115
116 var T = Ext.Toolbar;
117
118 Ext.extend(T, Ext.Container, {
119
120     defaultType: 'button',
121
122     /**
123      * @cfg {String/Object} layout
124      * This class assigns a default layout (<code>layout:'<b>toolbar</b>'</code>).
125      * Developers <i>may</i> override this configuration option if another layout
126      * is required (the constructor must be passed a configuration object in this
127      * case instead of an array).
128      * See {@link Ext.Container#layout} for additional information.
129      */
130
131     enableOverflow : false,
132
133     /**
134      * @cfg {Boolean} enableOverflow
135      * Defaults to false. Configure <code>true<code> to make the toolbar provide a button
136      * which activates a dropdown Menu to show items which overflow the Toolbar's width.
137      */
138     /**
139      * @cfg {String} buttonAlign
140      * <p>The default position at which to align child items. Defaults to <code>"left"</code></p>
141      * <p>May be specified as <code>"center"</code> to cause items added before a Fill (A <code>"->"</code>) item
142      * to be centered in the Toolbar. Items added after a Fill are still right-aligned.</p>
143      * <p>Specify as <code>"right"</code> to right align all child items.</p>
144      */
145
146     trackMenus : true,
147     internalDefaults: {removeMode: 'container', hideParent: true},
148     toolbarCls: 'x-toolbar',
149
150     initComponent : function(){
151         T.superclass.initComponent.call(this);
152
153         /**
154          * @event overflowchange
155          * Fires after the overflow state has changed.
156          * @param {Object} c The Container
157          * @param {Boolean} lastOverflow overflow state
158          */
159         this.addEvents('overflowchange');
160     },
161
162     // private
163     onRender : function(ct, position){
164         if(!this.el){
165             if(!this.autoCreate){
166                 this.autoCreate = {
167                     cls: this.toolbarCls + ' x-small-editor'
168                 };
169             }
170             this.el = ct.createChild(Ext.apply({ id: this.id },this.autoCreate), position);
171             Ext.Toolbar.superclass.onRender.apply(this, arguments);
172         }
173     },
174
175     /**
176      * <p>Adds element(s) to the toolbar -- this function takes a variable number of
177      * arguments of mixed type and adds them to the toolbar.</p>
178      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
179      * @param {Mixed} arg1 The following types of arguments are all valid:<br />
180      * <ul>
181      * <li>{@link Ext.Button} config: A valid button config object (equivalent to {@link #addButton})</li>
182      * <li>HtmlElement: Any standard HTML element (equivalent to {@link #addElement})</li>
183      * <li>Field: Any form field (equivalent to {@link #addField})</li>
184      * <li>Item: Any subclass of {@link Ext.Toolbar.Item} (equivalent to {@link #addItem})</li>
185      * <li>String: Any generic string (gets wrapped in a {@link Ext.Toolbar.TextItem}, equivalent to {@link #addText}).
186      * Note that there are a few special strings that are treated differently as explained next.</li>
187      * <li>'-': Creates a separator element (equivalent to {@link #addSeparator})</li>
188      * <li>' ': Creates a spacer element (equivalent to {@link #addSpacer})</li>
189      * <li>'->': Creates a fill element (equivalent to {@link #addFill})</li>
190      * </ul>
191      * @param {Mixed} arg2
192      * @param {Mixed} etc.
193      * @method add
194      */
195
196     // private
197     lookupComponent : function(c){
198         if(Ext.isString(c)){
199             if(c == '-'){
200                 c = new T.Separator();
201             }else if(c == ' '){
202                 c = new T.Spacer();
203             }else if(c == '->'){
204                 c = new T.Fill();
205             }else{
206                 c = new T.TextItem(c);
207             }
208             this.applyDefaults(c);
209         }else{
210             if(c.isFormField || c.render){ // some kind of form field, some kind of Toolbar.Item
211                 c = this.createComponent(c);
212             }else if(c.tag){ // DomHelper spec
213                 c = new T.Item({autoEl: c});
214             }else if(c.tagName){ // element
215                 c = new T.Item({el:c});
216             }else if(Ext.isObject(c)){ // must be button config?
217                 c = c.xtype ? this.createComponent(c) : this.constructButton(c);
218             }
219         }
220         return c;
221     },
222
223     // private
224     applyDefaults : function(c){
225         if(!Ext.isString(c)){
226             c = Ext.Toolbar.superclass.applyDefaults.call(this, c);
227             var d = this.internalDefaults;
228             if(c.events){
229                 Ext.applyIf(c.initialConfig, d);
230                 Ext.apply(c, d);
231             }else{
232                 Ext.applyIf(c, d);
233             }
234         }
235         return c;
236     },
237
238     /**
239      * Adds a separator
240      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
241      * @return {Ext.Toolbar.Item} The separator {@link Ext.Toolbar.Item item}
242      */
243     addSeparator : function(){
244         return this.add(new T.Separator());
245     },
246
247     /**
248      * Adds a spacer element
249      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
250      * @return {Ext.Toolbar.Spacer} The spacer item
251      */
252     addSpacer : function(){
253         return this.add(new T.Spacer());
254     },
255
256     /**
257      * Forces subsequent additions into the float:right toolbar
258      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
259      */
260     addFill : function(){
261         this.add(new T.Fill());
262     },
263
264     /**
265      * Adds any standard HTML element to the toolbar
266      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
267      * @param {Mixed} el The element or id of the element to add
268      * @return {Ext.Toolbar.Item} The element's item
269      */
270     addElement : function(el){
271         return this.addItem(new T.Item({el:el}));
272     },
273
274     /**
275      * Adds any Toolbar.Item or subclass
276      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
277      * @param {Ext.Toolbar.Item} item
278      * @return {Ext.Toolbar.Item} The item
279      */
280     addItem : function(item){
281         return this.add.apply(this, arguments);
282     },
283
284     /**
285      * Adds a button (or buttons). See {@link Ext.Button} for more info on the config.
286      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
287      * @param {Object/Array} config A button config or array of configs
288      * @return {Ext.Button/Array}
289      */
290     addButton : function(config){
291         if(Ext.isArray(config)){
292             var buttons = [];
293             for(var i = 0, len = config.length; i < len; i++) {
294                 buttons.push(this.addButton(config[i]));
295             }
296             return buttons;
297         }
298         return this.add(this.constructButton(config));
299     },
300
301     /**
302      * Adds text to the toolbar
303      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
304      * @param {String} text The text to add
305      * @return {Ext.Toolbar.Item} The element's item
306      */
307     addText : function(text){
308         return this.addItem(new T.TextItem(text));
309     },
310
311     /**
312      * Adds a new element to the toolbar from the passed {@link Ext.DomHelper} config
313      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
314      * @param {Object} config
315      * @return {Ext.Toolbar.Item} The element's item
316      */
317     addDom : function(config){
318         return this.add(new T.Item({autoEl: config}));
319     },
320
321     /**
322      * Adds a dynamically rendered Ext.form field (TextField, ComboBox, etc). Note: the field should not have
323      * been rendered yet. For a field that has already been rendered, use {@link #addElement}.
324      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
325      * @param {Ext.form.Field} field
326      * @return {Ext.Toolbar.Item}
327      */
328     addField : function(field){
329         return this.add(field);
330     },
331
332     /**
333      * Inserts any {@link Ext.Toolbar.Item}/{@link Ext.Button} at the specified index.
334      * <br><p><b>Note</b>: See the notes within {@link Ext.Container#add}.</p>
335      * @param {Number} index The index where the item is to be inserted
336      * @param {Object/Ext.Toolbar.Item/Ext.Button/Array} item The button, or button config object to be
337      * inserted, or an array of buttons/configs.
338      * @return {Ext.Button/Item}
339      */
340     insertButton : function(index, item){
341         if(Ext.isArray(item)){
342             var buttons = [];
343             for(var i = 0, len = item.length; i < len; i++) {
344                buttons.push(this.insertButton(index + i, item[i]));
345             }
346             return buttons;
347         }
348         return Ext.Toolbar.superclass.insert.call(this, index, item);
349     },
350
351     // private
352     trackMenu : function(item, remove){
353         if(this.trackMenus && item.menu){
354             var method = remove ? 'mun' : 'mon';
355             this[method](item, 'menutriggerover', this.onButtonTriggerOver, this);
356             this[method](item, 'menushow', this.onButtonMenuShow, this);
357             this[method](item, 'menuhide', this.onButtonMenuHide, this);
358         }
359     },
360
361     // private
362     constructButton : function(item){
363         var b = item.events ? item : this.createComponent(item, item.split ? 'splitbutton' : this.defaultType);
364         return b;
365     },
366
367     // private
368     onAdd : function(c){
369         Ext.Toolbar.superclass.onAdd.call(this);
370         this.trackMenu(c);
371         if(this.disabled){
372             c.disable();
373         }
374     },
375
376     // private
377     onRemove : function(c){
378         Ext.Toolbar.superclass.onRemove.call(this);
379         this.trackMenu(c, true);
380     },
381
382     // private
383     onDisable : function(){
384         this.items.each(function(item){
385              if(item.disable){
386                  item.disable();
387              }
388         });
389     },
390
391     // private
392     onEnable : function(){
393         this.items.each(function(item){
394              if(item.enable){
395                  item.enable();
396              }
397         });
398     },
399
400     // private
401     onButtonTriggerOver : function(btn){
402         if(this.activeMenuBtn && this.activeMenuBtn != btn){
403             this.activeMenuBtn.hideMenu();
404             btn.showMenu();
405             this.activeMenuBtn = btn;
406         }
407     },
408
409     // private
410     onButtonMenuShow : function(btn){
411         this.activeMenuBtn = btn;
412     },
413
414     // private
415     onButtonMenuHide : function(btn){
416         delete this.activeMenuBtn;
417     }
418 });
419 Ext.reg('toolbar', Ext.Toolbar);
420
421 /**
422  * @class Ext.Toolbar.Item
423  * @extends Ext.BoxComponent
424  * The base class that other non-interacting Toolbar Item classes should extend in order to
425  * get some basic common toolbar item functionality.
426  * @constructor
427  * Creates a new Item
428  * @param {HTMLElement} el
429  * @xtype tbitem
430  */
431 T.Item = Ext.extend(Ext.BoxComponent, {
432     hideParent: true, //  Hiding a Toolbar.Item hides its containing TD
433     enable:Ext.emptyFn,
434     disable:Ext.emptyFn,
435     focus:Ext.emptyFn
436     /**
437      * @cfg {String} overflowText Text to be used for the menu if the item is overflowed.
438      */
439 });
440 Ext.reg('tbitem', T.Item);
441
442 /**
443  * @class Ext.Toolbar.Separator
444  * @extends Ext.Toolbar.Item
445  * A simple class that adds a vertical separator bar between toolbar items
446  * (css class:<tt>'xtb-sep'</tt>). Example usage:
447  * <pre><code>
448 new Ext.Panel({
449     tbar : [
450         'Item 1',
451         {xtype: 'tbseparator'}, // or '-'
452         'Item 2'
453     ]
454 });
455 </code></pre>
456  * @constructor
457  * Creates a new Separator
458  * @xtype tbseparator
459  */
460 T.Separator = Ext.extend(T.Item, {
461     onRender : function(ct, position){
462         this.el = ct.createChild({tag:'span', cls:'xtb-sep'}, position);
463     }
464 });
465 Ext.reg('tbseparator', T.Separator);
466
467 /**
468  * @class Ext.Toolbar.Spacer
469  * @extends Ext.Toolbar.Item
470  * A simple element that adds extra horizontal space between items in a toolbar.
471  * By default a 2px wide space is added via css specification:<pre><code>
472 .x-toolbar .xtb-spacer {
473     width:2px;
474 }
475  * </code></pre>
476  * <p>Example usage:</p>
477  * <pre><code>
478 new Ext.Panel({
479     tbar : [
480         'Item 1',
481         {xtype: 'tbspacer'}, // or ' '
482         'Item 2',
483         // space width is also configurable via javascript
484         {xtype: 'tbspacer', width: 50}, // add a 50px space
485         'Item 3'
486     ]
487 });
488 </code></pre>
489  * @constructor
490  * Creates a new Spacer
491  * @xtype tbspacer
492  */
493 T.Spacer = Ext.extend(T.Item, {
494     /**
495      * @cfg {Number} width
496      * The width of the spacer in pixels (defaults to 2px via css style <tt>.x-toolbar .xtb-spacer</tt>).
497      */
498
499     onRender : function(ct, position){
500         this.el = ct.createChild({tag:'div', cls:'xtb-spacer', style: this.width?'width:'+this.width+'px':''}, position);
501     }
502 });
503 Ext.reg('tbspacer', T.Spacer);
504
505 /**
506  * @class Ext.Toolbar.Fill
507  * @extends Ext.Toolbar.Spacer
508  * A non-rendering placeholder item which instructs the Toolbar's Layout to begin using
509  * the right-justified button container.
510  * <pre><code>
511 new Ext.Panel({
512     tbar : [
513         'Item 1',
514         {xtype: 'tbfill'}, // or '->'
515         'Item 2'
516     ]
517 });
518 </code></pre>
519  * @constructor
520  * Creates a new Fill
521  * @xtype tbfill
522  */
523 T.Fill = Ext.extend(T.Item, {
524     // private
525     render : Ext.emptyFn,
526     isFill : true
527 });
528 Ext.reg('tbfill', T.Fill);
529
530 /**
531  * @class Ext.Toolbar.TextItem
532  * @extends Ext.Toolbar.Item
533  * A simple class that renders text directly into a toolbar
534  * (with css class:<tt>'xtb-text'</tt>). Example usage:
535  * <pre><code>
536 new Ext.Panel({
537     tbar : [
538         {xtype: 'tbtext', text: 'Item 1'} // or simply 'Item 1'
539     ]
540 });
541 </code></pre>
542  * @constructor
543  * Creates a new TextItem
544  * @param {String/Object} text A text string, or a config object containing a <tt>text</tt> property
545  * @xtype tbtext
546  */
547 T.TextItem = Ext.extend(T.Item, {
548     /**
549      * @cfg {String} text The text to be used as innerHTML (html tags are accepted)
550      */
551
552     constructor: function(config){
553         T.TextItem.superclass.constructor.call(this, Ext.isString(config) ? {text: config} : config);
554     },
555
556     // private
557     onRender : function(ct, position) {
558         this.autoEl = {cls: 'xtb-text', html: this.text || ''};
559         T.TextItem.superclass.onRender.call(this, ct, position);
560     },
561
562     /**
563      * Updates this item's text, setting the text to be used as innerHTML.
564      * @param {String} t The text to display (html accepted).
565      */
566     setText : function(t) {
567         if(this.rendered){
568             this.el.update(t);
569         }else{
570             this.text = t;
571         }
572     }
573 });
574 Ext.reg('tbtext', T.TextItem);
575
576 // backwards compat
577 T.Button = Ext.extend(Ext.Button, {});
578 T.SplitButton = Ext.extend(Ext.SplitButton, {});
579 Ext.reg('tbbutton', T.Button);
580 Ext.reg('tbsplit', T.SplitButton);
581
582 })();
583 /**
584  * @class Ext.ButtonGroup
585  * @extends Ext.Panel
586  * Container for a group of buttons. Example usage:
587  * <pre><code>
588 var p = new Ext.Panel({
589     title: 'Panel with Button Group',
590     width: 300,
591     height:200,
592     renderTo: document.body,
593     html: 'whatever',
594     tbar: [{
595         xtype: 'buttongroup',
596         {@link #columns}: 3,
597         title: 'Clipboard',
598         items: [{
599             text: 'Paste',
600             scale: 'large',
601             rowspan: 3, iconCls: 'add',
602             iconAlign: 'top',
603             cls: 'x-btn-as-arrow'
604         },{
605             xtype:'splitbutton',
606             text: 'Menu Button',
607             scale: 'large',
608             rowspan: 3,
609             iconCls: 'add',
610             iconAlign: 'top',
611             arrowAlign:'bottom',
612             menu: [{text: 'Menu Item 1'}]
613         },{
614             xtype:'splitbutton', text: 'Cut', iconCls: 'add16', menu: [{text: 'Cut Menu Item'}]
615         },{
616             text: 'Copy', iconCls: 'add16'
617         },{
618             text: 'Format', iconCls: 'add16'
619         }]
620     }]
621 });
622  * </code></pre>
623  * @constructor
624  * Create a new ButtonGroup.
625  * @param {Object} config The config object
626  * @xtype buttongroup
627  */
628 Ext.ButtonGroup = Ext.extend(Ext.Panel, {
629     /**
630      * @cfg {Number} columns The <tt>columns</tt> configuration property passed to the
631      * {@link #layout configured layout manager}. See {@link Ext.layout.TableLayout#columns}.
632      */
633     /**
634      * @cfg {String} baseCls  Defaults to <tt>'x-btn-group'</tt>.  See {@link Ext.Panel#baseCls}.
635      */
636     baseCls: 'x-btn-group',
637     /**
638      * @cfg {String} layout  Defaults to <tt>'table'</tt>.  See {@link Ext.Container#layout}.
639      */
640     layout:'table',
641     defaultType: 'button',
642     /**
643      * @cfg {Boolean} frame  Defaults to <tt>true</tt>.  See {@link Ext.Panel#frame}.
644      */
645     frame: true,
646     internalDefaults: {removeMode: 'container', hideParent: true},
647
648     initComponent : function(){
649         this.layoutConfig = this.layoutConfig || {};
650         Ext.applyIf(this.layoutConfig, {
651             columns : this.columns
652         });
653         if(!this.title){
654             this.addClass('x-btn-group-notitle');
655         }
656         this.on('afterlayout', this.onAfterLayout, this);
657         Ext.ButtonGroup.superclass.initComponent.call(this);
658     },
659
660     applyDefaults : function(c){
661         c = Ext.ButtonGroup.superclass.applyDefaults.call(this, c);
662         var d = this.internalDefaults;
663         if(c.events){
664             Ext.applyIf(c.initialConfig, d);
665             Ext.apply(c, d);
666         }else{
667             Ext.applyIf(c, d);
668         }
669         return c;
670     },
671
672     onAfterLayout : function(){
673         var bodyWidth = this.body.getFrameWidth('lr') + this.body.dom.firstChild.offsetWidth;
674         this.body.setWidth(bodyWidth);
675         this.el.setWidth(bodyWidth + this.getFrameWidth());
676     }
677     /**
678      * @cfg {Array} tools  @hide
679      */
680 });
681
682 Ext.reg('buttongroup', Ext.ButtonGroup);
683 /**
684  * @class Ext.PagingToolbar
685  * @extends Ext.Toolbar
686  * <p>As the amount of records increases, the time required for the browser to render
687  * them increases. Paging is used to reduce the amount of data exchanged with the client.
688  * Note: if there are more records/rows than can be viewed in the available screen area, vertical
689  * scrollbars will be added.</p>
690  * <p>Paging is typically handled on the server side (see exception below). The client sends
691  * parameters to the server side, which the server needs to interpret and then respond with the
692  * approprate data.</p>
693  * <p><b>Ext.PagingToolbar</b> is a specialized toolbar that is bound to a {@link Ext.data.Store}
694  * and provides automatic paging control. This Component {@link Ext.data.Store#load load}s blocks
695  * of data into the <tt>{@link #store}</tt> by passing {@link Ext.data.Store#paramNames paramNames} used for
696  * paging criteria.</p>
697  * <p>PagingToolbar is typically used as one of the Grid's toolbars:</p>
698  * <pre><code>
699 Ext.QuickTips.init(); // to display button quicktips
700
701 var myStore = new Ext.data.Store({
702     reader: new Ext.data.JsonReader({
703         {@link Ext.data.JsonReader#totalProperty totalProperty}: 'results', 
704         ...
705     }),
706     ...
707 });
708
709 var myPageSize = 25;  // server script should only send back 25 items at a time
710
711 var grid = new Ext.grid.GridPanel({
712     ...
713     store: myStore,
714     bbar: new Ext.PagingToolbar({
715         {@link #store}: myStore,       // grid and PagingToolbar using same store
716         {@link #displayInfo}: true,
717         {@link #pageSize}: myPageSize,
718         {@link #prependButtons}: true,
719         items: [
720             'text 1'
721         ]
722     })
723 });
724  * </code></pre>
725  *
726  * <p>To use paging, pass the paging requirements to the server when the store is first loaded.</p>
727  * <pre><code>
728 store.load({
729     params: {
730         // specify params for the first page load if using paging
731         start: 0,          
732         limit: myPageSize,
733         // other params
734         foo:   'bar'
735     }
736 });
737  * </code></pre>
738  * 
739  * <p>If using {@link Ext.data.Store#autoLoad store's autoLoad} configuration:</p>
740  * <pre><code>
741 var myStore = new Ext.data.Store({
742     {@link Ext.data.Store#autoLoad autoLoad}: {params:{start: 0, limit: 25}},
743     ...
744 });
745  * </code></pre>
746  * 
747  * <p>The packet sent back from the server would have this form:</p>
748  * <pre><code>
749 {
750     "success": true,
751     "results": 2000, 
752     "rows": [ // <b>*Note:</b> this must be an Array 
753         { "id":  1, "name": "Bill", "occupation": "Gardener" },
754         { "id":  2, "name":  "Ben", "occupation": "Horticulturalist" },
755         ...
756         { "id": 25, "name":  "Sue", "occupation": "Botanist" }
757     ]
758 }
759  * </code></pre>
760  * <p><u>Paging with Local Data</u></p>
761  * <p>Paging can also be accomplished with local data using extensions:</p>
762  * <div class="mdetail-params"><ul>
763  * <li><a href="http://extjs.com/forum/showthread.php?t=71532">Ext.ux.data.PagingStore</a></li>
764  * <li>Paging Memory Proxy (examples/ux/PagingMemoryProxy.js)</li>
765  * </ul></div>
766  * @constructor Create a new PagingToolbar
767  * @param {Object} config The config object
768  * @xtype paging
769  */
770 (function() {
771
772 var T = Ext.Toolbar;
773
774 Ext.PagingToolbar = Ext.extend(Ext.Toolbar, {
775     /**
776      * @cfg {Ext.data.Store} store
777      * The {@link Ext.data.Store} the paging toolbar should use as its data source (required).
778      */
779     /**
780      * @cfg {Boolean} displayInfo
781      * <tt>true</tt> to display the displayMsg (defaults to <tt>false</tt>)
782      */
783     /**
784      * @cfg {Number} pageSize
785      * The number of records to display per page (defaults to <tt>20</tt>)
786      */
787     pageSize : 20,
788     /**
789      * @cfg {Boolean} prependButtons
790      * <tt>true</tt> to insert any configured <tt>items</tt> <i>before</i> the paging buttons.
791      * Defaults to <tt>false</tt>.
792      */
793     /**
794      * @cfg {String} displayMsg
795      * The paging status message to display (defaults to <tt>'Displaying {0} - {1} of {2}'</tt>).
796      * Note that this string is formatted using the braced numbers <tt>{0}-{2}</tt> as tokens
797      * that are replaced by the values for start, end and total respectively. These tokens should
798      * be preserved when overriding this string if showing those values is desired.
799      */
800     displayMsg : 'Displaying {0} - {1} of {2}',
801     /**
802      * @cfg {String} emptyMsg
803      * The message to display when no records are found (defaults to 'No data to display')
804      */
805     emptyMsg : 'No data to display',
806     /**
807      * @cfg {String} beforePageText
808      * The text displayed before the input item (defaults to <tt>'Page'</tt>).
809      */
810     beforePageText : 'Page',
811     /**
812      * @cfg {String} afterPageText
813      * Customizable piece of the default paging text (defaults to <tt>'of {0}'</tt>). Note that
814      * this string is formatted using <tt>{0}</tt> as a token that is replaced by the number of
815      * total pages. This token should be preserved when overriding this string if showing the
816      * total page count is desired.
817      */
818     afterPageText : 'of {0}',
819     /**
820      * @cfg {String} firstText
821      * The quicktip text displayed for the first page button (defaults to <tt>'First Page'</tt>).
822      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
823      */
824     firstText : 'First Page',
825     /**
826      * @cfg {String} prevText
827      * The quicktip text displayed for the previous page button (defaults to <tt>'Previous Page'</tt>).
828      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
829      */
830     prevText : 'Previous Page',
831     /**
832      * @cfg {String} nextText
833      * The quicktip text displayed for the next page button (defaults to <tt>'Next Page'</tt>).
834      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
835      */
836     nextText : 'Next Page',
837     /**
838      * @cfg {String} lastText
839      * The quicktip text displayed for the last page button (defaults to <tt>'Last Page'</tt>).
840      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
841      */
842     lastText : 'Last Page',
843     /**
844      * @cfg {String} refreshText
845      * The quicktip text displayed for the Refresh button (defaults to <tt>'Refresh'</tt>).
846      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
847      */
848     refreshText : 'Refresh',
849
850     /**
851      * <p><b>Deprecated</b>. <code>paramNames</code> should be set in the <b>data store</b>
852      * (see {@link Ext.data.Store#paramNames}).</p>
853      * <br><p>Object mapping of parameter names used for load calls, initially set to:</p>
854      * <pre>{start: 'start', limit: 'limit'}</pre>
855      * @type Object
856      * @property paramNames
857      * @deprecated
858      */
859
860     /**
861      * The number of records to display per page.  See also <tt>{@link #cursor}</tt>.
862      * @type Number
863      * @property pageSize
864      */
865
866     /**
867      * Indicator for the record position.  This property might be used to get the active page
868      * number for example:<pre><code>
869      * // t is reference to the paging toolbar instance
870      * var activePage = Math.ceil((t.cursor + t.pageSize) / t.pageSize);
871      * </code></pre>
872      * @type Number
873      * @property cursor
874      */
875
876     initComponent : function(){
877         var pagingItems = [this.first = new T.Button({
878             tooltip: this.firstText,
879             overflowText: this.firstText,
880             iconCls: 'x-tbar-page-first',
881             disabled: true,
882             handler: this.moveFirst,
883             scope: this
884         }), this.prev = new T.Button({
885             tooltip: this.prevText,
886             overflowText: this.prevText,
887             iconCls: 'x-tbar-page-prev',
888             disabled: true,
889             handler: this.movePrevious,
890             scope: this
891         }), '-', this.beforePageText,
892         this.inputItem = new Ext.form.NumberField({
893             cls: 'x-tbar-page-number',
894             allowDecimals: false,
895             allowNegative: false,
896             enableKeyEvents: true,
897             selectOnFocus: true,
898             submitValue: false,
899             listeners: {
900                 scope: this,
901                 keydown: this.onPagingKeyDown,
902                 blur: this.onPagingBlur
903             }
904         }), this.afterTextItem = new T.TextItem({
905             text: String.format(this.afterPageText, 1)
906         }), '-', this.next = new T.Button({
907             tooltip: this.nextText,
908             overflowText: this.nextText,
909             iconCls: 'x-tbar-page-next',
910             disabled: true,
911             handler: this.moveNext,
912             scope: this
913         }), this.last = new T.Button({
914             tooltip: this.lastText,
915             overflowText: this.lastText,
916             iconCls: 'x-tbar-page-last',
917             disabled: true,
918             handler: this.moveLast,
919             scope: this
920         }), '-', this.refresh = new T.Button({
921             tooltip: this.refreshText,
922             overflowText: this.refreshText,
923             iconCls: 'x-tbar-loading',
924             handler: this.doRefresh,
925             scope: this
926         })];
927
928
929         var userItems = this.items || this.buttons || [];
930         if (this.prependButtons) {
931             this.items = userItems.concat(pagingItems);
932         }else{
933             this.items = pagingItems.concat(userItems);
934         }
935         delete this.buttons;
936         if(this.displayInfo){
937             this.items.push('->');
938             this.items.push(this.displayItem = new T.TextItem({}));
939         }
940         Ext.PagingToolbar.superclass.initComponent.call(this);
941         this.addEvents(
942             /**
943              * @event change
944              * Fires after the active page has been changed.
945              * @param {Ext.PagingToolbar} this
946              * @param {Object} pageData An object that has these properties:<ul>
947              * <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
948              * returned by the server</div></li>
949              * <li><code>activePage</code> : Number <div class="sub-desc">The current page number</div></li>
950              * <li><code>pages</code> : Number <div class="sub-desc">The total number of pages (calculated from
951              * the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
952              * </ul>
953              */
954             'change',
955             /**
956              * @event beforechange
957              * Fires just before the active page is changed.
958              * Return false to prevent the active page from being changed.
959              * @param {Ext.PagingToolbar} this
960              * @param {Object} params An object hash of the parameters which the PagingToolbar will send when
961              * loading the required page. This will contain:<ul>
962              * <li><code>start</code> : Number <div class="sub-desc">The starting row number for the next page of records to
963              * be retrieved from the server</div></li>
964              * <li><code>limit</code> : Number <div class="sub-desc">The number of records to be retrieved from the server</div></li>
965              * </ul>
966              * <p>(note: the names of the <b>start</b> and <b>limit</b> properties are determined
967              * by the store's {@link Ext.data.Store#paramNames paramNames} property.)</p>
968              * <p>Parameters may be added as required in the event handler.</p>
969              */
970             'beforechange'
971         );
972         this.on('afterlayout', this.onFirstLayout, this, {single: true});
973         this.cursor = 0;
974         this.bindStore(this.store, true);
975     },
976
977     // private
978     onFirstLayout : function(){
979         if(this.dsLoaded){
980             this.onLoad.apply(this, this.dsLoaded);
981         }
982     },
983
984     // private
985     updateInfo : function(){
986         if(this.displayItem){
987             var count = this.store.getCount();
988             var msg = count == 0 ?
989                 this.emptyMsg :
990                 String.format(
991                     this.displayMsg,
992                     this.cursor+1, this.cursor+count, this.store.getTotalCount()
993                 );
994             this.displayItem.setText(msg);
995         }
996     },
997
998     // private
999     onLoad : function(store, r, o){
1000         if(!this.rendered){
1001             this.dsLoaded = [store, r, o];
1002             return;
1003         }
1004         var p = this.getParams();
1005         this.cursor = (o.params && o.params[p.start]) ? o.params[p.start] : 0;
1006         var d = this.getPageData(), ap = d.activePage, ps = d.pages;
1007
1008         this.afterTextItem.setText(String.format(this.afterPageText, d.pages));
1009         this.inputItem.setValue(ap);
1010         this.first.setDisabled(ap == 1);
1011         this.prev.setDisabled(ap == 1);
1012         this.next.setDisabled(ap == ps);
1013         this.last.setDisabled(ap == ps);
1014         this.refresh.enable();
1015         this.updateInfo();
1016         this.fireEvent('change', this, d);
1017     },
1018
1019     // private
1020     getPageData : function(){
1021         var total = this.store.getTotalCount();
1022         return {
1023             total : total,
1024             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
1025             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
1026         };
1027     },
1028
1029     /**
1030      * Change the active page
1031      * @param {Integer} page The page to display
1032      */
1033     changePage : function(page){
1034         this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));
1035     },
1036
1037     // private
1038     onLoadError : function(){
1039         if(!this.rendered){
1040             return;
1041         }
1042         this.refresh.enable();
1043     },
1044
1045     // private
1046     readPage : function(d){
1047         var v = this.inputItem.getValue(), pageNum;
1048         if (!v || isNaN(pageNum = parseInt(v, 10))) {
1049             this.inputItem.setValue(d.activePage);
1050             return false;
1051         }
1052         return pageNum;
1053     },
1054
1055     onPagingFocus : function(){
1056         this.inputItem.select();
1057     },
1058
1059     //private
1060     onPagingBlur : function(e){
1061         this.inputItem.setValue(this.getPageData().activePage);
1062     },
1063
1064     // private
1065     onPagingKeyDown : function(field, e){
1066         var k = e.getKey(), d = this.getPageData(), pageNum;
1067         if (k == e.RETURN) {
1068             e.stopEvent();
1069             pageNum = this.readPage(d);
1070             if(pageNum !== false){
1071                 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
1072                 this.doLoad(pageNum * this.pageSize);
1073             }
1074         }else if (k == e.HOME || k == e.END){
1075             e.stopEvent();
1076             pageNum = k == e.HOME ? 1 : d.pages;
1077             field.setValue(pageNum);
1078         }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){
1079             e.stopEvent();
1080             if((pageNum = this.readPage(d))){
1081                 var increment = e.shiftKey ? 10 : 1;
1082                 if(k == e.DOWN || k == e.PAGEDOWN){
1083                     increment *= -1;
1084                 }
1085                 pageNum += increment;
1086                 if(pageNum >= 1 & pageNum <= d.pages){
1087                     field.setValue(pageNum);
1088                 }
1089             }
1090         }
1091     },
1092
1093     // private
1094     getParams : function(){
1095         //retain backwards compat, allow params on the toolbar itself, if they exist.
1096         return this.paramNames || this.store.paramNames;
1097     },
1098
1099     // private
1100     beforeLoad : function(){
1101         if(this.rendered && this.refresh){
1102             this.refresh.disable();
1103         }
1104     },
1105
1106     // private
1107     doLoad : function(start){
1108         var o = {}, pn = this.getParams();
1109         o[pn.start] = start;
1110         o[pn.limit] = this.pageSize;
1111         if(this.fireEvent('beforechange', this, o) !== false){
1112             this.store.load({params:o});
1113         }
1114     },
1115
1116     /**
1117      * Move to the first page, has the same effect as clicking the 'first' button.
1118      */
1119     moveFirst : function(){
1120         this.doLoad(0);
1121     },
1122
1123     /**
1124      * Move to the previous page, has the same effect as clicking the 'previous' button.
1125      */
1126     movePrevious : function(){
1127         this.doLoad(Math.max(0, this.cursor-this.pageSize));
1128     },
1129
1130     /**
1131      * Move to the next page, has the same effect as clicking the 'next' button.
1132      */
1133     moveNext : function(){
1134         this.doLoad(this.cursor+this.pageSize);
1135     },
1136
1137     /**
1138      * Move to the last page, has the same effect as clicking the 'last' button.
1139      */
1140     moveLast : function(){
1141         var total = this.store.getTotalCount(),
1142             extra = total % this.pageSize;
1143
1144         this.doLoad(extra ? (total - extra) : total - this.pageSize);
1145     },
1146
1147     /**
1148      * Refresh the current page, has the same effect as clicking the 'refresh' button.
1149      */
1150     doRefresh : function(){
1151         this.doLoad(this.cursor);
1152     },
1153
1154     /**
1155      * Binds the paging toolbar to the specified {@link Ext.data.Store}
1156      * @param {Store} store The store to bind to this toolbar
1157      * @param {Boolean} initial (Optional) true to not remove listeners
1158      */
1159     bindStore : function(store, initial){
1160         var doLoad;
1161         if(!initial && this.store){
1162             if(store !== this.store && this.store.autoDestroy){
1163                 this.store.destroy();
1164             }else{
1165                 this.store.un('beforeload', this.beforeLoad, this);
1166                 this.store.un('load', this.onLoad, this);
1167                 this.store.un('exception', this.onLoadError, this);
1168             }
1169             if(!store){
1170                 this.store = null;
1171             }
1172         }
1173         if(store){
1174             store = Ext.StoreMgr.lookup(store);
1175             store.on({
1176                 scope: this,
1177                 beforeload: this.beforeLoad,
1178                 load: this.onLoad,
1179                 exception: this.onLoadError
1180             });
1181             doLoad = true;
1182         }
1183         this.store = store;
1184         if(doLoad){
1185             this.onLoad(store, null, {});
1186         }
1187     },
1188
1189     /**
1190      * Unbinds the paging toolbar from the specified {@link Ext.data.Store} <b>(deprecated)</b>
1191      * @param {Ext.data.Store} store The data store to unbind
1192      */
1193     unbind : function(store){
1194         this.bindStore(null);
1195     },
1196
1197     /**
1198      * Binds the paging toolbar to the specified {@link Ext.data.Store} <b>(deprecated)</b>
1199      * @param {Ext.data.Store} store The data store to bind
1200      */
1201     bind : function(store){
1202         this.bindStore(store);
1203     },
1204
1205     // private
1206     onDestroy : function(){
1207         this.bindStore(null);
1208         Ext.PagingToolbar.superclass.onDestroy.call(this);
1209     }
1210 });
1211
1212 })();
1213 Ext.reg('paging', Ext.PagingToolbar);