ux-all-debug.js
资源名称:ext-3.1.0.zip [点击查看]
上传用户:dawnssy
上传日期:2022-08-06
资源大小:9345k
文件大小:337k
源码类别:
JavaScript
开发平台:
JavaScript
- /*! * Ext JS Library 3.1.0 * Copyright(c) 2006-2009 Ext JS, LLC * licensing@extjs.com * http://www.extjs.com/license */ Ext.ns('Ext.ux.grid'); /** * @class Ext.ux.grid.BufferView * @extends Ext.grid.GridView * A custom GridView which renders rows on an as-needed basis. */ Ext.ux.grid.BufferView = Ext.extend(Ext.grid.GridView, { /** * @cfg {Number} rowHeight * The height of a row in the grid. */ rowHeight: 19, /** * @cfg {Number} borderHeight * The combined height of border-top and border-bottom of a row. */ borderHeight: 2, /** * @cfg {Boolean/Number} scrollDelay * The number of milliseconds before rendering rows out of the visible * viewing area. Defaults to 100. Rows will render immediately with a config * of false. */ scrollDelay: 100, /** * @cfg {Number} cacheSize * The number of rows to look forward and backwards from the currently viewable * area. The cache applies only to rows that have been rendered already. */ cacheSize: 20, /** * @cfg {Number} cleanDelay * The number of milliseconds to buffer cleaning of extra rows not in the * cache. */ cleanDelay: 500, initTemplates : function(){ Ext.ux.grid.BufferView.superclass.initTemplates.call(this); var ts = this.templates; // empty div to act as a place holder for a row ts.rowHolder = new Ext.Template( '<div class="x-grid3-row {alt}" style="{tstyle}"></div>' ); ts.rowHolder.disableFormats = true; ts.rowHolder.compile(); ts.rowBody = new Ext.Template( '<table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">', '<tbody><tr>{cells}</tr>', (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''), '</tbody></table>' ); ts.rowBody.disableFormats = true; ts.rowBody.compile(); }, getStyleRowHeight : function(){ return Ext.isBorderBox ? (this.rowHeight + this.borderHeight) : this.rowHeight; }, getCalculatedRowHeight : function(){ return this.rowHeight + this.borderHeight; }, getVisibleRowCount : function(){ var rh = this.getCalculatedRowHeight(); var visibleHeight = this.scroller.dom.clientHeight; return (visibleHeight < 1) ? 0 : Math.ceil(visibleHeight / rh); }, getVisibleRows: function(){ var count = this.getVisibleRowCount(); var sc = this.scroller.dom.scrollTop; var start = (sc == 0 ? 0 : Math.floor(sc/this.getCalculatedRowHeight())-1); return { first: Math.max(start, 0), last: Math.min(start + count + 2, this.ds.getCount()-1) }; }, doRender : function(cs, rs, ds, startRow, colCount, stripe, onlyBody){ var ts = this.templates, ct = ts.cell, rt = ts.row, rb = ts.rowBody, last = colCount-1; var rh = this.getStyleRowHeight(); var vr = this.getVisibleRows(); var tstyle = 'width:'+this.getTotalWidth()+';height:'+rh+'px;'; // buffers var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r; for (var j = 0, len = rs.length; j < len; j++) { r = rs[j]; cb = []; var rowIndex = (j+startRow); var visible = rowIndex >= vr.first && rowIndex <= vr.last; if (visible) { for (var i = 0; i < colCount; i++) { c = cs[i]; p.id = c.id; p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : ''); p.attr = p.cellAttr = ""; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); p.style = c.style; if (p.value == undefined || p.value === "") { p.value = " "; } if (r.dirty && typeof r.modified[c.name] !== 'undefined') { p.css += ' x-grid3-dirty-cell'; } cb[cb.length] = ct.apply(p); } } var alt = []; if(stripe && ((rowIndex+1) % 2 == 0)){ alt[0] = "x-grid3-row-alt"; } if(r.dirty){ alt[1] = " x-grid3-dirty-row"; } rp.cols = colCount; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex, rp, ds); } rp.alt = alt.join(" "); rp.cells = cb.join(""); buf[buf.length] = !visible ? ts.rowHolder.apply(rp) : (onlyBody ? rb.apply(rp) : rt.apply(rp)); } return buf.join(""); }, isRowRendered: function(index){ var row = this.getRow(index); return row && row.childNodes.length > 0; }, syncScroll: function(){ Ext.ux.grid.BufferView.superclass.syncScroll.apply(this, arguments); this.update(); }, // a (optionally) buffered method to update contents of gridview update: function(){ if (this.scrollDelay) { if (!this.renderTask) { this.renderTask = new Ext.util.DelayedTask(this.doUpdate, this); } this.renderTask.delay(this.scrollDelay); }else{ this.doUpdate(); } }, onRemove : function(ds, record, index, isUpdate){ Ext.ux.grid.BufferView.superclass.onRemove.apply(this, arguments); if(isUpdate !== true){ this.update(); } }, doUpdate: function(){ if (this.getVisibleRowCount() > 0) { var g = this.grid, cm = g.colModel, ds = g.store; var cs = this.getColumnData(); var vr = this.getVisibleRows(); for (var i = vr.first; i <= vr.last; i++) { // if row is NOT rendered and is visible, render it if(!this.isRowRendered(i)){ var html = this.doRender(cs, [ds.getAt(i)], ds, i, cm.getColumnCount(), g.stripeRows, true); this.getRow(i).innerHTML = html; } } this.clean(); } }, // a buffered method to clean rows clean : function(){ if(!this.cleanTask){ this.cleanTask = new Ext.util.DelayedTask(this.doClean, this); } this.cleanTask.delay(this.cleanDelay); }, doClean: function(){ if (this.getVisibleRowCount() > 0) { var vr = this.getVisibleRows(); vr.first -= this.cacheSize; vr.last += this.cacheSize; var i = 0, rows = this.getRows(); // if first is less than 0, all rows have been rendered // so lets clean the end... if(vr.first <= 0){ i = vr.last + 1; } for(var len = this.ds.getCount(); i < len; i++){ // if current row is outside of first and last and // has content, update the innerHTML to nothing if ((i < vr.first || i > vr.last) && rows[i].innerHTML) { rows[i].innerHTML = ''; } } } }, layout: function(){ Ext.ux.grid.BufferView.superclass.layout.call(this); this.update(); } }); // We are adding these custom layouts to a namespace that does not // exist by default in Ext, so we have to add the namespace first: Ext.ns('Ext.ux.layout'); /** * @class Ext.ux.layout.CenterLayout * @extends Ext.layout.FitLayout * <p>This is a very simple layout style used to center contents within a container. This layout works within * nested containers and can also be used as expected as a Viewport layout to center the page layout.</p> * <p>As a subclass of FitLayout, CenterLayout expects to have a single child panel of the container that uses * the layout. The layout does not require any config options, although the child panel contained within the * layout must provide a fixed or percentage width. The child panel's height will fit to the container by * default, but you can specify <tt>autoHeight:true</tt> to allow it to autosize based on its content height. * Example usage:</p> * <pre><code> // The content panel is centered in the container var p = new Ext.Panel({ title: 'Center Layout', layout: 'ux.center', items: [{ title: 'Centered Content', width: '75%', html: 'Some content' }] }); // If you leave the title blank and specify no border // you'll create a non-visual, structural panel just // for centering the contents in the main container. var p = new Ext.Panel({ layout: 'ux.center', border: false, items: [{ title: 'Centered Content', width: 300, autoHeight: true, html: 'Some content' }] }); </code></pre> */ Ext.ux.layout.CenterLayout = Ext.extend(Ext.layout.FitLayout, { // private setItemSize : function(item, size){ this.container.addClass('ux-layout-center'); item.addClass('ux-layout-center-item'); if(item && size.height > 0){ if(item.width){ size.width = item.width; } item.setSize(size); } } }); Ext.Container.LAYOUTS['ux.center'] = Ext.ux.layout.CenterLayout; Ext.ns('Ext.ux.grid');
- /**
- * @class Ext.ux.grid.CheckColumn
- * @extends Object
- * GridPanel plugin to add a column with check boxes to a grid.
- * <p>Example usage:</p>
- * <pre><code>
- // create the column
- var checkColumn = new Ext.grid.CheckColumn({
- header: 'Indoor?',
- dataIndex: 'indoor',
- id: 'check',
- width: 55
- });
- // add the column to the column model
- var cm = new Ext.grid.ColumnModel([{
- header: 'Foo',
- ...
- },
- checkColumn
- ]);
- // create the grid
- var grid = new Ext.grid.EditorGridPanel({
- ...
- cm: cm,
- plugins: [checkColumn], // include plugin
- ...
- });
- * </code></pre>
- * In addition to storing a Boolean value within the record data, this
- * class toggles a css class between <tt>'x-grid3-check-col'</tt> and
- * <tt>'x-grid3-check-col-on'</tt> to alter the background image used for
- * a column.
- */
- Ext.ux.grid.CheckColumn = function(config){
- Ext.apply(this, config);
- if(!this.id){
- this.id = Ext.id();
- }
- this.renderer = this.renderer.createDelegate(this);
- };
- Ext.ux.grid.CheckColumn.prototype ={
- init : function(grid){
- this.grid = grid;
- this.grid.on('render', function(){
- var view = this.grid.getView();
- view.mainBody.on('mousedown', this.onMouseDown, this);
- }, this);
- },
- onMouseDown : function(e, t){
- if(t.className && t.className.indexOf('x-grid3-cc-'+this.id) != -1){
- e.stopEvent();
- var index = this.grid.getView().findRowIndex(t);
- var record = this.grid.store.getAt(index);
- record.set(this.dataIndex, !record.data[this.dataIndex]);
- }
- },
- renderer : function(v, p, record){
- p.css += ' x-grid3-check-col-td';
- return '<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'"> </div>';
- }
- };
- // register ptype
- Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn);
- // backwards compat
- Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn;Ext.ns('Ext.ux.grid');
- if(Ext.isWebKit){
- Ext.grid.GridView.prototype.borderWidth = 0;
- }
- Ext.ux.grid.ColumnHeaderGroup = Ext.extend(Ext.util.Observable, {
- constructor: function(config){
- this.config = config;
- },
- init: function(grid){
- Ext.applyIf(grid.colModel, this.config);
- Ext.apply(grid.getView(), this.viewConfig);
- },
- viewConfig: {
- initTemplates: function(){
- this.constructor.prototype.initTemplates.apply(this, arguments);
- var ts = this.templates || {};
- if(!ts.gcell){
- ts.gcell = new Ext.XTemplate('<td class="x-grid3-hd x-grid3-gcell x-grid3-td-{id} ux-grid-hd-group-row-{row} {cls}" style="{style}">', '<div {tooltip} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '', '{value}</div></td>');
- }
- this.templates = ts;
- this.hrowRe = new RegExp("ux-grid-hd-group-row-(\d+)", "");
- },
- renderHeaders: function(){
- var ts = this.templates, headers = [], cm = this.cm, rows = cm.rows, tstyle = 'width:' + this.getTotalWidth() + ';';
- for(var row = 0, rlen = rows.length; row < rlen; row++){
- var r = rows[row], cells = [];
- for(var i = 0, gcol = 0, len = r.length; i < len; i++){
- var group = r[i];
- group.colspan = group.colspan || 1;
- var id = this.getColumnId(group.dataIndex ? cm.findColumnIndex(group.dataIndex) : gcol), gs = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupStyle.call(this, group, gcol);
- cells[i] = ts.gcell.apply({
- cls: 'ux-grid-hd-group-cell',
- id: id,
- row: row,
- style: 'width:' + gs.width + ';' + (gs.hidden ? 'display:none;' : '') + (group.align ? 'text-align:' + group.align + ';' : ''),
- tooltip: group.tooltip ? (Ext.QuickTips.isEnabled() ? 'ext:qtip' : 'title') + '="' + group.tooltip + '"' : '',
- istyle: group.align == 'right' ? 'padding-right:16px' : '',
- btn: this.grid.enableHdMenu && group.header,
- value: group.header || ' '
- });
- gcol += group.colspan;
- }
- headers[row] = ts.header.apply({
- tstyle: tstyle,
- cells: cells.join('')
- });
- }
- headers.push(this.constructor.prototype.renderHeaders.apply(this, arguments));
- return headers.join('');
- },
- onColumnWidthUpdated: function(){
- this.constructor.prototype.onColumnWidthUpdated.apply(this, arguments);
- Ext.ux.grid.ColumnHeaderGroup.prototype.updateGroupStyles.call(this);
- },
- onAllColumnWidthsUpdated: function(){
- this.constructor.prototype.onAllColumnWidthsUpdated.apply(this, arguments);
- Ext.ux.grid.ColumnHeaderGroup.prototype.updateGroupStyles.call(this);
- },
- onColumnHiddenUpdated: function(){
- this.constructor.prototype.onColumnHiddenUpdated.apply(this, arguments);
- Ext.ux.grid.ColumnHeaderGroup.prototype.updateGroupStyles.call(this);
- },
- getHeaderCell: function(index){
- return this.mainHd.query(this.cellSelector)[index];
- },
- findHeaderCell: function(el){
- return el ? this.fly(el).findParent('td.x-grid3-hd', this.cellSelectorDepth) : false;
- },
- findHeaderIndex: function(el){
- var cell = this.findHeaderCell(el);
- return cell ? this.getCellIndex(cell) : false;
- },
- updateSortIcon: function(col, dir){
- var sc = this.sortClasses, hds = this.mainHd.select(this.cellSelector).removeClass(sc);
- hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]);
- },
- handleHdDown: function(e, t){
- var el = Ext.get(t);
- if(el.hasClass('x-grid3-hd-btn')){
- e.stopEvent();
- var hd = this.findHeaderCell(t);
- Ext.fly(hd).addClass('x-grid3-hd-menu-open');
- var index = this.getCellIndex(hd);
- this.hdCtxIndex = index;
- var ms = this.hmenu.items, cm = this.cm;
- ms.get('asc').setDisabled(!cm.isSortable(index));
- ms.get('desc').setDisabled(!cm.isSortable(index));
- this.hmenu.on('hide', function(){
- Ext.fly(hd).removeClass('x-grid3-hd-menu-open');
- }, this, {
- single: true
- });
- this.hmenu.show(t, 'tl-bl?');
- }else if(el.hasClass('ux-grid-hd-group-cell') || Ext.fly(t).up('.ux-grid-hd-group-cell')){
- e.stopEvent();
- }
- },
- handleHdMove: function(e, t){
- var hd = this.findHeaderCell(this.activeHdRef);
- if(hd && !this.headersDisabled && !Ext.fly(hd).hasClass('ux-grid-hd-group-cell')){
- var hw = this.splitHandleWidth || 5, r = this.activeHdRegion, x = e.getPageX(), ss = hd.style, cur = '';
- if(this.grid.enableColumnResize !== false){
- if(x - r.left <= hw && this.cm.isResizable(this.activeHdIndex - 1)){
- cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'e-resize' : 'col-resize'; // col-resize
- // not
- // always
- // supported
- }else if(r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)){
- cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'w-resize' : 'col-resize';
- }
- }
- ss.cursor = cur;
- }
- },
- handleHdOver: function(e, t){
- var hd = this.findHeaderCell(t);
- if(hd && !this.headersDisabled){
- this.activeHdRef = t;
- this.activeHdIndex = this.getCellIndex(hd);
- var fly = this.fly(hd);
- this.activeHdRegion = fly.getRegion();
- if(!(this.cm.isMenuDisabled(this.activeHdIndex) || fly.hasClass('ux-grid-hd-group-cell'))){
- fly.addClass('x-grid3-hd-over');
- this.activeHdBtn = fly.child('.x-grid3-hd-btn');
- if(this.activeHdBtn){
- this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight - 1) + 'px';
- }
- }
- }
- },
- handleHdOut: function(e, t){
- var hd = this.findHeaderCell(t);
- if(hd && (!Ext.isIE || !e.within(hd, true))){
- this.activeHdRef = null;
- this.fly(hd).removeClass('x-grid3-hd-over');
- hd.style.cursor = '';
- }
- },
- handleHdMenuClick: function(item){
- var index = this.hdCtxIndex, cm = this.cm, ds = this.ds, id = item.getItemId();
- switch(id){
- case 'asc':
- ds.sort(cm.getDataIndex(index), 'ASC');
- break;
- case 'desc':
- ds.sort(cm.getDataIndex(index), 'DESC');
- break;
- default:
- if(id.substr(0, 5) == 'group'){
- var i = id.split('-'), row = parseInt(i[1], 10), col = parseInt(i[2], 10), r = this.cm.rows[row], group, gcol = 0;
- for(var i = 0, len = r.length; i < len; i++){
- group = r[i];
- if(col >= gcol && col < gcol + group.colspan){
- break;
- }
- gcol += group.colspan;
- }
- if(item.checked){
- var max = cm.getColumnsBy(this.isHideableColumn, this).length;
- for(var i = gcol, len = gcol + group.colspan; i < len; i++){
- if(!cm.isHidden(i)){
- max--;
- }
- }
- if(max < 1){
- this.onDenyColumnHide();
- return false;
- }
- }
- for(var i = gcol, len = gcol + group.colspan; i < len; i++){
- if(cm.config[i].fixed !== true && cm.config[i].hideable !== false){
- cm.setHidden(i, item.checked);
- }
- }
- }else{
- index = cm.getIndexById(id.substr(4));
- if(index != -1){
- if(item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1){
- this.onDenyColumnHide();
- return false;
- }
- cm.setHidden(index, item.checked);
- }
- }
- item.checked = !item.checked;
- if(item.menu){
- var updateChildren = function(menu){
- menu.items.each(function(childItem){
- if(!childItem.disabled){
- childItem.setChecked(item.checked, false);
- if(childItem.menu){
- updateChildren(childItem.menu);
- }
- }
- });
- }
- updateChildren(item.menu);
- }
- var parentMenu = item, parentItem;
- while(parentMenu = parentMenu.parentMenu){
- if(!parentMenu.parentMenu || !(parentItem = parentMenu.parentMenu.items.get(parentMenu.getItemId())) || !parentItem.setChecked){
- break;
- }
- var checked = parentMenu.items.findIndexBy(function(m){
- return m.checked;
- }) >= 0;
- parentItem.setChecked(checked, true);
- }
- item.checked = !item.checked;
- }
- return true;
- },
- beforeColMenuShow: function(){
- var cm = this.cm, rows = this.cm.rows;
- this.colMenu.removeAll();
- for(var col = 0, clen = cm.getColumnCount(); col < clen; col++){
- var menu = this.colMenu, title = cm.getColumnHeader(col), text = [];
- if(cm.config[col].fixed !== true && cm.config[col].hideable !== false){
- for(var row = 0, rlen = rows.length; row < rlen; row++){
- var r = rows[row], group, gcol = 0;
- for(var i = 0, len = r.length; i < len; i++){
- group = r[i];
- if(col >= gcol && col < gcol + group.colspan){
- break;
- }
- gcol += group.colspan;
- }
- if(group && group.header){
- if(cm.hierarchicalColMenu){
- var gid = 'group-' + row + '-' + gcol;
- var item = menu.items.item(gid);
- var submenu = item ? item.menu : null;
- if(!submenu){
- submenu = new Ext.menu.Menu({
- itemId: gid
- });
- submenu.on("itemclick", this.handleHdMenuClick, this);
- var checked = false, disabled = true;
- for(var c = gcol, lc = gcol + group.colspan; c < lc; c++){
- if(!cm.isHidden(c)){
- checked = true;
- }
- if(cm.config[c].hideable !== false){
- disabled = false;
- }
- }
- menu.add({
- itemId: gid,
- text: group.header,
- menu: submenu,
- hideOnClick: false,
- checked: checked,
- disabled: disabled
- });
- }
- menu = submenu;
- }else{
- text.push(group.header);
- }
- }
- }
- text.push(title);
- menu.add(new Ext.menu.CheckItem({
- itemId: "col-" + cm.getColumnId(col),
- text: text.join(' '),
- checked: !cm.isHidden(col),
- hideOnClick: false,
- disabled: cm.config[col].hideable === false
- }));
- }
- }
- },
- renderUI: function(){
- this.constructor.prototype.renderUI.apply(this, arguments);
- Ext.apply(this.columnDrop, Ext.ux.grid.ColumnHeaderGroup.prototype.columnDropConfig);
- Ext.apply(this.splitZone, Ext.ux.grid.ColumnHeaderGroup.prototype.splitZoneConfig);
- }
- },
- splitZoneConfig: {
- allowHeaderDrag: function(e){
- return !e.getTarget(null, null, true).hasClass('ux-grid-hd-group-cell');
- }
- },
- columnDropConfig: {
- getTargetFromEvent: function(e){
- var t = Ext.lib.Event.getTarget(e);
- return this.view.findHeaderCell(t);
- },
- positionIndicator: function(h, n, e){
- var data = Ext.ux.grid.ColumnHeaderGroup.prototype.getDragDropData.call(this, h, n, e);
- if(data === false){
- return false;
- }
- var px = data.px + this.proxyOffsets[0];
- this.proxyTop.setLeftTop(px, data.r.top + this.proxyOffsets[1]);
- this.proxyTop.show();
- this.proxyBottom.setLeftTop(px, data.r.bottom);
- this.proxyBottom.show();
- return data.pt;
- },
- onNodeDrop: function(n, dd, e, data){
- var h = data.header;
- if(h != n){
- var d = Ext.ux.grid.ColumnHeaderGroup.prototype.getDragDropData.call(this, h, n, e);
- if(d === false){
- return false;
- }
- var cm = this.grid.colModel, right = d.oldIndex < d.newIndex, rows = cm.rows;
- for(var row = d.row, rlen = rows.length; row < rlen; row++){
- var r = rows[row], len = r.length, fromIx = 0, span = 1, toIx = len;
- for(var i = 0, gcol = 0; i < len; i++){
- var group = r[i];
- if(d.oldIndex >= gcol && d.oldIndex < gcol + group.colspan){
- fromIx = i;
- }
- if(d.oldIndex + d.colspan - 1 >= gcol && d.oldIndex + d.colspan - 1 < gcol + group.colspan){
- span = i - fromIx + 1;
- }
- if(d.newIndex >= gcol && d.newIndex < gcol + group.colspan){
- toIx = i;
- }
- gcol += group.colspan;
- }
- var groups = r.splice(fromIx, span);
- rows[row] = r.splice(0, toIx - (right ? span : 0)).concat(groups).concat(r);
- }
- for(var c = 0; c < d.colspan; c++){
- var oldIx = d.oldIndex + (right ? 0 : c), newIx = d.newIndex + (right ? -1 : c);
- cm.moveColumn(oldIx, newIx);
- this.grid.fireEvent("columnmove", oldIx, newIx);
- }
- return true;
- }
- return false;
- }
- },
- getGroupStyle: function(group, gcol){
- var width = 0, hidden = true;
- for(var i = gcol, len = gcol + group.colspan; i < len; i++){
- if(!this.cm.isHidden(i)){
- var cw = this.cm.getColumnWidth(i);
- if(typeof cw == 'number'){
- width += cw;
- }
- hidden = false;
- }
- }
- return {
- width: (Ext.isBorderBox ? width : Math.max(width - this.borderWidth, 0)) + 'px',
- hidden: hidden
- };
- },
- updateGroupStyles: function(col){
- var tables = this.mainHd.query('.x-grid3-header-offset > table'), tw = this.getTotalWidth(), rows = this.cm.rows;
- for(var row = 0; row < tables.length; row++){
- tables[row].style.width = tw;
- if(row < rows.length){
- var cells = tables[row].firstChild.firstChild.childNodes;
- for(var i = 0, gcol = 0; i < cells.length; i++){
- var group = rows[row][i];
- if((typeof col != 'number') || (col >= gcol && col < gcol + group.colspan)){
- var gs = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupStyle.call(this, group, gcol);
- cells[i].style.width = gs.width;
- cells[i].style.display = gs.hidden ? 'none' : '';
- }
- gcol += group.colspan;
- }
- }
- }
- },
- getGroupRowIndex: function(el){
- if(el){
- var m = el.className.match(this.hrowRe);
- if(m && m[1]){
- return parseInt(m[1], 10);
- }
- }
- return this.cm.rows.length;
- },
- getGroupSpan: function(row, col){
- if(row < 0){
- return {
- col: 0,
- colspan: this.cm.getColumnCount()
- };
- }
- var r = this.cm.rows[row];
- if(r){
- for(var i = 0, gcol = 0, len = r.length; i < len; i++){
- var group = r[i];
- if(col >= gcol && col < gcol + group.colspan){
- return {
- col: gcol,
- colspan: group.colspan
- };
- }
- gcol += group.colspan;
- }
- return {
- col: gcol,
- colspan: 0
- };
- }
- return {
- col: col,
- colspan: 1
- };
- },
- getDragDropData: function(h, n, e){
- if(h.parentNode != n.parentNode){
- return false;
- }
- var cm = this.grid.colModel, x = Ext.lib.Event.getPageX(e), r = Ext.lib.Dom.getRegion(n.firstChild), px, pt;
- if((r.right - x) <= (r.right - r.left) / 2){
- px = r.right + this.view.borderWidth;
- pt = "after";
- }else{
- px = r.left;
- pt = "before";
- }
- var oldIndex = this.view.getCellIndex(h), newIndex = this.view.getCellIndex(n);
- if(cm.isFixed(newIndex)){
- return false;
- }
- var row = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupRowIndex.call(this.view, h),
- oldGroup = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupSpan.call(this.view, row, oldIndex),
- newGroup = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupSpan.call(this.view, row, newIndex),
- oldIndex = oldGroup.col;
- newIndex = newGroup.col + (pt == "after" ? newGroup.colspan : 0);
- if(newIndex >= oldGroup.col && newIndex <= oldGroup.col + oldGroup.colspan){
- return false;
- }
- var parentGroup = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupSpan.call(this.view, row - 1, oldIndex);
- if(newIndex < parentGroup.col || newIndex > parentGroup.col + parentGroup.colspan){
- return false;
- }
- return {
- r: r,
- px: px,
- pt: pt,
- row: row,
- oldIndex: oldIndex,
- newIndex: newIndex,
- colspan: oldGroup.colspan
- };
- }
- });Ext.ns('Ext.ux.tree');
- /**
- * @class Ext.ux.tree.ColumnTree
- * @extends Ext.tree.TreePanel
- *
- * @xtype columntree
- */
- Ext.ux.tree.ColumnTree = Ext.extend(Ext.tree.TreePanel, {
- lines : false,
- borderWidth : Ext.isBorderBox ? 0 : 2, // the combined left/right border for each cell
- cls : 'x-column-tree',
- onRender : function(){
- Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
- this.headers = this.header.createChild({cls:'x-tree-headers'});
- var cols = this.columns, c;
- var totalWidth = 0;
- var scrollOffset = 19; // similar to Ext.grid.GridView default
- for(var i = 0, len = cols.length; i < len; i++){
- c = cols[i];
- totalWidth += c.width;
- this.headers.createChild({
- cls:'x-tree-hd ' + (c.cls?c.cls+'-hd':''),
- cn: {
- cls:'x-tree-hd-text',
- html: c.header
- },
- style:'width:'+(c.width-this.borderWidth)+'px;'
- });
- }
- this.headers.createChild({cls:'x-clear'});
- // prevent floats from wrapping when clipped
- this.headers.setWidth(totalWidth+scrollOffset);
- this.innerCt.setWidth(totalWidth);
- }
- });
- Ext.reg('columntree', Ext.ux.tree.ColumnTree);
- //backwards compat
- Ext.tree.ColumnTree = Ext.ux.tree.ColumnTree;
- /**
- * @class Ext.ux.tree.ColumnNodeUI
- * @extends Ext.tree.TreeNodeUI
- */
- Ext.ux.tree.ColumnNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
- focus: Ext.emptyFn, // prevent odd scrolling behavior
- renderElements : function(n, a, targetNode, bulkRender){
- this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
- var t = n.getOwnerTree();
- var cols = t.columns;
- var bw = t.borderWidth;
- var c = cols[0];
- var buf = [
- '<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf ', a.cls,'">',
- '<div class="x-tree-col" style="width:',c.width-bw,'px;">',
- '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
- '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow">',
- '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on">',
- '<a hidefocus="on" class="x-tree-node-anchor" href="',a.href ? a.href : "#",'" tabIndex="1" ',
- a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '>',
- '<span unselectable="on">', n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</span></a>",
- "</div>"];
- for(var i = 1, len = cols.length; i < len; i++){
- c = cols[i];
- buf.push('<div class="x-tree-col ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
- '<div class="x-tree-col-text">',(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</div>",
- "</div>");
- }
- buf.push(
- '<div class="x-clear"></div></div>',
- '<ul class="x-tree-node-ct" style="display:none;"></ul>',
- "</li>");
- if(bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()){
- this.wrap = Ext.DomHelper.insertHtml("beforeBegin",
- n.nextSibling.ui.getEl(), buf.join(""));
- }else{
- this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
- }
- this.elNode = this.wrap.childNodes[0];
- this.ctNode = this.wrap.childNodes[1];
- var cs = this.elNode.firstChild.childNodes;
- this.indentNode = cs[0];
- this.ecNode = cs[1];
- this.iconNode = cs[2];
- this.anchor = cs[3];
- this.textNode = cs[3].firstChild;
- }
- });
- //backwards compat
- Ext.tree.ColumnNodeUI = Ext.ux.tree.ColumnNodeUI;
- /**
- * @class Ext.DataView.LabelEditor
- * @extends Ext.Editor
- *
- */
- Ext.DataView.LabelEditor = Ext.extend(Ext.Editor, {
- alignment: "tl-tl",
- hideEl : false,
- cls: "x-small-editor",
- shim: false,
- completeOnEnter: true,
- cancelOnEsc: true,
- labelSelector: 'span.x-editable',
- constructor: function(cfg, field){
- Ext.DataView.LabelEditor.superclass.constructor.call(this,
- field || new Ext.form.TextField({
- allowBlank: false,
- growMin:90,
- growMax:240,
- grow:true,
- selectOnFocus:true
- }), cfg
- );
- },
- init : function(view){
- this.view = view;
- view.on('render', this.initEditor, this);
- this.on('complete', this.onSave, this);
- },
- initEditor : function(){
- this.view.on({
- scope: this,
- containerclick: this.doBlur,
- click: this.doBlur
- });
- this.view.getEl().on('mousedown', this.onMouseDown, this, {delegate: this.labelSelector});
- },
- doBlur: function(){
- if(this.editing){
- this.field.blur();
- }
- },
- onMouseDown : function(e, target){
- if(!e.ctrlKey && !e.shiftKey){
- var item = this.view.findItemFromChild(target);
- e.stopEvent();
- var record = this.view.store.getAt(this.view.indexOf(item));
- this.startEdit(target, record.data[this.dataIndex]);
- this.activeRecord = record;
- }else{
- e.preventDefault();
- }
- },
- onSave : function(ed, value){
- this.activeRecord.set(this.dataIndex, value);
- }
- });
- Ext.DataView.DragSelector = function(cfg){
- cfg = cfg || {};
- var view, proxy, tracker;
- var rs, bodyRegion, dragRegion = new Ext.lib.Region(0,0,0,0);
- var dragSafe = cfg.dragSafe === true;
- this.init = function(dataView){
- view = dataView;
- view.on('render', onRender);
- };
- function fillRegions(){
- rs = [];
- view.all.each(function(el){
- rs[rs.length] = el.getRegion();
- });
- bodyRegion = view.el.getRegion();
- }
- function cancelClick(){
- return false;
- }
- function onBeforeStart(e){
- return !dragSafe || e.target == view.el.dom;
- }
- function onStart(e){
- view.on('containerclick', cancelClick, view, {single:true});
- if(!proxy){
- proxy = view.el.createChild({cls:'x-view-selector'});
- }else{
- if(proxy.dom.parentNode !== view.el.dom){
- view.el.dom.appendChild(proxy.dom);
- }
- proxy.setDisplayed('block');
- }
- fillRegions();
- view.clearSelections();
- }
- function onDrag(e){
- var startXY = tracker.startXY;
- var xy = tracker.getXY();
- var x = Math.min(startXY[0], xy[0]);
- var y = Math.min(startXY[1], xy[1]);
- var w = Math.abs(startXY[0] - xy[0]);
- var h = Math.abs(startXY[1] - xy[1]);
- dragRegion.left = x;
- dragRegion.top = y;
- dragRegion.right = x+w;
- dragRegion.bottom = y+h;
- dragRegion.constrainTo(bodyRegion);
- proxy.setRegion(dragRegion);
- for(var i = 0, len = rs.length; i < len; i++){
- var r = rs[i], sel = dragRegion.intersect(r);
- if(sel && !r.selected){
- r.selected = true;
- view.select(i, true);
- }else if(!sel && r.selected){
- r.selected = false;
- view.deselect(i);
- }
- }
- }
- function onEnd(e){
- if (!Ext.isIE) {
- view.un('containerclick', cancelClick, view);
- }
- if(proxy){
- proxy.setDisplayed(false);
- }
- }
- function onRender(view){
- tracker = new Ext.dd.DragTracker({
- onBeforeStart: onBeforeStart,
- onStart: onStart,
- onDrag: onDrag,
- onEnd: onEnd
- });
- tracker.initEl(view.el);
- }
- };Ext.ns('Ext.ux.form'); /** * @class Ext.ux.form.FileUploadField * @extends Ext.form.TextField * Creates a file upload field. * @xtype fileuploadfield */ Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField, { /** * @cfg {String} buttonText The button text to display on the upload button (defaults to * 'Browse...'). Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text * value will be used instead if available. */ buttonText: 'Browse...', /** * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible * text field (defaults to false). If true, all inherited TextField members will still be available. */ buttonOnly: false, /** * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field * (defaults to 3). Note that this only applies if {@link #buttonOnly} = false. */ buttonOffset: 3, /** * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object. */ // private readOnly: true, /** * @hide * @method autoSize */ autoSize: Ext.emptyFn, // private initComponent: function(){ Ext.ux.form.FileUploadField.superclass.initComponent.call(this); this.addEvents( /** * @event fileselected * Fires when the underlying file input field's value has changed from the user * selecting a new file from the system file selection dialog. * @param {Ext.ux.form.FileUploadField} this * @param {String} value The file value returned by the underlying file input field */ 'fileselected' ); }, // private onRender : function(ct, position){ Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position); this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'}); this.el.addClass('x-form-file-text'); this.el.dom.removeAttribute('name'); this.createFileInput(); var btnCfg = Ext.applyIf(this.buttonCfg || {}, { text: this.buttonText }); this.button = new Ext.Button(Ext.apply(btnCfg, { renderTo: this.wrap, cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '') })); if(this.buttonOnly){ this.el.hide(); this.wrap.setWidth(this.button.getEl().getWidth()); } this.bindListeners(); this.resizeEl = this.positionEl = this.wrap; }, bindListeners: function(){ this.fileInput.on({ scope: this, mouseenter: function() { this.button.addClass(['x-btn-over','x-btn-focus']) }, mouseleave: function(){ this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click']) }, mousedown: function(){ this.button.addClass('x-btn-click') }, mouseup: function(){ this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click']) }, change: function(){ var v = this.fileInput.dom.value; this.setValue(v); this.fireEvent('fileselected', this, v); } }); }, createFileInput : function() { this.fileInput = this.wrap.createChild({ id: this.getFileInputId(), name: this.name||this.getId(), cls: 'x-form-file', tag: 'input', type: 'file', size: 1 }); }, reset : function(){ this.fileInput.remove(); this.createFileInput(); this.bindListeners(); Ext.ux.form.FileUploadField.superclass.reset.call(this); }, // private getFileInputId: function(){ return this.id + '-file'; }, // private onResize : function(w, h){ Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h); this.wrap.setWidth(w); if(!this.buttonOnly){ var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset; this.el.setWidth(w); } }, // private onDestroy: function(){ Ext.ux.form.FileUploadField.superclass.onDestroy.call(this); Ext.destroy(this.fileInput, this.button, this.wrap); }, onDisable: function(){ Ext.ux.form.FileUploadField.superclass.onDisable.call(this); this.doDisable(true); }, onEnable: function(){ Ext.ux.form.FileUploadField.superclass.onEnable.call(this); this.doDisable(false); }, // private doDisable: function(disabled){ this.fileInput.dom.disabled = disabled; this.button.setDisabled(disabled); }, // private preFocus : Ext.emptyFn, // private alignErrorIcon : function(){ this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]); } }); Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField); // backwards compat Ext.form.FileUploadField = Ext.ux.form.FileUploadField; /**
- * @class Ext.ux.GMapPanel
- * @extends Ext.Panel
- * @author Shea Frederick
- */
- Ext.ux.GMapPanel = Ext.extend(Ext.Panel, {
- initComponent : function(){
- var defConfig = {
- plain: true,
- zoomLevel: 3,
- yaw: 180,
- pitch: 0,
- zoom: 0,
- gmapType: 'map',
- border: false
- };
- Ext.applyIf(this,defConfig);
- Ext.ux.GMapPanel.superclass.initComponent.call(this);
- },
- afterRender : function(){
- var wh = this.ownerCt.getSize();
- Ext.applyIf(this, wh);
- Ext.ux.GMapPanel.superclass.afterRender.call(this);
- if (this.gmapType === 'map'){
- this.gmap = new GMap2(this.body.dom);
- }
- if (this.gmapType === 'panorama'){
- this.gmap = new GStreetviewPanorama(this.body.dom);
- }
- if (typeof this.addControl == 'object' && this.gmapType === 'map') {
- this.gmap.addControl(this.addControl);
- }
- if (typeof this.setCenter === 'object') {
- if (typeof this.setCenter.geoCodeAddr === 'string'){
- this.geoCodeLookup(this.setCenter.geoCodeAddr);
- }else{
- if (this.gmapType === 'map'){
- var point = new GLatLng(this.setCenter.lat,this.setCenter.lng);
- this.gmap.setCenter(point, this.zoomLevel);
- }
- if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
- this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);
- }
- }
- if (this.gmapType === 'panorama'){
- this.gmap.setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter.lng), {yaw: this.yaw, pitch: this.pitch, zoom: this.zoom});
- }
- }
- GEvent.bind(this.gmap, 'load', this, function(){
- this.onMapReady();
- });
- },
- onMapReady : function(){
- this.addMarkers(this.markers);
- this.addMapControls();
- this.addOptions();
- },
- onResize : function(w, h){
- if (typeof this.getMap() == 'object') {
- this.gmap.checkResize();
- }
- Ext.ux.GMapPanel.superclass.onResize.call(this, w, h);
- },
- setSize : function(width, height, animate){
- if (typeof this.getMap() == 'object') {
- this.gmap.checkResize();
- }
- Ext.ux.GMapPanel.superclass.setSize.call(this, width, height, animate);
- },
- getMap : function(){
- return this.gmap;
- },
- getCenter : function(){
- return this.getMap().getCenter();
- },
- getCenterLatLng : function(){
- var ll = this.getCenter();
- return {lat: ll.lat(), lng: ll.lng()};
- },
- addMarkers : function(markers) {
- if (Ext.isArray(markers)){
- for (var i = 0; i < markers.length; i++) {
- var mkr_point = new GLatLng(markers[i].lat,markers[i].lng);
- this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter, markers[i].listeners);
- }
- }
- },
- addMarker : function(point, marker, clear, center, listeners){
- Ext.applyIf(marker,G_DEFAULT_ICON);
- if (clear === true){
- this.getMap().clearOverlays();
- }
- if (center === true) {
- this.getMap().setCenter(point, this.zoomLevel);
- }
- var mark = new GMarker(point,marker);
- if (typeof listeners === 'object'){
- for (evt in listeners) {
- GEvent.bind(mark, evt, this, listeners[evt]);
- }
- }
- this.getMap().addOverlay(mark);
- },
- addMapControls : function(){
- if (this.gmapType === 'map') {
- if (Ext.isArray(this.mapControls)) {
- for(i=0;i<this.mapControls.length;i++){
- this.addMapControl(this.mapControls[i]);
- }
- }else if(typeof this.mapControls === 'string'){
- this.addMapControl(this.mapControls);
- }else if(typeof this.mapControls === 'object'){
- this.getMap().addControl(this.mapControls);
- }
- }
- },
- addMapControl : function(mc){
- var mcf = window[mc];
- if (typeof mcf === 'function') {
- this.getMap().addControl(new mcf());
- }
- },
- addOptions : function(){
- if (Ext.isArray(this.mapConfOpts)) {
- var mc;
- for(i=0;i<this.mapConfOpts.length;i++){
- this.addOption(this.mapConfOpts[i]);
- }
- }else if(typeof this.mapConfOpts === 'string'){
- this.addOption(this.mapConfOpts);
- }
- },
- addOption : function(mc){
- var mcf = this.getMap()[mc];
- if (typeof mcf === 'function') {
- this.getMap()[mc]();
- }
- },
- geoCodeLookup : function(addr) {
- this.geocoder = new GClientGeocoder();
- this.geocoder.getLocations(addr, this.addAddressToMap.createDelegate(this));
- },
- addAddressToMap : function(response) {
- if (!response || response.Status.code != 200) {
- Ext.MessageBox.alert('Error', 'Code '+response.Status.code+' Error Returned');
- }else{
- place = response.Placemark[0];
- addressinfo = place.AddressDetails;
- accuracy = addressinfo.Accuracy;
- if (accuracy === 0) {
- Ext.MessageBox.alert('Unable to Locate Address', 'Unable to Locate the Address you provided');
- }else{
- if (accuracy < 7) {
- Ext.MessageBox.alert('Address Accuracy', 'The address provided has a low accuracy.<br><br>Level '+accuracy+' Accuracy (8 = Exact Match, 1 = Vague Match)');
- }else{
- point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
- if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
- this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear,true, this.setCenter.listeners);
- }
- }
- }
- }
- }
- });
- Ext.reg('gmappanel', Ext.ux.GMapPanel); Ext.namespace('Ext.ux.grid');
- /**
- * @class Ext.ux.grid.GridFilters
- * @extends Ext.util.Observable
- * <p>GridFilter is a plugin (<code>ptype='gridfilters'</code>) for grids that
- * allow for a slightly more robust representation of filtering than what is
- * provided by the default store.</p>
- * <p>Filtering is adjusted by the user using the grid's column header menu
- * (this menu can be disabled through configuration). Through this menu users
- * can configure, enable, and disable filters for each column.</p>
- * <p><b><u>Features:</u></b></p>
- * <div class="mdetail-params"><ul>
- * <li><b>Filtering implementations</b> :
- * <div class="sub-desc">
- * Default filtering for Strings, Numeric Ranges, Date Ranges, Lists (which can
- * be backed by a Ext.data.Store), and Boolean. Additional custom filter types
- * and menus are easily created by extending Ext.ux.grid.filter.Filter.
- * </div></li>
- * <li><b>Graphical indicators</b> :
- * <div class="sub-desc">
- * Columns that are filtered have {@link #filterCls a configurable css class}
- * applied to the column headers.
- * </div></li>
- * <li><b>Paging</b> :
- * <div class="sub-desc">
- * If specified as a plugin to the grid's configured PagingToolbar, the current page
- * will be reset to page 1 whenever you update the filters.
- * </div></li>
- * <li><b>Automatic Reconfiguration</b> :
- * <div class="sub-desc">
- * Filters automatically reconfigure when the grid 'reconfigure' event fires.
- * </div></li>
- * <li><b>Stateful</b> :
- * Filter information will be persisted across page loads by specifying a
- * <code>stateId</code> in the Grid configuration.
- * <div class="sub-desc">
- * The filter collection binds to the
- * <code>{@link Ext.grid.GridPanel#beforestaterestore beforestaterestore}</code>
- * and <code>{@link Ext.grid.GridPanel#beforestatesave beforestatesave}</code>
- * events in order to be stateful.
- * </div></li>
- * <li><b>Grid Changes</b> :
- * <div class="sub-desc"><ul>
- * <li>A <code>filters</code> <i>property</i> is added to the grid pointing to
- * this plugin.</li>
- * <li>A <code>filterupdate</code> <i>event</i> is added to the grid and is
- * fired upon onStateChange completion.</li>
- * </ul></div></li>
- * <li><b>Server side code examples</b> :
- * <div class="sub-desc"><ul>
- * <li><a href="http://www.vinylfox.com/extjs/grid-filter-php-backend-code.php">PHP</a> - (Thanks VinylFox)</li>
- * <li><a href="http://extjs.com/forum/showthread.php?p=77326#post77326">Ruby on Rails</a> - (Thanks Zyclops)</li>
- * <li><a href="http://extjs.com/forum/showthread.php?p=176596#post176596">Ruby on Rails</a> - (Thanks Rotomaul)</li>
- * <li><a href="http://www.debatablybeta.com/posts/using-extjss-grid-filtering-with-django/">Python</a> - (Thanks Matt)</li>
- * <li><a href="http://mcantrell.wordpress.com/2008/08/22/extjs-grids-and-grails/">Grails</a> - (Thanks Mike)</li>
- * </ul></div></li>
- * </ul></div>
- * <p><b><u>Example usage:</u></b></p>
- * <pre><code>
- var store = new Ext.data.GroupingStore({
- ...
- });
- var filters = new Ext.ux.grid.GridFilters({
- autoReload: false, //don't reload automatically
- local: true, //only filter locally
- // filters may be configured through the plugin,
- // or in the column definition within the column model configuration
- filters: [{
- type: 'numeric',
- dataIndex: 'id'
- }, {
- type: 'string',
- dataIndex: 'name'
- }, {
- type: 'numeric',
- dataIndex: 'price'
- }, {
- type: 'date',
- dataIndex: 'dateAdded'
- }, {
- type: 'list',
- dataIndex: 'size',
- options: ['extra small', 'small', 'medium', 'large', 'extra large'],
- phpMode: true
- }, {
- type: 'boolean',
- dataIndex: 'visible'
- }]
- });
- var cm = new Ext.grid.ColumnModel([{
- ...
- }]);
- var grid = new Ext.grid.GridPanel({
- ds: store,
- cm: cm,
- view: new Ext.grid.GroupingView(),
- plugins: [filters],
- height: 400,
- width: 700,
- bbar: new Ext.PagingToolbar({
- store: store,
- pageSize: 15,
- plugins: [filters] //reset page to page 1 if filters change
- })
- });
- store.load({params: {start: 0, limit: 15}});
- // a filters property is added to the grid
- grid.filters
- * </code></pre>
- */
- Ext.ux.grid.GridFilters = Ext.extend(Ext.util.Observable, {
- /**
- * @cfg {Boolean} autoReload
- * Defaults to true, reloading the datasource when a filter change happens.
- * Set this to false to prevent the datastore from being reloaded if there
- * are changes to the filters. See <code>{@link updateBuffer}</code>.
- */
- autoReload : true,
- /**
- * @cfg {Boolean} encode
- * Specify true for {@link #buildQuery} to use Ext.util.JSON.encode to
- * encode the filter query parameter sent with a remote request.
- * Defaults to false.
- */
- /**
- * @cfg {Array} filters
- * An Array of filters config objects. Refer to each filter type class for
- * configuration details specific to each filter type. Filters for Strings,
- * Numeric Ranges, Date Ranges, Lists, and Boolean are the standard filters
- * available.
- */
- /**
- * @cfg {String} filterCls
- * The css class to be applied to column headers with active filters.
- * Defaults to <tt>'ux-filterd-column'</tt>.
- */
- filterCls : 'ux-filtered-column',
- /**
- * @cfg {Boolean} local
- * <tt>true</tt> to use Ext.data.Store filter functions (local filtering)
- * instead of the default (<tt>false</tt>) server side filtering.
- */
- local : false,
- /**
- * @cfg {String} menuFilterText
- * defaults to <tt>'Filters'</tt>.
- */
- menuFilterText : 'Filters',
- /**
- * @cfg {String} paramPrefix
- * The url parameter prefix for the filters.
- * Defaults to <tt>'filter'</tt>.
- */
- paramPrefix : 'filter',
- /**
- * @cfg {Boolean} showMenu
- * Defaults to true, including a filter submenu in the default header menu.
- */
- showMenu : true,
- /**
- * @cfg {String} stateId
- * Name of the value to be used to store state information.
- */
- stateId : undefined,
- /**
- * @cfg {Integer} updateBuffer
- * Number of milliseconds to defer store updates since the last filter change.
- */
- updateBuffer : 500,
- /** @private */
- constructor : function (config) {
- config = config || {};
- this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this);
- this.filters = new Ext.util.MixedCollection();
- this.filters.getKey = function (o) {
- return o ? o.dataIndex : null;
- };
- this.addFilters(config.filters);
- delete config.filters;
- Ext.apply(this, config);
- },
- /** @private */
- init : function (grid) {
- if (grid instanceof Ext.grid.GridPanel) {
- this.grid = grid;
- this.bindStore(this.grid.getStore(), true);
- // assumes no filters were passed in the constructor, so try and use ones from the colModel
- if(this.filters.getCount() == 0){
- this.addFilters(this.grid.getColumnModel());
- }
- this.grid.filters = this;
- this.grid.addEvents({'filterupdate': true});
- grid.on({
- scope: this,
- beforestaterestore: this.applyState,
- beforestatesave: this.saveState,
- beforedestroy: this.destroy,
- reconfigure: this.onReconfigure
- });
- if (grid.rendered){
- this.onRender();
- } else {
- grid.on({
- scope: this,
- single: true,
- render: this.onRender
- });
- }
- } else if (grid instanceof Ext.PagingToolbar) {
- this.toolbar = grid;
- }
- },
- /**
- * @private
- * Handler for the grid's beforestaterestore event (fires before the state of the
- * grid is restored).
- * @param {Object} grid The grid object
- * @param {Object} state The hash of state values returned from the StateProvider.
- */
- applyState : function (grid, state) {
- var key, filter;
- this.applyingState = true;
- this.clearFilters();
- if (state.filters) {
- for (key in state.filters) {
- filter = this.filters.get(key);
- if (filter) {
- filter.setValue(state.filters[key]);
- filter.setActive(true);
- }
- }
- }
- this.deferredUpdate.cancel();
- if (this.local) {
- this.reload();
- }
- delete this.applyingState;
- },
- /**
- * Saves the state of all active filters
- * @param {Object} grid
- * @param {Object} state
- * @return {Boolean}
- */
- saveState : function (grid, state) {
- var filters = {};
- this.filters.each(function (filter) {
- if (filter.active) {
- filters[filter.dataIndex] = filter.getValue();
- }
- });
- return (state.filters = filters);
- },
- /**
- * @private
- * Handler called when the grid is rendered
- */
- onRender : function () {
- this.grid.getView().on('refresh', this.onRefresh, this);
- this.createMenu();
- },
- /**
- * @private
- * Handler called by the grid 'beforedestroy' event
- */
- destroy : function () {
- this.removeAll();
- this.purgeListeners();
- if(this.filterMenu){
- Ext.menu.MenuMgr.unregister(this.filterMenu);
- this.filterMenu.destroy();
- this.filterMenu = this.menu.menu = null;
- }
- },
- /**
- * Remove all filters, permanently destroying them.
- */
- removeAll : function () {
- if(this.filters){
- Ext.destroy.apply(Ext, this.filters.items);
- // remove all items from the collection
- this.filters.clear();
- }
- },
- /**
- * Changes the data store bound to this view and refreshes it.
- * @param {Store} store The store to bind to this view
- */
- bindStore : function(store, initial){
- if(!initial && this.store){
- if (this.local) {
- store.un('load', this.onLoad, this);
- } else {
- store.un('beforeload', this.onBeforeLoad, this);
- }
- }
- if(store){
- if (this.local) {
- store.on('load', this.onLoad, this);
- } else {
- store.on('beforeload', this.onBeforeLoad, this);
- }
- }
- this.store = store;
- },
- /**
- * @private
- * Handler called when the grid reconfigure event fires
- */
- onReconfigure : function () {
- this.bindStore(this.grid.getStore());
- this.store.clearFilter();
- this.removeAll();
- this.addFilters(this.grid.getColumnModel());
- this.updateColumnHeadings();
- },
- createMenu : function () {
- var view = this.grid.getView(),
- hmenu = view.hmenu;
- if (this.showMenu && hmenu) {
- this.sep = hmenu.addSeparator();
- this.filterMenu = new Ext.menu.Menu({
- id: this.grid.id + '-filters-menu'
- });
- this.menu = hmenu.add({
- checked: false,
- itemId: 'filters',
- text: this.menuFilterText,
- menu: this.filterMenu
- });
- this.menu.on({
- scope: this,
- checkchange: this.onCheckChange,
- beforecheckchange: this.onBeforeCheck
- });
- hmenu.on('beforeshow', this.onMenu, this);
- }
- this.updateColumnHeadings();
- },
- /**
- * @private
- * Get the filter menu from the filters MixedCollection based on the clicked header
- */
- getMenuFilter : function () {
- var view = this.grid.getView();
- if (!view || view.hdCtxIndex === undefined) {
- return null;
- }
- return this.filters.get(
- view.cm.config[view.hdCtxIndex].dataIndex
- );
- },
- /**
- * @private
- * Handler called by the grid's hmenu beforeshow event
- */
- onMenu : function (filterMenu) {
- var filter = this.getMenuFilter();
- if (filter) {
- /*
- TODO: lazy rendering
- if (!filter.menu) {
- filter.menu = filter.createMenu();
- }
- */
- this.menu.menu = filter.menu;
- this.menu.setChecked(filter.active, false);
- // disable the menu if filter.disabled explicitly set to true
- this.menu.setDisabled(filter.disabled === true);
- }
- this.menu.setVisible(filter !== undefined);
- this.sep.setVisible(filter !== undefined);
- },
- /** @private */
- onCheckChange : function (item, value) {
- this.getMenuFilter().setActive(value);
- },
- /** @private */
- onBeforeCheck : function (check, value) {
- return !value || this.getMenuFilter().isActivatable();
- },
- /**
- * @private
- * Handler for all events on filters.
- * @param {String} event Event name
- * @param {Object} filter Standard signature of the event before the event is fired
- */
- onStateChange : function (event, filter) {
- if (event === 'serialize') {
- return;
- }
- if (filter == this.getMenuFilter()) {
- this.menu.setChecked(filter.active, false);
- }
- if ((this.autoReload || this.local) && !this.applyingState) {
- this.deferredUpdate.delay(this.updateBuffer);
- }
- this.updateColumnHeadings();
- if (!this.applyingState) {
- this.grid.saveState();
- }
- this.grid.fireEvent('filterupdate', this, filter);
- },
- /**
- * @private
- * Handler for store's beforeload event when configured for remote filtering
- * @param {Object} store
- * @param {Object} options
- */
- onBeforeLoad : function (store, options) {
- options.params = options.params || {};
- this.cleanParams(options.params);
- var params = this.buildQuery(this.getFilterData());
- Ext.apply(options.params, params);
- },
- /**
- * @private
- * Handler for store's load event when configured for local filtering
- * @param {Object} store
- * @param {Object} options
- */
- onLoad : function (store, options) {
- store.filterBy(this.getRecordFilter());
- },
- /**
- * @private
- * Handler called when the grid's view is refreshed
- */
- onRefresh : function () {
- this.updateColumnHeadings();
- },
- /**
- * Update the styles for the header row based on the active filters
- */
- updateColumnHeadings : function () {
- var view = this.grid.getView(),
- hds, i, len, filter;
- if (view.mainHd) {
- hds = view.mainHd.select('td').removeClass(this.filterCls);
- for (i = 0, len = view.cm.config.length; i < len; i++) {
- filter = this.getFilter(view.cm.config[i].dataIndex);
- if (filter && filter.active) {
- hds.item(i).addClass(this.filterCls);
- }
- }
- }
- },
- /** @private */
- reload : function () {
- if (this.local) {
- this.grid.store.clearFilter(true);
- this.grid.store.filterBy(this.getRecordFilter());
- } else {
- var start,
- store = this.grid.store;
- this.deferredUpdate.cancel();
- if (this.toolbar) {
- start = store.paramNames.start;
- if (store.lastOptions && store.lastOptions.params && store.lastOptions.params[start]) {
- store.lastOptions.params[start] = 0;
- }
- }
- store.reload();
- }
- },
- /**
- * Method factory that generates a record validator for the filters active at the time
- * of invokation.
- * @private
- */
- getRecordFilter : function () {
- var f = [], len, i;
- this.filters.each(function (filter) {
- if (filter.active) {
- f.push(filter);
- }
- });
- len = f.length;
- return function (record) {
- for (i = 0; i < len; i++) {
- if (!f[i].validateRecord(record)) {
- return false;
- }
- }
- return true;
- };
- },
- /**
- * Adds a filter to the collection and observes it for state change.
- * @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object.
- * @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object.
- */
- addFilter : function (config) {
- var Cls = this.getFilterClass(config.type),
- filter = config.menu ? config : (new Cls(config));
- this.filters.add(filter);
- Ext.util.Observable.capture(filter, this.onStateChange, this);
- return filter;
- },
- /**
- * Adds filters to the collection.
- * @param {Array/Ext.grid.ColumnModel} filters Either an Array of
- * filter configuration objects or an Ext.grid.ColumnModel. The columns
- * of a passed Ext.grid.ColumnModel will be examined for a <code>filter</code>
- * property and, if present, will be used as the filter configuration object.
- */
- addFilters : function (filters) {
- if (filters) {
- var i, len, filter, cm = false, dI;
- if (filters instanceof Ext.grid.ColumnModel) {
- filters = filters.config;
- cm = true;
- }
- for (i = 0, len = filters.length; i < len; i++) {
- filter = false;
- if (cm) {
- dI = filters[i].dataIndex;
- filter = filters[i].filter || filters[i].filterable;
- if (filter){
- filter = (filter === true) ? {} : filter;
- Ext.apply(filter, {dataIndex:dI});
- // filter type is specified in order of preference:
- // filter type specified in config
- // type specified in store's field's type config
- filter.type = filter.type || this.store.fields.get(dI).type;
- }
- } else {
- filter = filters[i];
- }
- // if filter config found add filter for the column
- if (filter) {
- this.addFilter(filter);
- }
- }
- }
- },
- /**
- * Returns a filter for the given dataIndex, if one exists.
- * @param {String} dataIndex The dataIndex of the desired filter object.
- * @return {Ext.ux.grid.filter.Filter}
- */
- getFilter : function (dataIndex) {
- return this.filters.get(dataIndex);
- },
- /**
- * Turns all filters off. This does not clear the configuration information
- * (see {@link #removeAll}).
- */
- clearFilters : function () {
- this.filters.each(function (filter) {
- filter.setActive(false);
- });
- },
- /**
- * Returns an Array of the currently active filters.
- * @return {Array} filters Array of the currently active filters.
- */
- getFilterData : function () {
- var filters = [], i, len;
- this.filters.each(function (f) {
- if (f.active) {
- var d = [].concat(f.serialize());
- for (i = 0, len = d.length; i < len; i++) {
- filters.push({
- field: f.dataIndex,
- data: d[i]
- });
- }
- }
- });
- return filters;
- },
- /**
- * Function to take the active filters data and build it into a query.
- * The format of the query depends on the <code>{@link #encode}</code>
- * configuration:
- * <div class="mdetail-params"><ul>
- *
- * <li><b><tt>false</tt></b> : <i>Default</i>
- * <div class="sub-desc">
- * Flatten into query string of the form (assuming <code>{@link #paramPrefix}='filters'</code>:
- * <pre><code>
- filters[0][field]="someDataIndex"&
- filters[0][data][comparison]="someValue1"&
- filters[0][data][type]="someValue2"&
- filters[0][data][value]="someValue3"&
- * </code></pre>
- * </div></li>
- * <li><b><tt>true</tt></b> :
- * <div class="sub-desc">
- * JSON encode the filter data
- * <pre><code>
- filters[0][field]="someDataIndex"&
- filters[0][data][comparison]="someValue1"&
- filters[0][data][type]="someValue2"&
- filters[0][data][value]="someValue3"&
- * </code></pre>
- * </div></li>
- * </ul></div>
- * Override this method to customize the format of the filter query for remote requests.
- * @param {Array} filters A collection of objects representing active filters and their configuration.
- * Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured
- * to be unique as any one filter may be a composite of more basic filters for the same dataIndex.
- * @return {Object} Query keys and values
- */
- buildQuery : function (filters) {
- var p = {}, i, f, root, dataPrefix, key, tmp,
- len = filters.length;
- if (!this.encode){
- for (i = 0; i < len; i++) {
- f = filters[i];
- root = [this.paramPrefix, '[', i, ']'].join('');
- p[root + '[field]'] = f.field;
- dataPrefix = root + '[data]';
- for (key in f.data) {
- p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
- }
- }
- } else {
- tmp = [];
- for (i = 0; i < len; i++) {
- f = filters[i];
- tmp.push(Ext.apply(
- {},
- {field: f.field},
- f.data
- ));
- }
- // only build if there is active filter
- if (tmp.length > 0){
- p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
- }
- }
- return p;
- },
- /**
- * Removes filter related query parameters from the provided object.
- * @param {Object} p Query parameters that may contain filter related fields.
- */
- cleanParams : function (p) {
- // if encoding just delete the property
- if (this.encode) {
- delete p[this.paramPrefix];
- // otherwise scrub the object of filter data
- } else {
- var regex, key;
- regex = new RegExp('^' + this.paramPrefix + '[[0-9]+]');
- for (key in p) {
- if (regex.test(key)) {
- delete p[key];
- }
- }
- }
- },
- /**
- * Function for locating filter classes, overwrite this with your favorite
- * loader to provide dynamic filter loading.
- * @param {String} type The type of filter to load ('Filter' is automatically
- * appended to the passed type; eg, 'string' becomes 'StringFilter').
- * @return {Class} The Ext.ux.grid.filter.Class
- */
- getFilterClass : function (type) {
- // map the supported Ext.data.Field type values into a supported filter
- switch(type) {
- case 'auto':
- type = 'string';
- break;
- case 'int':
- case 'float':
- type = 'numeric';
- break;
- }
- return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
- }
- });
- // register ptype
- Ext.preg('gridfilters', Ext.ux.grid.GridFilters);
- Ext.namespace('Ext.ux.grid.filter');
- /**
- * @class Ext.ux.grid.filter.Filter
- * @extends Ext.util.Observable
- * Abstract base class for filter implementations.
- */
- Ext.ux.grid.filter.Filter = Ext.extend(Ext.util.Observable, {
- /**
- * @cfg {Boolean} active
- * Indicates the initial status of the filter (defaults to false).
- */
- active : false,
- /**
- * True if this filter is active. Use setActive() to alter after configuration.
- * @type Boolean
- * @property active
- */
- /**
- * @cfg {String} dataIndex
- * The {@link Ext.data.Store} dataIndex of the field this filter represents.
- * The dataIndex does not actually have to exist in the store.
- */
- dataIndex : null,
- /**
- * The filter configuration menu that will be installed into the filter submenu of a column menu.
- * @type Ext.menu.Menu
- * @property
- */
- menu : null,
- /**
- * @cfg {Number} updateBuffer
- * Number of milliseconds to wait after user interaction to fire an update. Only supported
- * by filters: 'list', 'numeric', and 'string'. Defaults to 500.
- */
- updateBuffer : 500,
- constructor : function (config) {
- Ext.apply(this, config);
- this.addEvents(
- /**
- * @event activate
- * Fires when an inactive filter becomes active
- * @param {Ext.ux.grid.filter.Filter} this
- */
- 'activate',
- /**
- * @event deactivate
- * Fires when an active filter becomes inactive
- * @param {Ext.ux.grid.filter.Filter} this
- */
- 'deactivate',
- /**
- * @event serialize
- * Fires after the serialization process. Use this to attach additional parameters to serialization
- * data before it is encoded and sent to the server.
- * @param {Array/Object} data A map or collection of maps representing the current filter configuration.
- * @param {Ext.ux.grid.filter.Filter} filter The filter being serialized.
- */
- 'serialize',
- /**
- * @event update
- * Fires when a filter configuration has changed
- * @param {Ext.ux.grid.filter.Filter} this The filter object.
- */
- 'update'
- );
- Ext.ux.grid.filter.Filter.superclass.constructor.call(this);
- this.menu = new Ext.menu.Menu();
- this.init(config);
- if(config && config.value){
- this.setValue(config.value);
- this.setActive(config.active !== false, true);
- delete config.value;
- }
- },
- /**
- * Destroys this filter by purging any event listeners, and removing any menus.
- */
- destroy : function(){
- if (this.menu){
- this.menu.destroy();
- }
- this.purgeListeners();
- },
- /**
- * Template method to be implemented by all subclasses that is to
- * initialize the filter and install required menu items.
- * Defaults to Ext.emptyFn.
- */
- init : Ext.emptyFn,
- /**
- * Template method to be implemented by all subclasses that is to
- * get and return the value of the filter.
- * Defaults to Ext.emptyFn.
- * @return {Object} The 'serialized' form of this filter
- * @methodOf Ext.ux.grid.filter.Filter
- */
- getValue : Ext.emptyFn,
- /**
- * Template method to be implemented by all subclasses that is to
- * set the value of the filter and fire the 'update' event.
- * Defaults to Ext.emptyFn.
- * @param {Object} data The value to set the filter
- * @methodOf Ext.ux.grid.filter.Filter
- */
- setValue : Ext.emptyFn,
- /**
- * Template method to be implemented by all subclasses that is to
- * return <tt>true</tt> if the filter has enough configuration information to be activated.
- * Defaults to <tt>return true</tt>.
- * @return {Boolean}
- */
- isActivatable : function(){
- return true;
- },
- /**
- * Template method to be implemented by all subclasses that is to
- * get and return serialized filter data for transmission to the server.
- * Defaults to Ext.emptyFn.
- */
- getSerialArgs : Ext.emptyFn,
- /**
- * Template method to be implemented by all subclasses that is to
- * validates the provided Ext.data.Record against the filters configuration.
- * Defaults to <tt>return true</tt>.
- * @param {Ext.data.Record} record The record to validate
- * @return {Boolean} true if the record is valid within the bounds
- * of the filter, false otherwise.
- */
- validateRecord : function(){
- return true;
- },
- /**
- * Returns the serialized filter data for transmission to the server
- * and fires the 'serialize' event.
- * @return {Object/Array} An object or collection of objects containing
- * key value pairs representing the current configuration of the filter.
- * @methodOf Ext.ux.grid.filter.Filter
- */
- serialize : function(){
- var args = this.getSerialArgs();
- this.fireEvent('serialize', args, this);
- return args;
- },
- /** @private */
- fireUpdate : function(){
- if (this.active) {
- this.fireEvent('update', this);
- }
- this.setActive(this.isActivatable());
- },
- /**
- * Sets the status of the filter and fires the appropriate events.
- * @param {Boolean} active The new filter state.
- * @param {Boolean} suppressEvent True to prevent events from being fired.
- * @methodOf Ext.ux.grid.filter.Filter
- */
- setActive : function(active, suppressEvent){
- if(this.active != active){
- this.active = active;
- if (suppressEvent !== true) {
- this.fireEvent(active ? 'activate' : 'deactivate', this);
- }
- }
- }
- });/**
- * @class Ext.ux.grid.filter.BooleanFilter
- * @extends Ext.ux.grid.filter.Filter
- * Boolean filters use unique radio group IDs (so you can have more than one!)
- * <p><b><u>Example Usage:</u></b></p>
- * <pre><code>
- var filters = new Ext.ux.grid.GridFilters({
- ...
- filters: [{
- // required configs
- type: 'boolean',
- dataIndex: 'visible'
- // optional configs
- defaultValue: null, // leave unselected (false selected by default)
- yesText: 'Yes', // default
- noText: 'No' // default
- }]
- });
- * </code></pre>
- */
- Ext.ux.grid.filter.BooleanFilter = Ext.extend(Ext.ux.grid.filter.Filter, {
- /**
- * @cfg {Boolean} defaultValue
- * Set this to null if you do not want either option to be checked by default. Defaults to false.
- */
- defaultValue : false,
- /**
- * @cfg {String} yesText
- * Defaults to 'Yes'.
- */
- yesText : 'Yes',
- /**
- * @cfg {String} noText
- * Defaults to 'No'.
- */
- noText : 'No',
- /**
- * @private
- * Template method that is to initialize the filter and install required menu items.
- */
- init : function (config) {
- var gId = Ext.id();
- this.options = [
- new Ext.menu.CheckItem({text: this.yesText, group: gId, checked: this.defaultValue === true}),
- new Ext.menu.CheckItem({text: this.noText, group: gId, checked: this.defaultValue === false})];
- this.menu.add(this.options[0], this.options[1]);
- for(var i=0; i<this.options.length; i++){
- this.options[i].on('click', this.fireUpdate, this);
- this.options[i].on('checkchange', this.fireUpdate, this);
- }
- },
- /**
- * @private
- * Template method that is to get and return the value of the filter.
- * @return {String} The value of this filter
- */
- getValue : function () {
- return this.options[0].checked;
- },
- /**
- * @private
- * Template method that is to set the value of the filter.
- * @param {Object} value The value to set the filter
- */
- setValue : function (value) {
- this.options[value ? 0 : 1].setChecked(true);
- },
- /**
- * @private
- * Template method that is to get and return serialized filter data for
- * transmission to the server.
- * @return {Object/Array} An object or collection of objects containing
- * key value pairs representing the current configuration of the filter.
- */
- getSerialArgs : function () {
- var args = {type: 'boolean', value: this.getValue()};
- return args;
- },
- /**
- * Template method that is to validate the provided Ext.data.Record
- * against the filters configuration.
- * @param {Ext.data.Record} record The record to validate
- * @return {Boolean} true if the record is valid within the bounds
- * of the filter, false otherwise.
- */
- validateRecord : function (record) {
- return record.get(this.dataIndex) == this.getValue();
- }
- });/**
- * @class Ext.ux.grid.filter.DateFilter
- * @extends Ext.ux.grid.filter.Filter
- * Filter by a configurable Ext.menu.DateMenu
- * <p><b><u>Example Usage:</u></b></p>
- * <pre><code>
- var filters = new Ext.ux.grid.GridFilters({
- ...
- filters: [{
- // required configs
- type: 'date',
- dataIndex: 'dateAdded',
- // optional configs
- dateFormat: 'm/d/Y', // default
- beforeText: 'Before', // default
- afterText: 'After', // default
- onText: 'On', // default
- pickerOpts: {
- // any DateMenu configs
- },
- active: true // default is false
- }]
- });
- * </code></pre>
- */
- Ext.ux.grid.filter.DateFilter = Ext.extend(Ext.ux.grid.filter.Filter, {
- /**
- * @cfg {String} afterText
- * Defaults to 'After'.
- */
- afterText : 'After',
- /**
- * @cfg {String} beforeText
- * Defaults to 'Before'.
- */
- beforeText : 'Before',
- /**
- * @cfg {Object} compareMap
- * Map for assigning the comparison values used in serialization.
- */
- compareMap : {
- before: 'lt',
- after: 'gt',
- on: 'eq'
- },
- /**
- * @cfg {String} dateFormat
- * The date format to return when using getValue.
- * Defaults to 'm/d/Y'.
- */
- dateFormat : 'm/d/Y',
- /**
- * @cfg {Date} maxDate
- * Allowable date as passed to the Ext.DatePicker
- * Defaults to undefined.
- */
- /**
- * @cfg {Date} minDate
- * Allowable date as passed to the Ext.DatePicker
- * Defaults to undefined.
- */
- /**
- * @cfg {Array} menuItems
- * The items to be shown in this menu
- * Defaults to:<pre>
- * menuItems : ['before', 'after', '-', 'on'],
- * </pre>
- */
- menuItems : ['before', 'after', '-', 'on'],
- /**
- * @cfg {Object} menuItemCfgs
- * Default configuration options for each menu item
- */
- menuItemCfgs : {
- selectOnFocus: true,
- width: 125
- },
- /**
- * @cfg {String} onText
- * Defaults to 'On'.
- */
- onText : 'On',
- /**
- * @cfg {Object} pickerOpts
- * Configuration options for the date picker associated with each field.
- */
- pickerOpts : {},
- /**
- * @private
- * Template method that is to initialize the filter and install required menu items.
- */
- init : function (config) {
- var menuCfg, i, len, item, cfg, Cls;
- menuCfg = Ext.apply(this.pickerOpts, {
- minDate: this.minDate,
- maxDate: this.maxDate,
- format: this.dateFormat,
- listeners: {
- scope: this,
- select: this.onMenuSelect
- }
- });
- this.fields = {};
- for (i = 0, len = this.menuItems.length; i < len; i++) {
- item = this.menuItems[i];
- if (item !== '-') {
- cfg = {
- itemId: 'range-' + item,
- text: this[item + 'Text'],
- menu: new Ext.menu.DateMenu(
- Ext.apply(menuCfg, {
- itemId: item
- })
- ),
- listeners: {
- scope: this,
- checkchange: this.onCheckChange
- }
- };
- Cls = Ext.menu.CheckItem;
- item = this.fields[item] = new Cls(cfg);
- }
- //this.add(item);
- this.menu.add(item);
- }
- },
- onCheckChange : function () {
- this.setActive(this.isActivatable());
- this.fireEvent('update', this);
- },
- /**
- * @private
- * Handler method called when there is a keyup event on an input
- * item of this menu.
- */
- onInputKeyUp : function (field, e) {
- var k = e.getKey();
- if (k == e.RETURN && field.isValid()) {
- e.stopEvent();
- this.menu.hide(true);
- return;
- }
- },
- /**
- * Handler for when the menu for a field fires the 'select' event
- * @param {Object} date
- * @param {Object} menuItem
- * @param {Object} value
- * @param {Object} picker
- */
- onMenuSelect : function (menuItem, value, picker) {
- var fields = this.fields,
- field = this.fields[menuItem.itemId];
- field.setChecked(true);
- if (field == fields.on) {
- fields.before.setChecked(false, true);
- fields.after.setChecked(false, true);
- } else {
- fields.on.setChecked(false, true);
- if (field == fields.after && fields.before.menu.picker.value < value) {
- fields.before.setChecked(false, true);
- } else if (field == fields.before && fields.after.menu.picker.value > value) {
- fields.after.setChecked(false, true);
- }
- }
- this.fireEvent('update', this);
- },
- /**
- * @private
- * Template method that is to get and return the value of the filter.
- * @return {String} The value of this filter
- */
- getValue : function () {
- var key, result = {};
- for (key in this.fields) {
- if (this.fields[key].checked) {
- result[key] = this.fields[key].menu.picker.getValue();
- }
- }
- return result;
- },
- /**
- * @private
- * Template method that is to set the value of the filter.
- * @param {Object} value The value to set the filter
- * @param {Boolean} preserve true to preserve the checked status
- * of the other fields. Defaults to false, unchecking the
- * other fields
- */
- setValue : function (value, preserve) {
- var key;
- for (key in this.fields) {
- if(value[key]){
- this.fields[key].menu.picker.setValue(value[key]);
- this.fields[key].setChecked(true);
- } else if (!preserve) {
- this.fields[key].setChecked(false);
- }
- }
- this.fireEvent('update', this);
- },
- /**
- * @private
- * Template method that is to return <tt>true</tt> if the filter
- * has enough configuration information to be activated.
- * @return {Boolean}
- */
- isActivatable : function () {
- var key;
- for (key in this.fields) {
- if (this.fields[key].checked) {
- return true;
- }
- }
- return false;
- },
- /**
- * @private
- * Template method that is to get and return serialized filter data for
- * transmission to the server.
- * @return {Object/Array} An object or collection of objects containing
- * key value pairs representing the current configuration of the filter.
- */
- getSerialArgs : function () {
- var args = [];
- for (var key in this.fields) {
- if(this.fields[key].checked){
- args.push({
- type: 'date',
- comparison: this.compareMap[key],
- value: this.getFieldValue(key).format(this.dateFormat)
- });
- }
- }
- return args;
- },
- /**
- * Get and return the date menu picker value
- * @param {String} item The field identifier ('before', 'after', 'on')
- * @return {Date} Gets the current selected value of the date field
- */
- getFieldValue : function(item){
- return this.fields[item].menu.picker.getValue();
- },
- /**
- * Gets the menu picker associated with the passed field
- * @param {String} item The field identifier ('before', 'after', 'on')
- * @return {Object} The menu picker
- */
- getPicker : function(item){
- return this.fields[item].menu.picker;
- },
- /**
- * Template method that is to validate the provided Ext.data.Record
- * against the filters configuration.
- * @param {Ext.data.Record} record The record to validate
- * @return {Boolean} true if the record is valid within the bounds
- * of the filter, false otherwise.
- */
- validateRecord : function (record) {
- var key,
- pickerValue,
- val = record.get(this.dataIndex);
- if(!Ext.isDate(val)){
- return false;
- }
- val = val.clearTime(true).getTime();
- for (key in this.fields) {
- if (this.fields[key].checked) {
- pickerValue = this.getFieldValue(key).clearTime(true).getTime();
- if (key == 'before' && pickerValue <= val) {
- return false;
- }
- if (key == 'after' && pickerValue >= val) {
- return false;
- }
- if (key == 'on' && pickerValue != val) {
- return false;
- }
- }
- }
- return true;
- }
- });/**
- * @class Ext.ux.grid.filter.ListFilter
- * @extends Ext.ux.grid.filter.Filter
- * <p>List filters are able to be preloaded/backed by an Ext.data.Store to load
- * their options the first time they are shown. ListFilter utilizes the
- * {@link Ext.ux.menu.ListMenu} component.</p>
- * <p>Although not shown here, this class accepts all configuration options
- * for {@link Ext.ux.menu.ListMenu}.</p>
- *
- * <p><b><u>Example Usage:</u></b></p>
- * <pre><code>
- var filters = new Ext.ux.grid.GridFilters({
- ...
- filters: [{
- type: 'list',
- dataIndex: 'size',
- phpMode: true,
- // options will be used as data to implicitly creates an ArrayStore
- options: ['extra small', 'small', 'medium', 'large', 'extra large']
- }]
- });
- * </code></pre>
- *
- */
- Ext.ux.grid.filter.ListFilter = Ext.extend(Ext.ux.grid.filter.Filter, {
- /**
- * @cfg {Array} options
- * <p><code>data</code> to be used to implicitly create a data store
- * to back this list when the data source is <b>local</b>. If the
- * data for the list is remote, use the <code>{@link #store}</code>
- * config instead.</p>
- * <br><p>Each item within the provided array may be in one of the
- * following formats:</p>
- * <div class="mdetail-params"><ul>
- * <li><b>Array</b> :
- * <pre><code>
- options: [
- [11, 'extra small'],
- [18, 'small'],
- [22, 'medium'],
- [35, 'large'],
- [44, 'extra large']
- ]
- * </code></pre>
- * </li>
- * <li><b>Object</b> :
- * <pre><code>
- labelField: 'name', // override default of 'text'
- options: [
- {id: 11, name:'extra small'},
- {id: 18, name:'small'},
- {id: 22, name:'medium'},
- {id: 35, name:'large'},
- {id: 44, name:'extra large'}
- ]
- * </code></pre>
- * </li>
- * <li><b>String</b> :
- * <pre><code>
- * options: ['extra small', 'small', 'medium', 'large', 'extra large']
- * </code></pre>
- * </li>
- */
- /**
- * @cfg {Boolean} phpMode
- * <p>Adjust the format of this filter. Defaults to false.</p>
- * <br><p>When GridFilters <code>@cfg encode = false</code> (default):</p>
- * <pre><code>