+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;
+ delete state.filters;
+ },
+
+ /**
+ * 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(),
+ i, len, filter;
+ if (view.mainHd) {
+ for (i = 0, len = view.cm.config.length; i < len; i++) {
+ filter = this.getFilter(view.cm.config[i].dataIndex);
+ Ext.fly(view.getHeaderCell(i))[filter && filter.active ? 'addClass' : 'removeClass'](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.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>
+// phpMode == false (default):
+filter[0][data][type] list
+filter[0][data][value] value1
+filter[0][data][value] value2
+filter[0][field] prod
+
+// phpMode == true:
+filter[0][data][type] list
+filter[0][data][value] value1, value2
+filter[0][field] prod
+ * </code></pre>
+ * When GridFilters <code>@cfg encode = true</code>:
+ * <pre><code>
+// phpMode == false (default):
+filter : [{"type":"list","value":["small","medium"],"field":"size"}]
+
+// phpMode == true:
+filter : [{"type":"list","value":"small,medium","field":"size"}]
+ * </code></pre>
+ */
+ phpMode : false,
+ /**
+ * @cfg {Ext.data.Store} store
+ * The {@link Ext.data.Store} this list should use as its data source
+ * when the data source is <b>remote</b>. If the data for the list
+ * is local, use the <code>{@link #options}</code> config instead.
+ */
+
+ /**
+ * @private
+ * Template method that is to initialize the filter and install required menu items.
+ * @param {Object} config
+ */
+ init : function (config) {
+ this.dt = new Ext.util.DelayedTask(this.fireUpdate, this);
+
+ // if a menu already existed, do clean up first
+ if (this.menu){
+ this.menu.destroy();
+ }
+ this.menu = new Ext.ux.menu.ListMenu(config);
+ this.menu.on('checkchange', this.onCheckChange, 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.menu.getSelected();
+ },
+ /**
+ * @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.menu.setSelected(value);
+ 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 () {
+ return this.getValue().length > 0;
+ },
+
+ /**
+ * @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: 'list', value: this.phpMode ? this.getValue().join(',') : this.getValue()};
+ return args;
+ },
+
+ /** @private */
+ onCheckChange : function(){
+ this.dt.delay(this.updateBuffer);
+ },
+
+
+ /**
+ * 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 this.getValue().indexOf(record.get(this.dataIndex)) > -1;
+ }
+});/**
+ * @class Ext.ux.grid.filter.NumericFilter
+ * @extends Ext.ux.grid.filter.Filter
+ * Filters using an Ext.ux.menu.RangeMenu.
+ * <p><b><u>Example Usage:</u></b></p>
+ * <pre><code>
+var filters = new Ext.ux.grid.GridFilters({
+ ...
+ filters: [{
+ type: 'numeric',
+ dataIndex: 'price'
+ }]
+});
+ * </code></pre>
+ */
+Ext.ux.grid.filter.NumericFilter = Ext.extend(Ext.ux.grid.filter.Filter, {
+
+ /**
+ * @cfg {Object} fieldCls
+ * The Class to use to construct each field item within this menu
+ * Defaults to:<pre>
+ * fieldCls : Ext.form.NumberField
+ * </pre>
+ */
+ fieldCls : Ext.form.NumberField,
+ /**
+ * @cfg {Object} fieldCfg
+ * The default configuration options for any field item unless superseded
+ * by the <code>{@link #fields}</code> configuration.
+ * Defaults to:<pre>
+ * fieldCfg : {}
+ * </pre>
+ * Example usage:
+ * <pre><code>
+fieldCfg : {
+ width: 150,
+},
+ * </code></pre>
+ */
+ /**
+ * @cfg {Object} fields
+ * The field items may be configured individually
+ * Defaults to <tt>undefined</tt>.
+ * Example usage:
+ * <pre><code>
+fields : {
+ gt: { // override fieldCfg options
+ width: 200,
+ fieldCls: Ext.ux.form.CustomNumberField // to override default {@link #fieldCls}
+ }
+},
+ * </code></pre>
+ */
+ /**
+ * @cfg {Object} iconCls
+ * The iconCls to be applied to each comparator field item.
+ * Defaults to:<pre>
+iconCls : {
+ gt : 'ux-rangemenu-gt',
+ lt : 'ux-rangemenu-lt',
+ eq : 'ux-rangemenu-eq'
+}
+ * </pre>
+ */
+ iconCls : {
+ gt : 'ux-rangemenu-gt',
+ lt : 'ux-rangemenu-lt',
+ eq : 'ux-rangemenu-eq'
+ },
+
+ /**
+ * @cfg {Object} menuItemCfgs
+ * Default configuration options for each menu item
+ * Defaults to:<pre>
+menuItemCfgs : {
+ emptyText: 'Enter Filter Text...',
+ selectOnFocus: true,
+ width: 125
+}
+ * </pre>
+ */
+ menuItemCfgs : {
+ emptyText: 'Enter Filter Text...',
+ selectOnFocus: true,
+ width: 125
+ },
+
+ /**
+ * @cfg {Array} menuItems
+ * The items to be shown in this menu. Items are added to the menu
+ * according to their position within this array. Defaults to:<pre>
+ * menuItems : ['lt','gt','-','eq']
+ * </pre>
+ */
+ menuItems : ['lt', 'gt', '-', 'eq'],
+
+ /**
+ * @private
+ * Template method that is to initialize the filter and install required menu items.
+ */
+ init : function (config) {
+ // if a menu already existed, do clean up first
+ if (this.menu){
+ this.menu.destroy();
+ }
+ this.menu = new Ext.ux.menu.RangeMenu(Ext.apply(config, {
+ // pass along filter configs to the menu
+ fieldCfg : this.fieldCfg || {},
+ fieldCls : this.fieldCls,
+ fields : this.fields || {},
+ iconCls: this.iconCls,
+ menuItemCfgs: this.menuItemCfgs,
+ menuItems: this.menuItems,
+ updateBuffer: this.updateBuffer
+ }));
+ // relay the event fired by the menu
+ this.menu.on('update', 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.menu.getValue();
+ },
+
+ /**
+ * @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.menu.setValue(value);
+ },
+
+ /**
+ * @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 values = this.getValue();
+ for (key in values) {
+ if (values[key] !== undefined) {
+ 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 key,
+ args = [],
+ values = this.menu.getValue();
+ for (key in values) {
+ args.push({
+ type: 'numeric',
+ comparison: key,
+ value: values[key]
+ });
+ }
+ 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) {
+ var val = record.get(this.dataIndex),
+ values = this.getValue();
+ if (values.eq !== undefined && val != values.eq) {
+ return false;
+ }
+ if (values.lt !== undefined && val >= values.lt) {
+ return false;
+ }
+ if (values.gt !== undefined && val <= values.gt) {
+ return false;
+ }
+ return true;
+ }
+});/**
+ * @class Ext.ux.grid.filter.StringFilter
+ * @extends Ext.ux.grid.filter.Filter
+ * Filter by a configurable Ext.form.TextField
+ * <p><b><u>Example Usage:</u></b></p>
+ * <pre><code>
+var filters = new Ext.ux.grid.GridFilters({
+ ...
+ filters: [{
+ // required configs
+ type: 'string',
+ dataIndex: 'name',
+
+ // optional configs
+ value: 'foo',
+ active: true, // default is false
+ iconCls: 'ux-gridfilter-text-icon' // default
+ // any Ext.form.TextField configs accepted
+ }]
+});
+ * </code></pre>
+ */
+Ext.ux.grid.filter.StringFilter = Ext.extend(Ext.ux.grid.filter.Filter, {
+
+ /**
+ * @cfg {String} iconCls
+ * The iconCls to be applied to the menu item.
+ * Defaults to <tt>'ux-gridfilter-text-icon'</tt>.
+ */
+ iconCls : 'ux-gridfilter-text-icon',
+
+ emptyText: 'Enter Filter Text...',
+ selectOnFocus: true,
+ width: 125,
+
+ /**
+ * @private
+ * Template method that is to initialize the filter and install required menu items.
+ */
+ init : function (config) {
+ Ext.applyIf(config, {
+ enableKeyEvents: true,
+ iconCls: this.iconCls,
+ listeners: {
+ scope: this,
+ keyup: this.onInputKeyUp
+ }
+ });
+
+ this.inputItem = new Ext.form.TextField(config);
+ this.menu.add(this.inputItem);
+ this.updateTask = new Ext.util.DelayedTask(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.inputItem.getValue();
+ },
+
+ /**
+ * @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.inputItem.setValue(value);
+ 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 () {
+ return this.inputItem.getValue().length > 0;
+ },
+
+ /**
+ * @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 () {
+ return {type: 'string', value: this.getValue()};
+ },
+
+ /**
+ * 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 val = record.get(this.dataIndex);
+
+ if(typeof val != 'string') {
+ return (this.getValue().length === 0);
+ }
+
+ return val.toLowerCase().indexOf(this.getValue().toLowerCase()) > -1;
+ },
+
+ /**
+ * @private
+ * Handler method called when there is a keyup event on this.inputItem
+ */
+ onInputKeyUp : function (field, e) {
+ var k = e.getKey();
+ if (k == e.RETURN && field.isValid()) {
+ e.stopEvent();
+ this.menu.hide(true);
+ return;
+ }
+ // restart the timer
+ this.updateTask.delay(this.updateBuffer);
+ }
+});
+Ext.namespace('Ext.ux.menu');
+
+/**
+ * @class Ext.ux.menu.ListMenu
+ * @extends Ext.menu.Menu
+ * This is a supporting class for {@link Ext.ux.grid.filter.ListFilter}.
+ * Although not listed as configuration options for this class, this class
+ * also accepts all configuration options from {@link Ext.ux.grid.filter.ListFilter}.
+ */
+Ext.ux.menu.ListMenu = Ext.extend(Ext.menu.Menu, {
+ /**
+ * @cfg {String} labelField
+ * Defaults to 'text'.
+ */
+ labelField : 'text',
+ /**
+ * @cfg {String} paramPrefix
+ * Defaults to 'Loading...'.
+ */
+ loadingText : 'Loading...',
+ /**
+ * @cfg {Boolean} loadOnShow
+ * Defaults to true.
+ */
+ loadOnShow : true,
+ /**
+ * @cfg {Boolean} single
+ * Specify true to group all items in this list into a single-select
+ * radio button group. Defaults to false.
+ */
+ single : false,
+
+ constructor : function (cfg) {
+ this.selected = [];
+ this.addEvents(
+ /**
+ * @event checkchange
+ * Fires when there is a change in checked items from this list
+ * @param {Object} item Ext.menu.CheckItem
+ * @param {Object} checked The checked value that was set
+ */
+ 'checkchange'
+ );
+
+ Ext.ux.menu.ListMenu.superclass.constructor.call(this, cfg = cfg || {});
+
+ if(!cfg.store && cfg.options){
+ var options = [];
+ for(var i=0, len=cfg.options.length; i<len; i++){
+ var value = cfg.options[i];
+ switch(Ext.type(value)){
+ case 'array': options.push(value); break;
+ case 'object': options.push([value.id, value[this.labelField]]); break;
+ case 'string': options.push([value, value]); break;
+ }
+ }
+
+ this.store = new Ext.data.Store({
+ reader: new Ext.data.ArrayReader({id: 0}, ['id', this.labelField]),
+ data: options,
+ listeners: {
+ 'load': this.onLoad,
+ scope: this
+ }
+ });
+ this.loaded = true;
+ } else {
+ this.add({text: this.loadingText, iconCls: 'loading-indicator'});
+ this.store.on('load', this.onLoad, this);
+ }
+ },
+
+ destroy : function () {
+ if (this.store) {
+ this.store.destroy();
+ }
+ Ext.ux.menu.ListMenu.superclass.destroy.call(this);
+ },
+
+ /**
+ * Lists will initially show a 'loading' item while the data is retrieved from the store.
+ * In some cases the loaded data will result in a list that goes off the screen to the
+ * right (as placement calculations were done with the loading item). This adapter will
+ * allow show to be called with no arguments to show with the previous arguments and
+ * thus recalculate the width and potentially hang the menu from the left.
+ */
+ show : function () {
+ var lastArgs = null;
+ return function(){
+ if(arguments.length === 0){
+ Ext.ux.menu.ListMenu.superclass.show.apply(this, lastArgs);
+ } else {
+ lastArgs = arguments;
+ if (this.loadOnShow && !this.loaded) {
+ this.store.load();
+ }
+ Ext.ux.menu.ListMenu.superclass.show.apply(this, arguments);
+ }
+ };
+ }(),
+
+ /** @private */
+ onLoad : function (store, records) {
+ var visible = this.isVisible();
+ this.hide(false);
+
+ this.removeAll(true);
+
+ var gid = this.single ? Ext.id() : null;
+ for(var i=0, len=records.length; i<len; i++){
+ var item = new Ext.menu.CheckItem({
+ text: records[i].get(this.labelField),
+ group: gid,
+ checked: this.selected.indexOf(records[i].id) > -1,
+ hideOnClick: false});
+
+ item.itemId = records[i].id;
+ item.on('checkchange', this.checkChange, this);
+
+ this.add(item);
+ }
+
+ this.loaded = true;
+
+ if (visible) {
+ this.show();
+ }
+ this.fireEvent('load', this, records);
+ },
+
+ /**
+ * Get the selected items.
+ * @return {Array} selected
+ */
+ getSelected : function () {
+ return this.selected;
+ },
+
+ /** @private */
+ setSelected : function (value) {
+ value = this.selected = [].concat(value);
+
+ if (this.loaded) {
+ this.items.each(function(item){
+ item.setChecked(false, true);
+ for (var i = 0, len = value.length; i < len; i++) {
+ if (item.itemId == value[i]) {
+ item.setChecked(true, true);
+ }
+ }
+ }, this);
+ }
+ },
+
+ /**
+ * Handler for the 'checkchange' event from an check item in this menu
+ * @param {Object} item Ext.menu.CheckItem
+ * @param {Object} checked The checked value that was set
+ */
+ checkChange : function (item, checked) {
+ var value = [];
+ this.items.each(function(item){
+ if (item.checked) {
+ value.push(item.itemId);
+ }
+ },this);
+ this.selected = value;
+
+ this.fireEvent('checkchange', item, checked);
+ }
+});Ext.ns('Ext.ux.menu');
+
+/**
+ * @class Ext.ux.menu.RangeMenu
+ * @extends Ext.menu.Menu
+ * Custom implementation of Ext.menu.Menu that has preconfigured
+ * items for gt, lt, eq.
+ * <p><b><u>Example Usage:</u></b></p>
+ * <pre><code>
+
+ * </code></pre>
+ */
+Ext.ux.menu.RangeMenu = Ext.extend(Ext.menu.Menu, {
+
+ constructor : function (config) {
+
+ Ext.ux.menu.RangeMenu.superclass.constructor.call(this, config);
+
+ this.addEvents(
+ /**
+ * @event update
+ * Fires when a filter configuration has changed
+ * @param {Ext.ux.grid.filter.Filter} this The filter object.
+ */
+ 'update'
+ );
+
+ this.updateTask = new Ext.util.DelayedTask(this.fireUpdate, this);
+
+ var i, len, item, cfg, Cls;
+
+ for (i = 0, len = this.menuItems.length; i < len; i++) {
+ item = this.menuItems[i];
+ if (item !== '-') {
+ // defaults
+ cfg = {
+ itemId: 'range-' + item,
+ enableKeyEvents: true,
+ iconCls: this.iconCls[item] || 'no-icon',
+ listeners: {
+ scope: this,
+ keyup: this.onInputKeyUp
+ }
+ };
+ Ext.apply(
+ cfg,
+ // custom configs
+ Ext.applyIf(this.fields[item] || {}, this.fieldCfg[item]),
+ // configurable defaults
+ this.menuItemCfgs
+ );
+ Cls = cfg.fieldCls || this.fieldCls;
+ item = this.fields[item] = new Cls(cfg);
+ }
+ this.add(item);
+ }
+ },
+
+ /**
+ * @private
+ * called by this.updateTask
+ */
+ fireUpdate : function () {
+ this.fireEvent('update', this);
+ },
+
+ /**
+ * Get and return the value of the filter.
+ * @return {String} The value of this filter
+ */
+ getValue : function () {
+ var result = {}, key, field;
+ for (key in this.fields) {
+ field = this.fields[key];
+ if (field.isValid() && String(field.getValue()).length > 0) {
+ result[key] = field.getValue();
+ }
+ }
+ return result;
+ },
+
+ /**
+ * Set the value of this menu and fires the 'update' event.
+ * @param {Object} data The data to assign to this menu
+ */
+ setValue : function (data) {
+ var key;
+ for (key in this.fields) {
+ this.fields[key].setValue(data[key] !== undefined ? data[key] : '');
+ }
+ 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.hide(true);
+ return;
+ }
+
+ if (field == this.fields.eq) {
+ if (this.fields.gt) {
+ this.fields.gt.setValue(null);
+ }
+ if (this.fields.lt) {
+ this.fields.lt.setValue(null);
+ }
+ }
+ else {
+ this.fields.eq.setValue(null);
+ }
+
+ // restart the timer
+ this.updateTask.delay(this.updateBuffer);
+ }
+});
+/*!
+ * Ext JS Library 3.2.0
+ * Copyright(c) 2006-2010 Ext JS, Inc.
+ * licensing@extjs.com
+ * http://www.extjs.com/license
+ */
+Ext.ns('Ext.ux.grid');
+
+/**
+ * @class Ext.ux.grid.GroupSummary
+ * @extends Ext.util.Observable
+ * A GridPanel plugin that enables dynamic column calculations and a dynamically
+ * updated grouped summary row.
+ */
+Ext.ux.grid.GroupSummary = Ext.extend(Ext.util.Observable, {
+ /**
+ * @cfg {Function} summaryRenderer Renderer example:<pre><code>
+summaryRenderer: function(v, params, data){
+ return ((v === 0 || v > 1) ? '(' + v +' Tasks)' : '(1 Task)');
+},
+ * </code></pre>
+ */
+ /**
+ * @cfg {String} summaryType (Optional) The type of
+ * calculation to be used for the column. For options available see
+ * {@link #Calculations}.
+ */
+
+ constructor : function(config){
+ Ext.apply(this, config);
+ Ext.ux.grid.GroupSummary.superclass.constructor.call(this);
+ },
+ init : function(grid){
+ this.grid = grid;
+ var v = this.view = grid.getView();
+ v.doGroupEnd = this.doGroupEnd.createDelegate(this);
+
+ v.afterMethod('onColumnWidthUpdated', this.doWidth, this);
+ v.afterMethod('onAllColumnWidthsUpdated', this.doAllWidths, this);
+ v.afterMethod('onColumnHiddenUpdated', this.doHidden, this);
+ v.afterMethod('onUpdate', this.doUpdate, this);
+ v.afterMethod('onRemove', this.doRemove, this);
+
+ if(!this.rowTpl){
+ this.rowTpl = new Ext.Template(
+ '<div class="x-grid3-summary-row" style="{tstyle}">',
+ '<table class="x-grid3-summary-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
+ '<tbody><tr>{cells}</tr></tbody>',
+ '</table></div>'
+ );
+ this.rowTpl.disableFormats = true;
+ }
+ this.rowTpl.compile();
+
+ if(!this.cellTpl){
+ this.cellTpl = new Ext.Template(
+ '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}">',
+ '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on">{value}</div>',
+ "</td>"
+ );
+ this.cellTpl.disableFormats = true;
+ }
+ this.cellTpl.compile();
+ },
+
+ /**
+ * Toggle the display of the summary row on/off
+ * @param {Boolean} visible <tt>true</tt> to show the summary, <tt>false</tt> to hide the summary.
+ */
+ toggleSummaries : function(visible){
+ var el = this.grid.getGridEl();
+ if(el){
+ if(visible === undefined){
+ visible = el.hasClass('x-grid-hide-summary');
+ }
+ el[visible ? 'removeClass' : 'addClass']('x-grid-hide-summary');
+ }
+ },
+
+ renderSummary : function(o, cs){
+ cs = cs || this.view.getColumnData();
+ var cfg = this.grid.getColumnModel().config,
+ buf = [], c, p = {}, cf, last = cs.length-1;
+ for(var i = 0, len = cs.length; i < len; i++){
+ c = cs[i];
+ cf = cfg[i];
+ p.id = c.id;
+ p.style = c.style;
+ p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
+ if(cf.summaryType || cf.summaryRenderer){
+ p.value = (cf.summaryRenderer || c.renderer)(o.data[c.name], p, o);
+ }else{
+ p.value = '';
+ }
+ if(p.value == undefined || p.value === "") p.value = " ";
+ buf[buf.length] = this.cellTpl.apply(p);
+ }
+
+ return this.rowTpl.apply({
+ tstyle: 'width:'+this.view.getTotalWidth()+';',
+ cells: buf.join('')
+ });
+ },
+
+ /**
+ * @private
+ * @param {Object} rs
+ * @param {Object} cs
+ */
+ calculate : function(rs, cs){
+ var data = {}, r, c, cfg = this.grid.getColumnModel().config, cf;
+ for(var j = 0, jlen = rs.length; j < jlen; j++){
+ r = rs[j];
+ for(var i = 0, len = cs.length; i < len; i++){
+ c = cs[i];
+ cf = cfg[i];
+ if(cf.summaryType){
+ data[c.name] = Ext.ux.grid.GroupSummary.Calculations[cf.summaryType](data[c.name] || 0, r, c.name, data);
+ }
+ }
+ }
+ return data;
+ },
+
+ doGroupEnd : function(buf, g, cs, ds, colCount){
+ var data = this.calculate(g.rs, cs);
+ buf.push('</div>', this.renderSummary({data: data}, cs), '</div>');
+ },
+
+ doWidth : function(col, w, tw){
+ if(!this.isGrouped()){
+ return;
+ }
+ var gs = this.view.getGroups(),
+ len = gs.length,
+ i = 0,
+ s;
+ for(; i < len; ++i){
+ s = gs[i].childNodes[2];
+ s.style.width = tw;
+ s.firstChild.style.width = tw;
+ s.firstChild.rows[0].childNodes[col].style.width = w;
+ }
+ },
+
+ doAllWidths : function(ws, tw){
+ if(!this.isGrouped()){
+ return;
+ }
+ var gs = this.view.getGroups(),
+ len = gs.length,
+ i = 0,
+ j,
+ s,
+ cells,
+ wlen = ws.length;
+
+ for(; i < len; i++){
+ s = gs[i].childNodes[2];
+ s.style.width = tw;
+ s.firstChild.style.width = tw;
+ cells = s.firstChild.rows[0].childNodes;
+ for(j = 0; j < wlen; j++){
+ cells[j].style.width = ws[j];
+ }
+ }
+ },
+
+ doHidden : function(col, hidden, tw){
+ if(!this.isGrouped()){
+ return;
+ }
+ var gs = this.view.getGroups(),
+ len = gs.length,
+ i = 0,
+ s,
+ display = hidden ? 'none' : '';
+ for(; i < len; i++){
+ s = gs[i].childNodes[2];
+ s.style.width = tw;
+ s.firstChild.style.width = tw;
+ s.firstChild.rows[0].childNodes[col].style.display = display;
+ }
+ },
+
+ isGrouped : function(){
+ return !Ext.isEmpty(this.grid.getStore().groupField);
+ },
+
+ // Note: requires that all (or the first) record in the
+ // group share the same group value. Returns false if the group
+ // could not be found.
+ refreshSummary : function(groupValue){
+ return this.refreshSummaryById(this.view.getGroupId(groupValue));
+ },
+
+ getSummaryNode : function(gid){
+ var g = Ext.fly(gid, '_gsummary');
+ if(g){
+ return g.down('.x-grid3-summary-row', true);
+ }
+ return null;
+ },
+
+ refreshSummaryById : function(gid){
+ var g = Ext.getDom(gid);
+ if(!g){
+ return false;
+ }
+ var rs = [];
+ this.grid.getStore().each(function(r){
+ if(r._groupId == gid){
+ rs[rs.length] = r;
+ }
+ });
+ var cs = this.view.getColumnData(),
+ data = this.calculate(rs, cs),
+ markup = this.renderSummary({data: data}, cs),
+ existing = this.getSummaryNode(gid);
+
+ if(existing){
+ g.removeChild(existing);
+ }
+ Ext.DomHelper.append(g, markup);
+ return true;
+ },
+
+ doUpdate : function(ds, record){
+ this.refreshSummaryById(record._groupId);
+ },
+
+ doRemove : function(ds, record, index, isUpdate){
+ if(!isUpdate){
+ this.refreshSummaryById(record._groupId);
+ }
+ },
+
+ /**
+ * Show a message in the summary row.
+ * <pre><code>
+grid.on('afteredit', function(){
+ var groupValue = 'Ext Forms: Field Anchoring';
+ summary.showSummaryMsg(groupValue, 'Updating Summary...');
+});
+ * </code></pre>
+ * @param {String} groupValue
+ * @param {String} msg Text to use as innerHTML for the summary row.
+ */
+ showSummaryMsg : function(groupValue, msg){
+ var gid = this.view.getGroupId(groupValue),
+ node = this.getSummaryNode(gid);
+ if(node){
+ node.innerHTML = '<div class="x-grid3-summary-msg">' + msg + '</div>';
+ }
+ }
+});
+
+//backwards compat
+Ext.grid.GroupSummary = Ext.ux.grid.GroupSummary;
+
+
+/**
+ * Calculation types for summary row:</p><div class="mdetail-params"><ul>
+ * <li><b><tt>sum</tt></b> : <div class="sub-desc"></div></li>
+ * <li><b><tt>count</tt></b> : <div class="sub-desc"></div></li>
+ * <li><b><tt>max</tt></b> : <div class="sub-desc"></div></li>
+ * <li><b><tt>min</tt></b> : <div class="sub-desc"></div></li>
+ * <li><b><tt>average</tt></b> : <div class="sub-desc"></div></li>
+ * </ul></div>
+ * <p>Custom calculations may be implemented. An example of
+ * custom <code>summaryType=totalCost</code>:</p><pre><code>
+// define a custom summary function
+Ext.ux.grid.GroupSummary.Calculations['totalCost'] = function(v, record, field){
+ return v + (record.data.estimate * record.data.rate);
+};
+ * </code></pre>
+ * @property Calculations
+ */
+
+Ext.ux.grid.GroupSummary.Calculations = {
+ 'sum' : function(v, record, field){
+ return v + (record.data[field]||0);
+ },
+
+ 'count' : function(v, record, field, data){
+ return data[field+'count'] ? ++data[field+'count'] : (data[field+'count'] = 1);
+ },
+
+ 'max' : function(v, record, field, data){
+ var v = record.data[field];
+ var max = data[field+'max'] === undefined ? (data[field+'max'] = v) : data[field+'max'];
+ return v > max ? (data[field+'max'] = v) : max;
+ },
+
+ 'min' : function(v, record, field, data){
+ var v = record.data[field];
+ var min = data[field+'min'] === undefined ? (data[field+'min'] = v) : data[field+'min'];
+ return v < min ? (data[field+'min'] = v) : min;
+ },
+
+ 'average' : function(v, record, field, data){
+ var c = data[field+'count'] ? ++data[field+'count'] : (data[field+'count'] = 1);
+ var t = (data[field+'total'] = ((data[field+'total']||0) + (record.data[field]||0)));
+ return t === 0 ? 0 : t / c;
+ }
+};
+Ext.grid.GroupSummary.Calculations = Ext.ux.grid.GroupSummary.Calculations;
+
+/**
+ * @class Ext.ux.grid.HybridSummary
+ * @extends Ext.ux.grid.GroupSummary
+ * Adds capability to specify the summary data for the group via json as illustrated here:
+ * <pre><code>
+{
+ data: [
+ {
+ projectId: 100, project: 'House',
+ taskId: 112, description: 'Paint',
+ estimate: 6, rate: 150,
+ due:'06/24/2007'
+ },
+ ...
+ ],
+
+ summaryData: {
+ 'House': {
+ description: 14, estimate: 9,
+ rate: 99, due: new Date(2009, 6, 29),
+ cost: 999
+ }
+ }
+}
+ * </code></pre>
+ *
+ */
+Ext.ux.grid.HybridSummary = Ext.extend(Ext.ux.grid.GroupSummary, {
+ /**
+ * @private
+ * @param {Object} rs
+ * @param {Object} cs
+ */
+ calculate : function(rs, cs){
+ var gcol = this.view.getGroupField(),
+ gvalue = rs[0].data[gcol],
+ gdata = this.getSummaryData(gvalue);
+ return gdata || Ext.ux.grid.HybridSummary.superclass.calculate.call(this, rs, cs);
+ },
+
+ /**
+ * <pre><code>
+grid.on('afteredit', function(){
+ var groupValue = 'Ext Forms: Field Anchoring';
+ summary.showSummaryMsg(groupValue, 'Updating Summary...');
+ setTimeout(function(){ // simulate server call
+ // HybridSummary class implements updateSummaryData
+ summary.updateSummaryData(groupValue,
+ // create data object based on configured dataIndex
+ {description: 22, estimate: 888, rate: 888, due: new Date(), cost: 8});
+ }, 2000);
+});
+ * </code></pre>
+ * @param {String} groupValue
+ * @param {Object} data data object
+ * @param {Boolean} skipRefresh (Optional) Defaults to false
+ */
+ updateSummaryData : function(groupValue, data, skipRefresh){
+ var json = this.grid.getStore().reader.jsonData;
+ if(!json.summaryData){
+ json.summaryData = {};
+ }
+ json.summaryData[groupValue] = data;
+ if(!skipRefresh){
+ this.refreshSummary(groupValue);
+ }
+ },
+
+ /**
+ * Returns the summaryData for the specified groupValue or null.
+ * @param {String} groupValue
+ * @return {Object} summaryData
+ */
+ getSummaryData : function(groupValue){
+ var reader = this.grid.getStore().reader,
+ json = reader.jsonData,
+ fields = reader.recordType.prototype.fields,
+ v;
+
+ if(json && json.summaryData){
+ v = json.summaryData[groupValue];
+ if(v){
+ return reader.extractValues(v, fields.items, fields.length);
+ }
+ }
+ return null;
+ }
+});
+
+//backwards compat
+Ext.grid.HybridSummary = Ext.ux.grid.HybridSummary;
+Ext.ux.GroupTab = Ext.extend(Ext.Container, {
+ mainItem: 0,
+
+ expanded: true,
+
+ deferredRender: true,
+
+ activeTab: null,
+
+ idDelimiter: '__',
+
+ headerAsText: false,
+
+ frame: false,
+
+ hideBorders: true,
+
+ initComponent: function(config){
+ Ext.apply(this, config);
+ this.frame = false;
+
+ Ext.ux.GroupTab.superclass.initComponent.call(this);
+
+ this.addEvents('activate', 'deactivate', 'changemainitem', 'beforetabchange', 'tabchange');
+
+ this.setLayout(new Ext.layout.CardLayout({
+ deferredRender: this.deferredRender
+ }));
+
+ if (!this.stack) {
+ this.stack = Ext.TabPanel.AccessStack();
+ }
+
+ this.initItems();
+
+ this.on('beforerender', function(){
+ this.groupEl = this.ownerCt.getGroupEl(this);
+ }, this);
+
+ this.on('add', this.onAdd, this, {
+ target: this
+ });
+ this.on('remove', this.onRemove, this, {
+ target: this
+ });
+
+ if (this.mainItem !== undefined) {
+ var item = (typeof this.mainItem == 'object') ? this.mainItem : this.items.get(this.mainItem);
+ delete this.mainItem;
+ this.setMainItem(item);
+ }
+ },
+
+ /**
+ * Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
+ * can return false to cancel the tab change.
+ * @param {String/Panel} tab The id or tab Panel to activate
+ */
+ setActiveTab : function(item){
+ item = this.getComponent(item);
+ if(!item){
+ return false;
+ }
+ if(!this.rendered){
+ this.activeTab = item;
+ return true;
+ }
+ if(this.activeTab != item && this.fireEvent('beforetabchange', this, item, this.activeTab) !== false){
+ if(this.activeTab && this.activeTab != this.mainItem){
+ var oldEl = this.getTabEl(this.activeTab);
+ if(oldEl){
+ Ext.fly(oldEl).removeClass('x-grouptabs-strip-active');
+ }
+ }
+ var el = this.getTabEl(item);
+ Ext.fly(el).addClass('x-grouptabs-strip-active');
+ this.activeTab = item;
+ this.stack.add(item);
+
+ this.layout.setActiveItem(item);
+ if(this.layoutOnTabChange && item.doLayout){
+ item.doLayout();
+ }
+ if(this.scrolling){
+ this.scrollToTab(item, this.animScroll);
+ }
+
+ this.fireEvent('tabchange', this, item);
+ return true;
+ }
+ return false;
+ },
+
+ getTabEl: function(item){
+ if (item == this.mainItem) {
+ return this.groupEl;
+ }
+ return Ext.TabPanel.prototype.getTabEl.call(this, item);
+ },
+
+ onRender: function(ct, position){
+ Ext.ux.GroupTab.superclass.onRender.call(this, ct, position);
+
+ this.strip = Ext.fly(this.groupEl).createChild({
+ tag: 'ul',
+ cls: 'x-grouptabs-sub'
+ });
+
+ this.tooltip = new Ext.ToolTip({
+ target: this.groupEl,
+ delegate: 'a.x-grouptabs-text',
+ trackMouse: true,
+ renderTo: document.body,
+ listeners: {
+ beforeshow: function(tip) {
+ var item = (tip.triggerElement.parentNode === this.mainItem.tabEl)
+ ? this.mainItem
+ : this.findById(tip.triggerElement.parentNode.id.split(this.idDelimiter)[1]);
+
+ if(!item.tabTip) {
+ return false;
+ }
+ tip.body.dom.innerHTML = item.tabTip;
+ },
+ scope: this
+ }
+ });
+
+ if (!this.itemTpl) {
+ var tt = new Ext.Template('<li class="{cls}" id="{id}">', '<a onclick="return false;" class="x-grouptabs-text {iconCls}">{text}</a>', '</li>');
+ tt.disableFormats = true;
+ tt.compile();
+ Ext.ux.GroupTab.prototype.itemTpl = tt;
+ }
+
+ this.items.each(this.initTab, this);
+ },
+
+ afterRender: function(){
+ Ext.ux.GroupTab.superclass.afterRender.call(this);
+
+ if (this.activeTab !== undefined) {
+ var item = (typeof this.activeTab == 'object') ? this.activeTab : this.items.get(this.activeTab);
+ delete this.activeTab;
+ this.setActiveTab(item);
+ }
+ },
+
+ // private
+ initTab: function(item, index){
+ var before = this.strip.dom.childNodes[index];
+ var p = Ext.TabPanel.prototype.getTemplateArgs.call(this, item);
+
+ if (item === this.mainItem) {
+ item.tabEl = this.groupEl;
+ p.cls += ' x-grouptabs-main-item';
+ }
+
+ var el = before ? this.itemTpl.insertBefore(before, p) : this.itemTpl.append(this.strip, p);
+
+ item.tabEl = item.tabEl || el;
+
+ item.on('disable', this.onItemDisabled, this);
+ item.on('enable', this.onItemEnabled, this);
+ item.on('titlechange', this.onItemTitleChanged, this);
+ item.on('iconchange', this.onItemIconChanged, this);
+ item.on('beforeshow', this.onBeforeShowItem, this);
+ },
+
+ setMainItem: function(item){
+ item = this.getComponent(item);
+ if (!item || this.fireEvent('changemainitem', this, item, this.mainItem) === false) {
+ return;
+ }
+
+ this.mainItem = item;
+ },
+
+ getMainItem: function(){
+ return this.mainItem || null;
+ },
+
+ // private
+ onBeforeShowItem: function(item){
+ if (item != this.activeTab) {
+ this.setActiveTab(item);
+ return false;
+ }
+ },
+
+ // private
+ onAdd: function(gt, item, index){
+ if (this.rendered) {
+ this.initTab.call(this, item, index);
+ }
+ },
+
+ // private
+ onRemove: function(tp, item){
+ Ext.destroy(Ext.get(this.getTabEl(item)));
+ this.stack.remove(item);
+ item.un('disable', this.onItemDisabled, this);
+ item.un('enable', this.onItemEnabled, this);
+ item.un('titlechange', this.onItemTitleChanged, this);
+ item.un('iconchange', this.onItemIconChanged, this);
+ item.un('beforeshow', this.onBeforeShowItem, this);
+ if (item == this.activeTab) {
+ var next = this.stack.next();
+ if (next) {
+ this.setActiveTab(next);
+ }
+ else if (this.items.getCount() > 0) {
+ this.setActiveTab(0);
+ }
+ else {
+ this.activeTab = null;
+ }
+ }
+ },
+
+ // private
+ onBeforeAdd: function(item){
+ var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item);
+ if (existing) {
+ this.setActiveTab(item);
+ return false;
+ }
+ Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments);
+ var es = item.elements;
+ item.elements = es ? es.replace(',header', '') : es;
+ item.border = (item.border === true);
+ },
+
+ // private
+ onItemDisabled: Ext.TabPanel.prototype.onItemDisabled,
+ onItemEnabled: Ext.TabPanel.prototype.onItemEnabled,
+
+ // private
+ onItemTitleChanged: function(item){
+ var el = this.getTabEl(item);
+ if (el) {
+ Ext.fly(el).child('a.x-grouptabs-text', true).innerHTML = item.title;
+ }
+ },
+
+ //private
+ onItemIconChanged: function(item, iconCls, oldCls){
+ var el = this.getTabEl(item);
+ if (el) {
+ Ext.fly(el).child('a.x-grouptabs-text').replaceClass(oldCls, iconCls);
+ }
+ },
+
+ beforeDestroy: function(){
+ Ext.TabPanel.prototype.beforeDestroy.call(this);
+ this.tooltip.destroy();
+ }
+});
+
+Ext.reg('grouptab', Ext.ux.GroupTab);
+Ext.ns('Ext.ux');
+
+Ext.ux.GroupTabPanel = Ext.extend(Ext.TabPanel, {
+ tabPosition: 'left',
+
+ alternateColor: false,
+
+ alternateCls: 'x-grouptabs-panel-alt',
+
+ defaultType: 'grouptab',
+
+ deferredRender: false,
+
+ activeGroup : null,
+
+ initComponent: function(){
+ Ext.ux.GroupTabPanel.superclass.initComponent.call(this);
+
+ this.addEvents(
+ 'beforegroupchange',
+ 'groupchange'
+ );
+ this.elements = 'body,header';
+ this.stripTarget = 'header';
+
+ this.tabPosition = this.tabPosition == 'right' ? 'right' : 'left';
+
+ this.addClass('x-grouptabs-panel');
+
+ if (this.tabStyle && this.tabStyle != '') {
+ this.addClass('x-grouptabs-panel-' + this.tabStyle);
+ }
+
+ if (this.alternateColor) {
+ this.addClass(this.alternateCls);
+ }
+
+ this.on('beforeadd', function(gtp, item, index){
+ this.initGroup(item, index);
+ });
+ this.items.each(function(item){
+ item.on('tabchange',function(item){
+ this.fireEvent('tabchange', this, item.activeTab);
+ }, this);
+ },this);
+ },
+
+ initEvents : function() {
+ this.mon(this.strip, 'mousedown', this.onStripMouseDown, this);
+ },
+
+ onRender: function(ct, position){
+ Ext.TabPanel.superclass.onRender.call(this, ct, position);
+ if(this.plain){
+ var pos = this.tabPosition == 'top' ? 'header' : 'footer';
+ this[pos].addClass('x-tab-panel-'+pos+'-plain');
+ }
+
+ var st = this[this.stripTarget];
+
+ this.stripWrap = st.createChild({cls:'x-tab-strip-wrap ', cn:{
+ tag:'ul', cls:'x-grouptabs-strip x-grouptabs-tab-strip-'+this.tabPosition}});
+
+ var beforeEl = (this.tabPosition=='bottom' ? this.stripWrap : null);
+ this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
+
+ this.header.addClass('x-grouptabs-panel-header');
+ this.bwrap.addClass('x-grouptabs-bwrap');
+ this.body.addClass('x-tab-panel-body-'+this.tabPosition + ' x-grouptabs-panel-body');
+
+ if (!this.groupTpl) {
+ var tt = new Ext.Template(
+ '<li class="{cls}" id="{id}">',
+ '<a class="x-grouptabs-expand" onclick="return false;"></a>',
+ '<a class="x-grouptabs-text {iconCls}" href="#" onclick="return false;">',
+ '<span>{text}</span></a>',
+ '</li>'
+ );
+ tt.disableFormats = true;
+ tt.compile();
+ Ext.ux.GroupTabPanel.prototype.groupTpl = tt;
+ }
+ this.items.each(this.initGroup, this);
+ },
+
+ afterRender: function(){
+ Ext.ux.GroupTabPanel.superclass.afterRender.call(this);
+
+ this.tabJoint = Ext.fly(this.body.dom.parentNode).createChild({
+ cls: 'x-tab-joint'
+ });
+
+ this.addClass('x-tab-panel-' + this.tabPosition);
+ this.header.setWidth(this.tabWidth);
+
+ if (this.activeGroup !== undefined) {
+ var group = (typeof this.activeGroup == 'object') ? this.activeGroup : this.items.get(this.activeGroup);
+ delete this.activeGroup;
+ this.setActiveGroup(group);
+ group.setActiveTab(group.getMainItem());
+ }
+ },
+
+ getGroupEl : Ext.TabPanel.prototype.getTabEl,
+
+ // private
+ findTargets: function(e){
+ var item = null,
+ itemEl = e.getTarget('li', this.strip);
+ if (itemEl) {
+ item = this.findById(itemEl.id.split(this.idDelimiter)[1]);
+ if (item.disabled) {
+ return {
+ expand: null,
+ item: null,
+ el: null
+ };
+ }
+ }
+ return {
+ expand: e.getTarget('.x-grouptabs-expand', this.strip),
+ isGroup: !e.getTarget('ul.x-grouptabs-sub', this.strip),
+ item: item,
+ el: itemEl
+ };
+ },
+
+ // private
+ onStripMouseDown: function(e){
+ if (e.button != 0) {
+ return;
+ }
+ e.preventDefault();
+ var t = this.findTargets(e);
+ if (t.expand) {
+ this.toggleGroup(t.el);
+ }
+ else if (t.item) {
+ if(t.isGroup) {
+ t.item.setActiveTab(t.item.getMainItem());
+ }
+ else {
+ t.item.ownerCt.setActiveTab(t.item);
+ }
+ }
+ },
+
+ expandGroup: function(groupEl){
+ if(groupEl.isXType) {
+ groupEl = this.getGroupEl(groupEl);
+ }
+ Ext.fly(groupEl).addClass('x-grouptabs-expanded');
+ this.syncTabJoint();
+ },
+
+ toggleGroup: function(groupEl){
+ if(groupEl.isXType) {
+ groupEl = this.getGroupEl(groupEl);
+ }
+ Ext.fly(groupEl).toggleClass('x-grouptabs-expanded');
+ this.syncTabJoint();
+ },
+
+ collapseGroup: function(groupEl){
+ if(groupEl.isXType) {
+ groupEl = this.getGroupEl(groupEl);
+ }
+ Ext.fly(groupEl).removeClass('x-grouptabs-expanded');
+ this.syncTabJoint();
+ },
+
+ syncTabJoint: function(groupEl){
+ if (!this.tabJoint) {
+ return;
+ }
+
+ groupEl = groupEl || this.getGroupEl(this.activeGroup);
+ if(groupEl) {
+ this.tabJoint.setHeight(Ext.fly(groupEl).getHeight() - 2);
+
+ var y = Ext.isGecko2 ? 0 : 1;
+ if (this.tabPosition == 'left'){
+ this.tabJoint.alignTo(groupEl, 'tl-tr', [-2,y]);
+ }
+ else {
+ this.tabJoint.alignTo(groupEl, 'tr-tl', [1,y]);
+ }
+ }
+ else {
+ this.tabJoint.hide();
+ }
+ },
+
+ getActiveTab : function() {
+ if(!this.activeGroup) return null;
+ return this.activeGroup.getTabEl(this.activeGroup.activeTab) || null;
+ },
+
+ onResize: function(){
+ Ext.ux.GroupTabPanel.superclass.onResize.apply(this, arguments);
+ this.syncTabJoint();
+ },
+
+ createCorner: function(el, pos){
+ return Ext.fly(el).createChild({
+ cls: 'x-grouptabs-corner x-grouptabs-corner-' + pos
+ });
+ },
+
+ initGroup: function(group, index){
+ var before = this.strip.dom.childNodes[index],
+ p = this.getTemplateArgs(group);
+ if (index === 0) {
+ p.cls += ' x-tab-first';
+ }
+ p.cls += ' x-grouptabs-main';
+ p.text = group.getMainItem().title;
+
+ var el = before ? this.groupTpl.insertBefore(before, p) : this.groupTpl.append(this.strip, p),
+ tl = this.createCorner(el, 'top-' + this.tabPosition),
+ bl = this.createCorner(el, 'bottom-' + this.tabPosition);
+
+ group.tabEl = el;
+ if (group.expanded) {
+ this.expandGroup(el);
+ }
+
+ if (Ext.isIE6 || (Ext.isIE && !Ext.isStrict)){
+ bl.setLeft('-10px');
+ bl.setBottom('-5px');
+ tl.setLeft('-10px');
+ tl.setTop('-5px');
+ }
+
+ this.mon(group, {
+ scope: this,
+ changemainitem: this.onGroupChangeMainItem,
+ beforetabchange: this.onGroupBeforeTabChange
+ });
+ },
+
+ setActiveGroup : function(group) {
+ group = this.getComponent(group);
+ if(!group){
+ return false;
+ }
+ if(!this.rendered){
+ this.activeGroup = group;
+ return true;
+ }
+ if(this.activeGroup != group && this.fireEvent('beforegroupchange', this, group, this.activeGroup) !== false){
+ if(this.activeGroup){
+ this.activeGroup.activeTab = null;
+ var oldEl = this.getGroupEl(this.activeGroup);
+ if(oldEl){
+ Ext.fly(oldEl).removeClass('x-grouptabs-strip-active');
+ }
+ }
+
+ var groupEl = this.getGroupEl(group);
+ Ext.fly(groupEl).addClass('x-grouptabs-strip-active');
+
+ this.activeGroup = group;
+ this.stack.add(group);
+
+ this.layout.setActiveItem(group);
+ this.syncTabJoint(groupEl);
+
+ this.fireEvent('groupchange', this, group);
+ return true;
+ }
+ return false;
+ },
+
+ onGroupBeforeTabChange: function(group, newTab, oldTab){
+ if(group !== this.activeGroup || newTab !== oldTab) {
+ this.strip.select('.x-grouptabs-sub > li.x-grouptabs-strip-active', true).removeClass('x-grouptabs-strip-active');
+ }
+ this.expandGroup(this.getGroupEl(group));
+ if(group !== this.activeGroup) {
+ return this.setActiveGroup(group);
+ }
+ },
+
+ getFrameHeight: function(){
+ var h = this.el.getFrameWidth('tb');
+ h += (this.tbar ? this.tbar.getHeight() : 0) +
+ (this.bbar ? this.bbar.getHeight() : 0);
+
+ return h;
+ },
+
+ adjustBodyWidth: function(w){
+ return w - this.tabWidth;
+ }
+});
+
+Ext.reg('grouptabpanel', Ext.ux.GroupTabPanel);
+/*
+ * Note that this control will most likely remain as an example, and not as a core Ext form
+ * control. However, the API will be changing in a future release and so should not yet be
+ * treated as a final, stable API at this time.
+ */
+
+/**
+ * @class Ext.ux.form.ItemSelector
+ * @extends Ext.form.Field
+ * A control that allows selection of between two Ext.ux.form.MultiSelect controls.
+ *
+ * @history
+ * 2008-06-19 bpm Original code contributed by Toby Stuart (with contributions from Robert Williams)
+ *
+ * @constructor
+ * Create a new ItemSelector
+ * @param {Object} config Configuration options
+ * @xtype itemselector
+ */
+Ext.ux.form.ItemSelector = Ext.extend(Ext.form.Field, {
+ hideNavIcons:false,
+ imagePath:"",
+ iconUp:"up2.gif",
+ iconDown:"down2.gif",
+ iconLeft:"left2.gif",
+ iconRight:"right2.gif",
+ iconTop:"top2.gif",
+ iconBottom:"bottom2.gif",
+ drawUpIcon:true,
+ drawDownIcon:true,
+ drawLeftIcon:true,
+ drawRightIcon:true,
+ drawTopIcon:true,
+ drawBotIcon:true,
+ delimiter:',',
+ bodyStyle:null,
+ border:false,
+ defaultAutoCreate:{tag: "div"},
+ /**
+ * @cfg {Array} multiselects An array of {@link Ext.ux.form.MultiSelect} config objects, with at least all required parameters (e.g., store)
+ */
+ multiselects:null,
+
+ initComponent: function(){
+ Ext.ux.form.ItemSelector.superclass.initComponent.call(this);
+ this.addEvents({
+ 'rowdblclick' : true,
+ 'change' : true
+ });
+ },
+
+ onRender: function(ct, position){
+ Ext.ux.form.ItemSelector.superclass.onRender.call(this, ct, position);
+
+ // Internal default configuration for both multiselects
+ var msConfig = [{
+ legend: 'Available',
+ draggable: true,
+ droppable: true,
+ width: 100,
+ height: 100
+ },{
+ legend: 'Selected',
+ droppable: true,
+ draggable: true,
+ width: 100,
+ height: 100
+ }];
+
+ this.fromMultiselect = new Ext.ux.form.MultiSelect(Ext.applyIf(this.multiselects[0], msConfig[0]));
+ this.fromMultiselect.on('dblclick', this.onRowDblClick, this);
+
+ this.toMultiselect = new Ext.ux.form.MultiSelect(Ext.applyIf(this.multiselects[1], msConfig[1]));
+ this.toMultiselect.on('dblclick', this.onRowDblClick, this);
+
+ var p = new Ext.Panel({
+ bodyStyle:this.bodyStyle,
+ border:this.border,
+ layout:"table",
+ layoutConfig:{columns:3}
+ });
+
+ p.add(this.fromMultiselect);
+ var icons = new Ext.Panel({header:false});
+ p.add(icons);
+ p.add(this.toMultiselect);
+ p.render(this.el);
+ icons.el.down('.'+icons.bwrapCls).remove();
+
+ // ICON HELL!!!
+ if (this.imagePath!="" && this.imagePath.charAt(this.imagePath.length-1)!="/")
+ this.imagePath+="/";
+ this.iconUp = this.imagePath + (this.iconUp || 'up2.gif');
+ this.iconDown = this.imagePath + (this.iconDown || 'down2.gif');
+ this.iconLeft = this.imagePath + (this.iconLeft || 'left2.gif');
+ this.iconRight = this.imagePath + (this.iconRight || 'right2.gif');
+ this.iconTop = this.imagePath + (this.iconTop || 'top2.gif');
+ this.iconBottom = this.imagePath + (this.iconBottom || 'bottom2.gif');
+ var el=icons.getEl();
+ this.toTopIcon = el.createChild({tag:'img', src:this.iconTop, style:{cursor:'pointer', margin:'2px'}});
+ el.createChild({tag: 'br'});
+ this.upIcon = el.createChild({tag:'img', src:this.iconUp, style:{cursor:'pointer', margin:'2px'}});
+ el.createChild({tag: 'br'});
+ this.addIcon = el.createChild({tag:'img', src:this.iconRight, style:{cursor:'pointer', margin:'2px'}});
+ el.createChild({tag: 'br'});
+ this.removeIcon = el.createChild({tag:'img', src:this.iconLeft, style:{cursor:'pointer', margin:'2px'}});
+ el.createChild({tag: 'br'});
+ this.downIcon = el.createChild({tag:'img', src:this.iconDown, style:{cursor:'pointer', margin:'2px'}});
+ el.createChild({tag: 'br'});
+ this.toBottomIcon = el.createChild({tag:'img', src:this.iconBottom, style:{cursor:'pointer', margin:'2px'}});
+ this.toTopIcon.on('click', this.toTop, this);
+ this.upIcon.on('click', this.up, this);
+ this.downIcon.on('click', this.down, this);
+ this.toBottomIcon.on('click', this.toBottom, this);
+ this.addIcon.on('click', this.fromTo, this);
+ this.removeIcon.on('click', this.toFrom, this);
+ if (!this.drawUpIcon || this.hideNavIcons) { this.upIcon.dom.style.display='none'; }
+ if (!this.drawDownIcon || this.hideNavIcons) { this.downIcon.dom.style.display='none'; }
+ if (!this.drawLeftIcon || this.hideNavIcons) { this.addIcon.dom.style.display='none'; }
+ if (!this.drawRightIcon || this.hideNavIcons) { this.removeIcon.dom.style.display='none'; }
+ if (!this.drawTopIcon || this.hideNavIcons) { this.toTopIcon.dom.style.display='none'; }
+ if (!this.drawBotIcon || this.hideNavIcons) { this.toBottomIcon.dom.style.display='none'; }
+
+ var tb = p.body.first();
+ this.el.setWidth(p.body.first().getWidth());
+ p.body.removeClass();
+
+ this.hiddenName = this.name;
+ var hiddenTag = {tag: "input", type: "hidden", value: "", name: this.name};
+ this.hiddenField = this.el.createChild(hiddenTag);
+ },
+
+ doLayout: function(){
+ if(this.rendered){
+ this.fromMultiselect.fs.doLayout();
+ this.toMultiselect.fs.doLayout();
+ }
+ },
+
+ afterRender: function(){
+ Ext.ux.form.ItemSelector.superclass.afterRender.call(this);
+
+ this.toStore = this.toMultiselect.store;
+ this.toStore.on('add', this.valueChanged, this);
+ this.toStore.on('remove', this.valueChanged, this);
+ this.toStore.on('load', this.valueChanged, this);
+ this.valueChanged(this.toStore);
+ },
+
+ toTop : function() {
+ var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
+ var records = [];
+ if (selectionsArray.length > 0) {
+ selectionsArray.sort();
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
+ records.push(record);
+ }
+ selectionsArray = [];
+ for (var i=records.length-1; i>-1; i--) {
+ record = records[i];
+ this.toMultiselect.view.store.remove(record);
+ this.toMultiselect.view.store.insert(0, record);
+ selectionsArray.push(((records.length - 1) - i));
+ }
+ }
+ this.toMultiselect.view.refresh();
+ this.toMultiselect.view.select(selectionsArray);
+ },
+
+ toBottom : function() {
+ var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
+ var records = [];
+ if (selectionsArray.length > 0) {
+ selectionsArray.sort();
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
+ records.push(record);
+ }
+ selectionsArray = [];
+ for (var i=0; i<records.length; i++) {
+ record = records[i];
+ this.toMultiselect.view.store.remove(record);
+ this.toMultiselect.view.store.add(record);
+ selectionsArray.push((this.toMultiselect.view.store.getCount()) - (records.length - i));
+ }
+ }
+ this.toMultiselect.view.refresh();
+ this.toMultiselect.view.select(selectionsArray);
+ },
+
+ up : function() {
+ var record = null;
+ var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
+ selectionsArray.sort();
+ var newSelectionsArray = [];
+ if (selectionsArray.length > 0) {
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
+ if ((selectionsArray[i] - 1) >= 0) {
+ this.toMultiselect.view.store.remove(record);
+ this.toMultiselect.view.store.insert(selectionsArray[i] - 1, record);
+ newSelectionsArray.push(selectionsArray[i] - 1);
+ }
+ }
+ this.toMultiselect.view.refresh();
+ this.toMultiselect.view.select(newSelectionsArray);
+ }
+ },
+
+ down : function() {
+ var record = null;
+ var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
+ selectionsArray.sort();
+ selectionsArray.reverse();
+ var newSelectionsArray = [];
+ if (selectionsArray.length > 0) {
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
+ if ((selectionsArray[i] + 1) < this.toMultiselect.view.store.getCount()) {
+ this.toMultiselect.view.store.remove(record);
+ this.toMultiselect.view.store.insert(selectionsArray[i] + 1, record);
+ newSelectionsArray.push(selectionsArray[i] + 1);
+ }
+ }
+ this.toMultiselect.view.refresh();
+ this.toMultiselect.view.select(newSelectionsArray);
+ }
+ },
+
+ fromTo : function() {
+ var selectionsArray = this.fromMultiselect.view.getSelectedIndexes();
+ var records = [];
+ if (selectionsArray.length > 0) {
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.fromMultiselect.view.store.getAt(selectionsArray[i]);
+ records.push(record);
+ }
+ if(!this.allowDup)selectionsArray = [];
+ for (var i=0; i<records.length; i++) {
+ record = records[i];
+ if(this.allowDup){
+ var x=new Ext.data.Record();
+ record.id=x.id;
+ delete x;
+ this.toMultiselect.view.store.add(record);
+ }else{
+ this.fromMultiselect.view.store.remove(record);
+ this.toMultiselect.view.store.add(record);
+ selectionsArray.push((this.toMultiselect.view.store.getCount() - 1));
+ }
+ }
+ }
+ this.toMultiselect.view.refresh();
+ this.fromMultiselect.view.refresh();
+ var si = this.toMultiselect.store.sortInfo;
+ if(si){
+ this.toMultiselect.store.sort(si.field, si.direction);
+ }
+ this.toMultiselect.view.select(selectionsArray);
+ },
+
+ toFrom : function() {
+ var selectionsArray = this.toMultiselect.view.getSelectedIndexes();
+ var records = [];
+ if (selectionsArray.length > 0) {
+ for (var i=0; i<selectionsArray.length; i++) {
+ record = this.toMultiselect.view.store.getAt(selectionsArray[i]);
+ records.push(record);
+ }
+ selectionsArray = [];
+ for (var i=0; i<records.length; i++) {
+ record = records[i];
+ this.toMultiselect.view.store.remove(record);
+ if(!this.allowDup){
+ this.fromMultiselect.view.store.add(record);
+ selectionsArray.push((this.fromMultiselect.view.store.getCount() - 1));
+ }
+ }
+ }
+ this.fromMultiselect.view.refresh();
+ this.toMultiselect.view.refresh();
+ var si = this.fromMultiselect.store.sortInfo;
+ if (si){
+ this.fromMultiselect.store.sort(si.field, si.direction);
+ }
+ this.fromMultiselect.view.select(selectionsArray);
+ },
+
+ valueChanged: function(store) {
+ var record = null;
+ var values = [];
+ for (var i=0; i<store.getCount(); i++) {
+ record = store.getAt(i);
+ values.push(record.get(this.toMultiselect.valueField));
+ }
+ this.hiddenField.dom.value = values.join(this.delimiter);
+ this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
+ },
+
+ getValue : function() {
+ return this.hiddenField.dom.value;
+ },
+
+ onRowDblClick : function(vw, index, node, e) {
+ if (vw == this.toMultiselect.view){
+ this.toFrom();
+ } else if (vw == this.fromMultiselect.view) {
+ this.fromTo();
+ }
+ return this.fireEvent('rowdblclick', vw, index, node, e);
+ },
+
+ reset: function(){
+ range = this.toMultiselect.store.getRange();
+ this.toMultiselect.store.removeAll();
+ this.fromMultiselect.store.add(range);
+ var si = this.fromMultiselect.store.sortInfo;
+ if (si){
+ this.fromMultiselect.store.sort(si.field, si.direction);
+ }
+ this.valueChanged(this.toMultiselect.store);
+ }
+});
+
+Ext.reg('itemselector', Ext.ux.form.ItemSelector);
+
+//backwards compat
+Ext.ux.ItemSelector = Ext.ux.form.ItemSelector;
+Ext.ns('Ext.ux.grid');
+
+Ext.ux.grid.LockingGridView = Ext.extend(Ext.grid.GridView, {
+ lockText : 'Lock',
+ unlockText : 'Unlock',
+ rowBorderWidth : 1,
+ lockedBorderWidth : 1,
+
+ /*
+ * This option ensures that height between the rows is synchronized
+ * between the locked and unlocked sides. This option only needs to be used
+ * when the row heights aren't predictable.
+ */
+ syncHeights: false,
+
+ initTemplates : function(){
+ var ts = this.templates || {};
+
+ if (!ts.master) {
+ ts.master = new Ext.Template(
+ '<div class="x-grid3" hidefocus="true">',
+ '<div class="x-grid3-locked">',
+ '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>',
+ '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>',
+ '</div>',
+ '<div class="x-grid3-viewport x-grid3-unlocked">',
+ '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
+ '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
+ '</div>',
+ '<div class="x-grid3-resize-marker"> </div>',
+ '<div class="x-grid3-resize-proxy"> </div>',
+ '</div>'
+ );
+ }
+
+ this.templates = ts;
+
+ Ext.ux.grid.LockingGridView.superclass.initTemplates.call(this);
+ },
+
+ getEditorParent : function(ed){
+ return this.el.dom;
+ },
+
+ initElements : function(){
+ var E = Ext.Element,
+ el = this.grid.getGridEl().dom.firstChild,
+ cs = el.childNodes;
+
+ this.el = new E(el);
+ this.lockedWrap = new E(cs[0]);
+ this.lockedHd = new E(this.lockedWrap.dom.firstChild);
+ this.lockedInnerHd = this.lockedHd.dom.firstChild;
+ this.lockedScroller = new E(this.lockedWrap.dom.childNodes[1]);
+ this.lockedBody = new E(this.lockedScroller.dom.firstChild);
+ this.mainWrap = new E(cs[1]);
+ this.mainHd = new E(this.mainWrap.dom.firstChild);
+
+ if (this.grid.hideHeaders) {
+ this.lockedHd.setDisplayed(false);
+ this.mainHd.setDisplayed(false);
+ }
+
+ this.innerHd = this.mainHd.dom.firstChild;
+ this.scroller = new E(this.mainWrap.dom.childNodes[1]);
+
+ if(this.forceFit){
+ this.scroller.setStyle('overflow-x', 'hidden');
+ }
+
+ this.mainBody = new E(this.scroller.dom.firstChild);
+ this.focusEl = new E(this.scroller.dom.childNodes[1]);
+ this.resizeMarker = new E(cs[2]);
+ this.resizeProxy = new E(cs[3]);
+
+ this.focusEl.swallowEvent('click', true);
+ },
+
+ getLockedRows : function(){
+ return this.hasRows() ? this.lockedBody.dom.childNodes : [];
+ },
+
+ getLockedRow : function(row){
+ return this.getLockedRows()[row];
+ },
+
+ getCell : function(row, col){
+ var llen = this.cm.getLockedCount();
+ if(col < llen){
+ return this.getLockedRow(row).getElementsByTagName('td')[col];
+ }
+ return Ext.ux.grid.LockingGridView.superclass.getCell.call(this, row, col - llen);
+ },
+
+ getHeaderCell : function(index){
+ var llen = this.cm.getLockedCount();
+ if(index < llen){
+ return this.lockedHd.dom.getElementsByTagName('td')[index];
+ }
+ return Ext.ux.grid.LockingGridView.superclass.getHeaderCell.call(this, index - llen);
+ },
+
+ addRowClass : function(row, cls){
+ var r = this.getLockedRow(row);
+ if(r){
+ this.fly(r).addClass(cls);
+ }
+ Ext.ux.grid.LockingGridView.superclass.addRowClass.call(this, row, cls);
+ },
+
+ removeRowClass : function(row, cls){
+ var r = this.getLockedRow(row);
+ if(r){
+ this.fly(r).removeClass(cls);
+ }
+ Ext.ux.grid.LockingGridView.superclass.removeRowClass.call(this, row, cls);
+ },
+
+ removeRow : function(row) {
+ Ext.removeNode(this.getLockedRow(row));
+ Ext.ux.grid.LockingGridView.superclass.removeRow.call(this, row);
+ },
+
+ removeRows : function(firstRow, lastRow){
+ var bd = this.lockedBody.dom;
+ for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
+ Ext.removeNode(bd.childNodes[firstRow]);
+ }
+ Ext.ux.grid.LockingGridView.superclass.removeRows.call(this, firstRow, lastRow);
+ },
+
+ syncScroll : function(e){
+ var mb = this.scroller.dom;
+ this.lockedScroller.dom.scrollTop = mb.scrollTop;
+ Ext.ux.grid.LockingGridView.superclass.syncScroll.call(this, e);
+ },
+
+ updateSortIcon : function(col, dir){
+ var sc = this.sortClasses,
+ lhds = this.lockedHd.select('td').removeClass(sc),
+ hds = this.mainHd.select('td').removeClass(sc),
+ llen = this.cm.getLockedCount(),
+ cls = sc[dir == 'DESC' ? 1 : 0];
+ if(col < llen){
+ lhds.item(col).addClass(cls);
+ }else{
+ hds.item(col - llen).addClass(cls);
+ }
+ },
+
+ updateAllColumnWidths : function(){
+ var tw = this.getTotalWidth(),
+ clen = this.cm.getColumnCount(),
+ lw = this.getLockedWidth(),
+ llen = this.cm.getLockedCount(),
+ ws = [], len, i;
+ this.updateLockedWidth();
+ for(i = 0; i < clen; i++){
+ ws[i] = this.getColumnWidth(i);
+ var hd = this.getHeaderCell(i);
+ hd.style.width = ws[i];
+ }
+ var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j;
+ for(i = 0, len = ns.length; i < len; i++){
+ row = lns[i];
+ row.style.width = lw;
+ if(row.firstChild){
+ row.firstChild.style.width = lw;
+ trow = row.firstChild.rows[0];
+ for (j = 0; j < llen; j++) {
+ trow.childNodes[j].style.width = ws[j];
+ }
+ }
+ row = ns[i];
+ row.style.width = tw;
+ if(row.firstChild){
+ row.firstChild.style.width = tw;
+ trow = row.firstChild.rows[0];
+ for (j = llen; j < clen; j++) {
+ trow.childNodes[j - llen].style.width = ws[j];
+ }
+ }
+ }
+ this.onAllColumnWidthsUpdated(ws, tw);
+ this.syncHeaderHeight();
+ },
+
+ updateColumnWidth : function(col, width){
+ var w = this.getColumnWidth(col),
+ llen = this.cm.getLockedCount(),
+ ns, rw, c, row;
+ this.updateLockedWidth();
+ if(col < llen){
+ ns = this.getLockedRows();
+ rw = this.getLockedWidth();
+ c = col;
+ }else{
+ ns = this.getRows();
+ rw = this.getTotalWidth();
+ c = col - llen;
+ }
+ var hd = this.getHeaderCell(col);
+ hd.style.width = w;
+ for(var i = 0, len = ns.length; i < len; i++){
+ row = ns[i];
+ row.style.width = rw;
+ if(row.firstChild){
+ row.firstChild.style.width = rw;
+ row.firstChild.rows[0].childNodes[c].style.width = w;
+ }
+ }
+ this.onColumnWidthUpdated(col, w, this.getTotalWidth());
+ this.syncHeaderHeight();
+ },
+
+ updateColumnHidden : function(col, hidden){
+ var llen = this.cm.getLockedCount(),
+ ns, rw, c, row,
+ display = hidden ? 'none' : '';
+ this.updateLockedWidth();
+ if(col < llen){
+ ns = this.getLockedRows();
+ rw = this.getLockedWidth();
+ c = col;
+ }else{
+ ns = this.getRows();
+ rw = this.getTotalWidth();
+ c = col - llen;
+ }
+ var hd = this.getHeaderCell(col);
+ hd.style.display = display;
+ for(var i = 0, len = ns.length; i < len; i++){
+ row = ns[i];
+ row.style.width = rw;
+ if(row.firstChild){
+ row.firstChild.style.width = rw;
+ row.firstChild.rows[0].childNodes[c].style.display = display;
+ }
+ }
+ this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth());
+ delete this.lastViewWidth;
+ this.layout();
+ },
+
+ doRender : function(cs, rs, ds, startRow, colCount, stripe){
+ var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1,
+ tstyle = 'width:'+this.getTotalWidth()+';',
+ lstyle = 'width:'+this.getLockedWidth()+';',
+ buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
+ for(var j = 0, len = rs.length; j < len; j++){
+ r = rs[j]; cb = []; lcb = [];
+ var rowIndex = (j+startRow);
+ 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 ' : '')) +
+ (this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : '');
+ p.attr = p.cellAttr = '';
+ p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
+ p.style = c.style;
+ if(Ext.isEmpty(p.value)){
+ p.value = ' ';
+ }
+ if(this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])){
+ p.css += ' x-grid3-dirty-cell';
+ }
+ if(c.locked){
+ lcb[lcb.length] = ct.apply(p);
+ }else{
+ 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('');
+ rp.tstyle = tstyle;
+ buf[buf.length] = rt.apply(rp);
+ rp.cells = lcb.join('');
+ rp.tstyle = lstyle;
+ lbuf[lbuf.length] = rt.apply(rp);
+ }
+ return [buf.join(''), lbuf.join('')];
+ },
+ processRows : function(startRow, skipStripe){
+ if(!this.ds || this.ds.getCount() < 1){
+ return;
+ }
+ var rows = this.getRows(),
+ lrows = this.getLockedRows(),
+ row, lrow;
+ skipStripe = skipStripe || !this.grid.stripeRows;
+ startRow = startRow || 0;
+ for(var i = 0, len = rows.length; i < len; ++i){
+ row = rows[i];
+ lrow = lrows[i];
+ row.rowIndex = i;
+ lrow.rowIndex = i;
+ if(!skipStripe){
+ row.className = row.className.replace(this.rowClsRe, ' ');
+ lrow.className = lrow.className.replace(this.rowClsRe, ' ');
+ if ((i + 1) % 2 === 0){
+ row.className += ' x-grid3-row-alt';
+ lrow.className += ' x-grid3-row-alt';
+ }
+ }
+ if(this.syncHeights){
+ var el1 = Ext.get(row),
+ el2 = Ext.get(lrow),
+ h1 = el1.getHeight(),
+ h2 = el2.getHeight();
+
+ if(h1 > h2){
+ el2.setHeight(h1);
+ }else if(h2 > h1){
+ el1.setHeight(h2);
+ }
+ }
+ }
+ if(startRow === 0){
+ Ext.fly(rows[0]).addClass(this.firstRowCls);
+ Ext.fly(lrows[0]).addClass(this.firstRowCls);
+ }
+ Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
+ Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls);
+ },
+
+ afterRender : function(){
+ if(!this.ds || !this.cm){
+ return;
+ }
+ var bd = this.renderRows() || [' ', ' '];
+ this.mainBody.dom.innerHTML = bd[0];
+ this.lockedBody.dom.innerHTML = bd[1];
+ this.processRows(0, true);
+ if(this.deferEmptyText !== true){
+ this.applyEmptyText();
+ }
+ this.grid.fireEvent('viewready', this.grid);
+ },
+
+ renderUI : function(){
+ var header = this.renderHeaders();
+ var body = this.templates.body.apply({rows:' '});
+ var html = this.templates.master.apply({
+ body: body,
+ header: header[0],
+ ostyle: 'width:'+this.getOffsetWidth()+';',
+ bstyle: 'width:'+this.getTotalWidth()+';',
+ lockedBody: body,
+ lockedHeader: header[1],
+ lstyle: 'width:'+this.getLockedWidth()+';'
+ });
+ var g = this.grid;
+ g.getGridEl().dom.innerHTML = html;
+ this.initElements();
+ Ext.fly(this.innerHd).on('click', this.handleHdDown, this);
+ Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this);
+ this.mainHd.on({
+ scope: this,
+ mouseover: this.handleHdOver,
+ mouseout: this.handleHdOut,
+ mousemove: this.handleHdMove
+ });
+ this.lockedHd.on({
+ scope: this,
+ mouseover: this.handleHdOver,
+ mouseout: this.handleHdOut,
+ mousemove: this.handleHdMove
+ });
+ this.scroller.on('scroll', this.syncScroll, this);
+ if(g.enableColumnResize !== false){
+ this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
+ this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom));
+ this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom));
+ }
+ if(g.enableColumnMove){
+ this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
+ this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd));
+ this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd));
+ this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
+ }
+ if(g.enableHdMenu !== false){
+ this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'});
+ this.hmenu.add(
+ {itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
+ {itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
+ );
+ if(this.grid.enableColLock !== false){
+ this.hmenu.add('-',
+ {itemId: 'lock', text: this.lockText, cls: 'xg-hmenu-lock'},
+ {itemId: 'unlock', text: this.unlockText, cls: 'xg-hmenu-unlock'}
+ );
+ }
+ if(g.enableColumnHide !== false){
+ this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'});
+ this.colMenu.on({
+ scope: this,
+ beforeshow: this.beforeColMenuShow,
+ itemclick: this.handleHdMenuClick
+ });
+ this.hmenu.add('-', {
+ itemId:'columns',
+ hideOnClick: false,
+ text: this.columnsText,
+ menu: this.colMenu,
+ iconCls: 'x-cols-icon'
+ });
+ }
+ this.hmenu.on('itemclick', this.handleHdMenuClick, this);
+ }
+ if(g.trackMouseOver){
+ this.mainBody.on({
+ scope: this,
+ mouseover: this.onRowOver,
+ mouseout: this.onRowOut
+ });
+ this.lockedBody.on({
+ scope: this,
+ mouseover: this.onRowOver,
+ mouseout: this.onRowOut
+ });
+ }
+
+ if(g.enableDragDrop || g.enableDrag){
+ this.dragZone = new Ext.grid.GridDragZone(g, {
+ ddGroup : g.ddGroup || 'GridDD'
+ });
+ }
+ this.updateHeaderSortState();
+ },
+
+ layout : function(){
+ if(!this.mainBody){
+ return;
+ }
+ var g = this.grid;
+ var c = g.getGridEl();
+ var csize = c.getSize(true);
+ var vw = csize.width;
+ if(!g.hideHeaders && (vw < 20 || csize.height < 20)){
+ return;
+ }
+ this.syncHeaderHeight();
+ if(g.autoHeight){
+ this.scroller.dom.style.overflow = 'visible';
+ this.lockedScroller.dom.style.overflow = 'visible';
+ if(Ext.isWebKit){
+ this.scroller.dom.style.position = 'static';
+ this.lockedScroller.dom.style.position = 'static';
+ }
+ }else{
+ this.el.setSize(csize.width, csize.height);
+ var hdHeight = this.mainHd.getHeight();
+ var vh = csize.height - (hdHeight);
+ }
+ this.updateLockedWidth();
+ if(this.forceFit){
+ if(this.lastViewWidth != vw){
+ this.fitColumns(false, false);
+ this.lastViewWidth = vw;
+ }
+ }else {
+ this.autoExpand();
+ this.syncHeaderScroll();
+ }
+ this.onLayout(vw, vh);
+ },
+
+ getOffsetWidth : function() {
+ return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px';
+ },
+
+ renderHeaders : function(){
+ var cm = this.cm,
+ ts = this.templates,
+ ct = ts.hcell,
+ cb = [], lcb = [],
+ p = {},
+ len = cm.getColumnCount(),
+ last = len - 1;
+ for(var i = 0; i < len; i++){
+ p.id = cm.getColumnId(i);
+ p.value = cm.getColumnHeader(i) || '';
+ p.style = this.getColumnStyle(i, true);
+ p.tooltip = this.getColumnTooltip(i);
+ p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
+ (cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : '');
+ if(cm.config[i].align == 'right'){
+ p.istyle = 'padding-right:16px';
+ } else {
+ delete p.istyle;
+ }
+ if(cm.isLocked(i)){
+ lcb[lcb.length] = ct.apply(p);
+ }else{
+ cb[cb.length] = ct.apply(p);
+ }
+ }
+ return [ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}),
+ ts.header.apply({cells: lcb.join(''), tstyle:'width:'+this.getLockedWidth()+';'})];
+ },
+
+ updateHeaders : function(){
+ var hd = this.renderHeaders();
+ this.innerHd.firstChild.innerHTML = hd[0];
+ this.innerHd.firstChild.style.width = this.getOffsetWidth();
+ this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth();
+ this.lockedInnerHd.firstChild.innerHTML = hd[1];
+ var lw = this.getLockedWidth();
+ this.lockedInnerHd.firstChild.style.width = lw;
+ this.lockedInnerHd.firstChild.firstChild.style.width = lw;
+ },
+
+ getResolvedXY : function(resolved){
+ if(!resolved){
+ return null;
+ }
+ var c = resolved.cell, r = resolved.row;
+ return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()];
+ },
+
+ syncFocusEl : function(row, col, hscroll){
+ Ext.ux.grid.LockingGridView.superclass.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
+ },
+
+ ensureVisible : function(row, col, hscroll){
+ return Ext.ux.grid.LockingGridView.superclass.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
+ },
+
+ insertRows : function(dm, firstRow, lastRow, isUpdate){
+ var last = dm.getCount() - 1;
+ if(!isUpdate && firstRow === 0 && lastRow >= last){
+ this.refresh();
+ }else{
+ if(!isUpdate){
+ this.fireEvent('beforerowsinserted', this, firstRow, lastRow);
+ }
+ var html = this.renderRows(firstRow, lastRow),
+ before = this.getRow(firstRow);
+ if(before){
+ if(firstRow === 0){
+ this.removeRowClass(0, this.firstRowCls);
+ }
+ Ext.DomHelper.insertHtml('beforeBegin', before, html[0]);
+ before = this.getLockedRow(firstRow);
+ Ext.DomHelper.insertHtml('beforeBegin', before, html[1]);
+ }else{
+ this.removeRowClass(last - 1, this.lastRowCls);
+ Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]);
+ Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]);
+ }
+ if(!isUpdate){
+ this.fireEvent('rowsinserted', this, firstRow, lastRow);
+ this.processRows(firstRow);
+ }else if(firstRow === 0 || firstRow >= last){
+ this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls);
+ }
+ }
+ this.syncFocusEl(firstRow);
+ },
+
+ getColumnStyle : function(col, isHeader){
+ var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || '';
+ style += 'width:'+this.getColumnWidth(col)+';';
+ if(this.cm.isHidden(col)){
+ style += 'display:none;';
+ }
+ var align = this.cm.config[col].align;
+ if(align){
+ style += 'text-align:'+align+';';
+ }
+ return style;
+ },
+
+ getLockedWidth : function() {
+ return this.cm.getTotalLockedWidth() + 'px';
+ },
+
+ getTotalWidth : function() {
+ return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px';
+ },
+
+ getColumnData : function(){
+ var cs = [], cm = this.cm, colCount = cm.getColumnCount();
+ for(var i = 0; i < colCount; i++){
+ var name = cm.getDataIndex(i);
+ cs[i] = {
+ name : (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name),
+ renderer : cm.getRenderer(i),
+ id : cm.getColumnId(i),
+ style : this.getColumnStyle(i),
+ locked : cm.isLocked(i)
+ };
+ }
+ return cs;
+ },
+
+ renderBody : function(){
+ var markup = this.renderRows() || [' ', ' '];
+ return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})];
+ },
+
+ refreshRow : function(record){
+ Ext.ux.grid.LockingGridView.superclass.refreshRow.call(this, record);
+ var index = Ext.isNumber(record) ? record : this.ds.indexOf(record);
+ this.getLockedRow(index).rowIndex = index;
+ },
+
+ refresh : function(headersToo){
+ this.fireEvent('beforerefresh', this);
+ this.grid.stopEditing(true);
+ var result = this.renderBody();
+ this.mainBody.update(result[0]).setWidth(this.getTotalWidth());
+ this.lockedBody.update(result[1]).setWidth(this.getLockedWidth());
+ if(headersToo === true){
+ this.updateHeaders();
+ this.updateHeaderSortState();
+ }
+ this.processRows(0, true);
+ this.layout();
+ this.applyEmptyText();
+ this.fireEvent('refresh', this);
+ },
+
+ onDenyColumnLock : function(){
+
+ },
+
+ initData : function(ds, cm){
+ if(this.cm){
+ this.cm.un('columnlockchange', this.onColumnLock, this);
+ }
+ Ext.ux.grid.LockingGridView.superclass.initData.call(this, ds, cm);
+ if(this.cm){
+ this.cm.on('columnlockchange', this.onColumnLock, this);
+ }
+ },
+
+ onColumnLock : function(){
+ this.refresh(true);
+ },
+
+ handleHdMenuClick : function(item){
+ var index = this.hdCtxIndex,
+ cm = this.cm,
+ id = item.getItemId(),
+ llen = cm.getLockedCount();
+ switch(id){
+ case 'lock':
+ if(cm.getColumnCount(true) <= llen + 1){
+ this.onDenyColumnLock();
+ return;
+ }
+ cm.setLocked(index, true);
+ if(llen != index){
+ cm.moveColumn(index, llen);
+ this.grid.fireEvent('columnmove', index, llen);
+ }
+ break;
+ case 'unlock':
+ if(llen - 1 != index){
+ cm.setLocked(index, false, true);
+ cm.moveColumn(index, llen - 1);
+ this.grid.fireEvent('columnmove', index, llen - 1);
+ }else{
+ cm.setLocked(index, false);
+ }
+ break;
+ default:
+ return Ext.ux.grid.LockingGridView.superclass.handleHdMenuClick.call(this, item);
+ }
+ return true;
+ },
+
+ handleHdDown : function(e, t){
+ Ext.ux.grid.LockingGridView.superclass.handleHdDown.call(this, e, t);
+ if(this.grid.enableColLock !== false){
+ if(Ext.fly(t).hasClass('x-grid3-hd-btn')){
+ var hd = this.findHeaderCell(t),
+ index = this.getCellIndex(hd),
+ ms = this.hmenu.items, cm = this.cm;
+ ms.get('lock').setDisabled(cm.isLocked(index));
+ ms.get('unlock').setDisabled(!cm.isLocked(index));
+ }
+ }
+ },
+
+ syncHeaderHeight: function(){
+ this.innerHd.firstChild.firstChild.style.height = 'auto';
+ this.lockedInnerHd.firstChild.firstChild.style.height = 'auto';
+ var hd = this.innerHd.firstChild.firstChild.offsetHeight,
+ lhd = this.lockedInnerHd.firstChild.firstChild.offsetHeight,
+ height = (lhd > hd ? lhd : hd) + 'px';
+ this.innerHd.firstChild.firstChild.style.height = height;
+ this.lockedInnerHd.firstChild.firstChild.style.height = height;
+ },
+
+ updateLockedWidth: function(){
+ var lw = this.cm.getTotalLockedWidth(),
+ tw = this.cm.getTotalWidth() - lw,
+ csize = this.grid.getGridEl().getSize(true),
+ lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth,
+ rp = Ext.isBorderBox ? 0 : this.rowBorderWidth,
+ vw = (csize.width - lw - lp - rp) + 'px',
+ so = this.getScrollOffset();
+ if(!this.grid.autoHeight){
+ var vh = (csize.height - this.mainHd.getHeight()) + 'px';
+ this.lockedScroller.dom.style.height = vh;
+ this.scroller.dom.style.height = vh;
+ }
+ this.lockedWrap.dom.style.width = (lw + rp) + 'px';
+ this.scroller.dom.style.width = vw;
+ this.mainWrap.dom.style.left = (lw + lp + rp) + 'px';
+ if(this.innerHd){
+ this.lockedInnerHd.firstChild.style.width = lw + 'px';
+ this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px';
+ this.innerHd.style.width = vw;
+ this.innerHd.firstChild.style.width = (tw + rp + so) + 'px';
+ this.innerHd.firstChild.firstChild.style.width = tw + 'px';
+ }
+ if(this.mainBody){
+ this.lockedBody.dom.style.width = (lw + rp) + 'px';
+ this.mainBody.dom.style.width = (tw + rp) + 'px';
+ }
+ }
+});
+
+Ext.ux.grid.LockingColumnModel = Ext.extend(Ext.grid.ColumnModel, {
+ /**
+ * Returns true if the given column index is currently locked
+ * @param {Number} colIndex The column index
+ * @return {Boolean} True if the column is locked
+ */
+ isLocked : function(colIndex){
+ return this.config[colIndex].locked === true;
+ },
+
+ /**
+ * Locks or unlocks a given column
+ * @param {Number} colIndex The column index
+ * @param {Boolean} value True to lock, false to unlock
+ * @param {Boolean} suppressEvent Pass false to cause the columnlockchange event not to fire
+ */
+ setLocked : function(colIndex, value, suppressEvent){
+ if (this.isLocked(colIndex) == value) {
+ return;
+ }
+ this.config[colIndex].locked = value;
+ if (!suppressEvent) {
+ this.fireEvent('columnlockchange', this, colIndex, value);
+ }
+ },
+
+ /**
+ * Returns the total width of all locked columns
+ * @return {Number} The width of all locked columns
+ */
+ getTotalLockedWidth : function(){
+ var totalWidth = 0;
+ for (var i = 0, len = this.config.length; i < len; i++) {
+ if (this.isLocked(i) && !this.isHidden(i)) {
+ totalWidth += this.getColumnWidth(i);
+ }
+ }
+
+ return totalWidth;
+ },
+
+ /**
+ * Returns the total number of locked columns
+ * @return {Number} The number of locked columns
+ */
+ getLockedCount : function() {
+ var len = this.config.length;
+
+ for (var i = 0; i < len; i++) {
+ if (!this.isLocked(i)) {
+ return i;
+ }
+ }
+
+ //if we get to this point all of the columns are locked so we return the total
+ return len;
+ },
+
+ /**
+ * Moves a column from one position to another
+ * @param {Number} oldIndex The current column index
+ * @param {Number} newIndex The destination column index
+ */
+ moveColumn : function(oldIndex, newIndex){
+ var oldLocked = this.isLocked(oldIndex),
+ newLocked = this.isLocked(newIndex);
+
+ if (oldIndex < newIndex && oldLocked && !newLocked) {
+ this.setLocked(oldIndex, false, true);
+ } else if (oldIndex > newIndex && !oldLocked && newLocked) {
+ this.setLocked(oldIndex, true, true);
+ }
+
+ Ext.ux.grid.LockingColumnModel.superclass.moveColumn.apply(this, arguments);
+ }
+});
+Ext.ns('Ext.ux.form');
+
+/**
+ * @class Ext.ux.form.MultiSelect
+ * @extends Ext.form.Field
+ * A control that allows selection and form submission of multiple list items.
+ *
+ * @history
+ * 2008-06-19 bpm Original code contributed by Toby Stuart (with contributions from Robert Williams)
+ * 2008-06-19 bpm Docs and demo code clean up
+ *
+ * @constructor
+ * Create a new MultiSelect
+ * @param {Object} config Configuration options
+ * @xtype multiselect
+ */
+Ext.ux.form.MultiSelect = Ext.extend(Ext.form.Field, {
+ /**
+ * @cfg {String} legend Wraps the object with a fieldset and specified legend.
+ */
+ /**
+ * @cfg {Ext.ListView} view The {@link Ext.ListView} used to render the multiselect list.
+ */
+ /**
+ * @cfg {String/Array} dragGroup The ddgroup name(s) for the MultiSelect DragZone (defaults to undefined).
+ */
+ /**
+ * @cfg {String/Array} dropGroup The ddgroup name(s) for the MultiSelect DropZone (defaults to undefined).
+ */
+ /**
+ * @cfg {Boolean} ddReorder Whether the items in the MultiSelect list are drag/drop reorderable (defaults to false).
+ */
+ ddReorder:false,
+ /**
+ * @cfg {Object/Array} tbar The top toolbar of the control. This can be a {@link Ext.Toolbar} object, a
+ * toolbar config, or an array of buttons/button configs to be added to the toolbar.
+ */
+ /**
+ * @cfg {String} appendOnly True if the list should only allow append drops when drag/drop is enabled
+ * (use for lists which are sorted, defaults to false).
+ */
+ appendOnly:false,
+ /**
+ * @cfg {Number} width Width in pixels of the control (defaults to 100).
+ */
+ width:100,
+ /**
+ * @cfg {Number} height Height in pixels of the control (defaults to 100).
+ */
+ height:100,
+ /**
+ * @cfg {String/Number} displayField Name/Index of the desired display field in the dataset (defaults to 0).
+ */
+ displayField:0,
+ /**
+ * @cfg {String/Number} valueField Name/Index of the desired value field in the dataset (defaults to 1).
+ */
+ valueField:1,
+ /**
+ * @cfg {Boolean} allowBlank False to require at least one item in the list to be selected, true to allow no
+ * selection (defaults to true).
+ */
+ allowBlank:true,
+ /**
+ * @cfg {Number} minSelections Minimum number of selections allowed (defaults to 0).
+ */
+ minSelections:0,
+ /**
+ * @cfg {Number} maxSelections Maximum number of selections allowed (defaults to Number.MAX_VALUE).
+ */
+ maxSelections:Number.MAX_VALUE,
+ /**
+ * @cfg {String} blankText Default text displayed when the control contains no items (defaults to the same value as
+ * {@link Ext.form.TextField#blankText}.
+ */
+ blankText:Ext.form.TextField.prototype.blankText,
+ /**
+ * @cfg {String} minSelectionsText Validation message displayed when {@link #minSelections} is not met (defaults to 'Minimum {0}
+ * item(s) required'). The {0} token will be replaced by the value of {@link #minSelections}.
+ */
+ minSelectionsText:'Minimum {0} item(s) required',
+ /**
+ * @cfg {String} maxSelectionsText Validation message displayed when {@link #maxSelections} is not met (defaults to 'Maximum {0}
+ * item(s) allowed'). The {0} token will be replaced by the value of {@link #maxSelections}.
+ */
+ maxSelectionsText:'Maximum {0} item(s) allowed',
+ /**
+ * @cfg {String} delimiter The string used to delimit between items when set or returned as a string of values
+ * (defaults to ',').
+ */
+ delimiter:',',
+ /**
+ * @cfg {Ext.data.Store/Array} store The data source to which this MultiSelect is bound (defaults to <tt>undefined</tt>).
+ * Acceptable values for this property are:
+ * <div class="mdetail-params"><ul>
+ * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
+ * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally.
+ * <div class="mdetail-params"><ul>
+ * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
+ * A 1-dimensional array will automatically be expanded (each array item will be the combo
+ * {@link #valueField value} and {@link #displayField text})</div></li>
+ * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
+ * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
+ * {@link #valueField value}, while the value at index 1 is assumed to be the combo {@link #displayField text}.
+ * </div></li></ul></div></li></ul></div>
+ */
+
+ // private
+ defaultAutoCreate : {tag: "div"},
+
+ // private
+ initComponent: function(){
+ Ext.ux.form.MultiSelect.superclass.initComponent.call(this);
+
+ if(Ext.isArray(this.store)){
+ if (Ext.isArray(this.store[0])){
+ this.store = new Ext.data.ArrayStore({
+ fields: ['value','text'],
+ data: this.store
+ });
+ this.valueField = 'value';
+ }else{
+ this.store = new Ext.data.ArrayStore({
+ fields: ['text'],
+ data: this.store,
+ expandData: true
+ });
+ this.valueField = 'text';
+ }
+ this.displayField = 'text';
+ } else {
+ this.store = Ext.StoreMgr.lookup(this.store);
+ }
+
+ this.addEvents({
+ 'dblclick' : true,
+ 'click' : true,
+ 'change' : true,
+ 'drop' : true
+ });
+ },
+
+ // private
+ onRender: function(ct, position){
+ Ext.ux.form.MultiSelect.superclass.onRender.call(this, ct, position);
+
+ var fs = this.fs = new Ext.form.FieldSet({
+ renderTo: this.el,
+ title: this.legend,
+ height: this.height,
+ width: this.width,
+ style: "padding:0;",
+ tbar: this.tbar
+ });
+ fs.body.addClass('ux-mselect');
+
+ this.view = new Ext.ListView({
+ multiSelect: true,
+ store: this.store,
+ columns: [{ header: 'Value', width: 1, dataIndex: this.displayField }],
+ hideHeaders: true
+ });
+
+ fs.add(this.view);
+
+ this.view.on('click', this.onViewClick, this);
+ this.view.on('beforeclick', this.onViewBeforeClick, this);
+ this.view.on('dblclick', this.onViewDblClick, this);
+
+ this.hiddenName = this.name || Ext.id();
+ var hiddenTag = { tag: "input", type: "hidden", value: "", name: this.hiddenName };
+ this.hiddenField = this.el.createChild(hiddenTag);
+ this.hiddenField.dom.disabled = this.hiddenName != this.name;
+ fs.doLayout();
+ },
+
+ // private
+ afterRender: function(){
+ Ext.ux.form.MultiSelect.superclass.afterRender.call(this);
+
+ if (this.ddReorder && !this.dragGroup && !this.dropGroup){
+ this.dragGroup = this.dropGroup = 'MultiselectDD-' + Ext.id();
+ }
+
+ if (this.draggable || this.dragGroup){
+ this.dragZone = new Ext.ux.form.MultiSelect.DragZone(this, {
+ ddGroup: this.dragGroup
+ });
+ }
+ if (this.droppable || this.dropGroup){
+ this.dropZone = new Ext.ux.form.MultiSelect.DropZone(this, {
+ ddGroup: this.dropGroup
+ });
+ }
+ },
+
+ // private
+ onViewClick: function(vw, index, node, e) {
+ this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
+ this.hiddenField.dom.value = this.getValue();
+ this.fireEvent('click', this, e);
+ this.validate();
+ },
+
+ // private
+ onViewBeforeClick: function(vw, index, node, e) {
+ if (this.disabled || this.readOnly) {
+ return false;
+ }
+ },
+
+ // private
+ onViewDblClick : function(vw, index, node, e) {
+ return this.fireEvent('dblclick', vw, index, node, e);
+ },
+
+ /**
+ * Returns an array of data values for the selected items in the list. The values will be separated
+ * by {@link #delimiter}.
+ * @return {Array} value An array of string data values
+ */
+ getValue: function(valueField){
+ var returnArray = [];
+ var selectionsArray = this.view.getSelectedIndexes();
+ if (selectionsArray.length == 0) {return '';}
+ for (var i=0; i<selectionsArray.length; i++) {
+ returnArray.push(this.store.getAt(selectionsArray[i]).get((valueField != null) ? valueField : this.valueField));
+ }
+ return returnArray.join(this.delimiter);
+ },
+
+ /**
+ * Sets a delimited string (using {@link #delimiter}) or array of data values into the list.
+ * @param {String/Array} values The values to set
+ */
+ setValue: function(values) {
+ var index;
+ var selections = [];
+ this.view.clearSelections();
+ this.hiddenField.dom.value = '';
+
+ if (!values || (values == '')) { return; }
+
+ if (!Ext.isArray(values)) { values = values.split(this.delimiter); }
+ for (var i=0; i<values.length; i++) {
+ index = this.view.store.indexOf(this.view.store.query(this.valueField,
+ new RegExp('^' + values[i] + '$', "i")).itemAt(0));
+ selections.push(index);
+ }
+ this.view.select(selections);
+ this.hiddenField.dom.value = this.getValue();
+ this.validate();
+ },
+
+ // inherit docs
+ reset : function() {
+ this.setValue('');
+ },
+
+ // inherit docs
+ getRawValue: function(valueField) {
+ var tmp = this.getValue(valueField);
+ if (tmp.length) {
+ tmp = tmp.split(this.delimiter);
+ }
+ else {
+ tmp = [];
+ }
+ return tmp;
+ },
+
+ // inherit docs
+ setRawValue: function(values){
+ setValue(values);
+ },
+
+ // inherit docs
+ validateValue : function(value){
+ if (value.length < 1) { // if it has no value
+ if (this.allowBlank) {
+ this.clearInvalid();
+ return true;
+ } else {
+ this.markInvalid(this.blankText);
+ return false;
+ }
+ }
+ if (value.length < this.minSelections) {
+ this.markInvalid(String.format(this.minSelectionsText, this.minSelections));
+ return false;
+ }
+ if (value.length > this.maxSelections) {
+ this.markInvalid(String.format(this.maxSelectionsText, this.maxSelections));
+ return false;
+ }
+ return true;
+ },
+
+ // inherit docs
+ disable: function(){
+ this.disabled = true;
+ this.hiddenField.dom.disabled = true;
+ this.fs.disable();
+ },
+
+ // inherit docs
+ enable: function(){
+ this.disabled = false;
+ this.hiddenField.dom.disabled = false;
+ this.fs.enable();
+ },
+
+ // inherit docs
+ destroy: function(){
+ Ext.destroy(this.fs, this.dragZone, this.dropZone);
+ Ext.ux.form.MultiSelect.superclass.destroy.call(this);
+ }
+});
+
+
+Ext.reg('multiselect', Ext.ux.form.MultiSelect);
+
+//backwards compat
+Ext.ux.Multiselect = Ext.ux.form.MultiSelect;
+
+
+Ext.ux.form.MultiSelect.DragZone = function(ms, config){
+ this.ms = ms;
+ this.view = ms.view;
+ var ddGroup = config.ddGroup || 'MultiselectDD';
+ var dd;
+ if (Ext.isArray(ddGroup)){
+ dd = ddGroup.shift();
+ } else {
+ dd = ddGroup;
+ ddGroup = null;
+ }
+ Ext.ux.form.MultiSelect.DragZone.superclass.constructor.call(this, this.ms.fs.body, { containerScroll: true, ddGroup: dd });
+ this.setDraggable(ddGroup);
+};
+
+Ext.extend(Ext.ux.form.MultiSelect.DragZone, Ext.dd.DragZone, {
+ onInitDrag : function(x, y){
+ var el = Ext.get(this.dragData.ddel.cloneNode(true));
+ this.proxy.update(el.dom);
+ el.setWidth(el.child('em').getWidth());
+ this.onStartDrag(x, y);
+ return true;
+ },
+
+ // private
+ collectSelection: function(data) {
+ data.repairXY = Ext.fly(this.view.getSelectedNodes()[0]).getXY();
+ var i = 0;
+ this.view.store.each(function(rec){
+ if (this.view.isSelected(i)) {
+ var n = this.view.getNode(i);
+ var dragNode = n.cloneNode(true);
+ dragNode.id = Ext.id();
+ data.ddel.appendChild(dragNode);
+ data.records.push(this.view.store.getAt(i));
+ data.viewNodes.push(n);
+ }
+ i++;
+ }, this);
+ },
+
+ // override
+ onEndDrag: function(data, e) {
+ var d = Ext.get(this.dragData.ddel);
+ if (d && d.hasClass("multi-proxy")) {
+ d.remove();
+ }
+ },
+
+ // override
+ getDragData: function(e){
+ var target = this.view.findItemFromChild(e.getTarget());
+ if(target) {
+ if (!this.view.isSelected(target) && !e.ctrlKey && !e.shiftKey) {
+ this.view.select(target);
+ this.ms.setValue(this.ms.getValue());
+ }
+ if (this.view.getSelectionCount() == 0 || e.ctrlKey || e.shiftKey) return false;
+ var dragData = {
+ sourceView: this.view,
+ viewNodes: [],
+ records: []
+ };
+ if (this.view.getSelectionCount() == 1) {
+ var i = this.view.getSelectedIndexes()[0];
+ var n = this.view.getNode(i);
+ dragData.viewNodes.push(dragData.ddel = n);
+ dragData.records.push(this.view.store.getAt(i));
+ dragData.repairXY = Ext.fly(n).getXY();
+ } else {
+ dragData.ddel = document.createElement('div');
+ dragData.ddel.className = 'multi-proxy';
+ this.collectSelection(dragData);
+ }
+ return dragData;
+ }
+ return false;
+ },
+
+ // override the default repairXY.
+ getRepairXY : function(e){
+ return this.dragData.repairXY;
+ },
+
+ // private
+ setDraggable: function(ddGroup){
+ if (!ddGroup) return;
+ if (Ext.isArray(ddGroup)) {
+ Ext.each(ddGroup, this.setDraggable, this);
+ return;
+ }
+ this.addToGroup(ddGroup);
+ }
+});
+
+Ext.ux.form.MultiSelect.DropZone = function(ms, config){
+ this.ms = ms;
+ this.view = ms.view;
+ var ddGroup = config.ddGroup || 'MultiselectDD';
+ var dd;
+ if (Ext.isArray(ddGroup)){
+ dd = ddGroup.shift();
+ } else {
+ dd = ddGroup;
+ ddGroup = null;
+ }
+ Ext.ux.form.MultiSelect.DropZone.superclass.constructor.call(this, this.ms.fs.body, { containerScroll: true, ddGroup: dd });
+ this.setDroppable(ddGroup);
+};
+
+Ext.extend(Ext.ux.form.MultiSelect.DropZone, Ext.dd.DropZone, {
+ /**
+ * Part of the Ext.dd.DropZone interface. If no target node is found, the
+ * whole Element becomes the target, and this causes the drop gesture to append.
+ */
+ getTargetFromEvent : function(e) {
+ var target = e.getTarget();
+ return target;
+ },
+
+ // private
+ getDropPoint : function(e, n, dd){
+ if (n == this.ms.fs.body.dom) { return "below"; }
+ var t = Ext.lib.Dom.getY(n), b = t + n.offsetHeight;
+ var c = t + (b - t) / 2;
+ var y = Ext.lib.Event.getPageY(e);
+ if(y <= c) {
+ return "above";
+ }else{
+ return "below";
+ }
+ },
+
+ // private
+ isValidDropPoint: function(pt, n, data) {
+ if (!data.viewNodes || (data.viewNodes.length != 1)) {
+ return true;
+ }
+ var d = data.viewNodes[0];
+ if (d == n) {
+ return false;
+ }
+ if ((pt == "below") && (n.nextSibling == d)) {
+ return false;
+ }
+ if ((pt == "above") && (n.previousSibling == d)) {
+ return false;
+ }
+ return true;
+ },
+
+ // override
+ onNodeEnter : function(n, dd, e, data){
+ return false;
+ },
+
+ // override
+ onNodeOver : function(n, dd, e, data){
+ var dragElClass = this.dropNotAllowed;
+ var pt = this.getDropPoint(e, n, dd);
+ if (this.isValidDropPoint(pt, n, data)) {
+ if (this.ms.appendOnly) {
+ return "x-tree-drop-ok-below";
+ }
+
+ // set the insert point style on the target node
+ if (pt) {
+ var targetElClass;
+ if (pt == "above"){
+ dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
+ targetElClass = "x-view-drag-insert-above";
+ } else {
+ dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
+ targetElClass = "x-view-drag-insert-below";
+ }
+ if (this.lastInsertClass != targetElClass){
+ Ext.fly(n).replaceClass(this.lastInsertClass, targetElClass);
+ this.lastInsertClass = targetElClass;
+ }
+ }
+ }
+ return dragElClass;
+ },
+
+ // private
+ onNodeOut : function(n, dd, e, data){
+ this.removeDropIndicators(n);
+ },
+
+ // private
+ onNodeDrop : function(n, dd, e, data){
+ if (this.ms.fireEvent("drop", this, n, dd, e, data) === false) {
+ return false;
+ }
+ var pt = this.getDropPoint(e, n, dd);
+ if (n != this.ms.fs.body.dom)
+ n = this.view.findItemFromChild(n);
+
+ if(this.ms.appendOnly) {
+ insertAt = this.view.store.getCount();
+ } else {
+ insertAt = n == this.ms.fs.body.dom ? this.view.store.getCount() - 1 : this.view.indexOf(n);
+ if (pt == "below") {
+ insertAt++;
+ }
+ }
+
+ var dir = false;
+
+ // Validate if dragging within the same MultiSelect
+ if (data.sourceView == this.view) {
+ // If the first element to be inserted below is the target node, remove it
+ if (pt == "below") {
+ if (data.viewNodes[0] == n) {
+ data.viewNodes.shift();
+ }
+ } else { // If the last element to be inserted above is the target node, remove it
+ if (data.viewNodes[data.viewNodes.length - 1] == n) {
+ data.viewNodes.pop();
+ }
+ }
+
+ // Nothing to drop...
+ if (!data.viewNodes.length) {
+ return false;
+ }
+
+ // If we are moving DOWN, then because a store.remove() takes place first,
+ // the insertAt must be decremented.
+ if (insertAt > this.view.store.indexOf(data.records[0])) {
+ dir = 'down';
+ insertAt--;
+ }
+ }
+
+ for (var i = 0; i < data.records.length; i++) {
+ var r = data.records[i];
+ if (data.sourceView) {
+ data.sourceView.store.remove(r);
+ }
+ this.view.store.insert(dir == 'down' ? insertAt : insertAt++, r);
+ var si = this.view.store.sortInfo;
+ if(si){
+ this.view.store.sort(si.field, si.direction);
+ }
+ }
+ return true;
+ },
+
+ // private
+ removeDropIndicators : function(n){
+ if(n){
+ Ext.fly(n).removeClass([
+ "x-view-drag-insert-above",
+ "x-view-drag-insert-left",
+ "x-view-drag-insert-right",
+ "x-view-drag-insert-below"]);
+ this.lastInsertClass = "_noclass";
+ }
+ },
+
+ // private
+ setDroppable: function(ddGroup){
+ if (!ddGroup) return;
+ if (Ext.isArray(ddGroup)) {
+ Ext.each(ddGroup, this.setDroppable, this);
+ return;
+ }
+ this.addToGroup(ddGroup);
+ }
+});
+
+/* Fix for Opera, which does not seem to include the map function on Array's */
+if (!Array.prototype.map) {
+ Array.prototype.map = function(fun){
+ var len = this.length;
+ if (typeof fun != 'function') {
+ throw new TypeError();
+ }
+ var res = new Array(len);
+ var thisp = arguments[1];
+ for (var i = 0; i < len; i++) {
+ if (i in this) {
+ res[i] = fun.call(thisp, this[i], i, this);
+ }
+ }
+ return res;
+ };
+}
+
+Ext.ns('Ext.ux.data');
+
+/**
+ * @class Ext.ux.data.PagingMemoryProxy
+ * @extends Ext.data.MemoryProxy
+ * <p>Paging Memory Proxy, allows to use paging grid with in memory dataset</p>
+ */
+Ext.ux.data.PagingMemoryProxy = Ext.extend(Ext.data.MemoryProxy, {
+ constructor : function(data){
+ Ext.ux.data.PagingMemoryProxy.superclass.constructor.call(this);
+ this.data = data;
+ },
+ doRequest : function(action, rs, params, reader, callback, scope, options){
+ params = params ||
+ {};
+ var result;
+ try {
+ result = reader.readRecords(this.data);
+ }
+ catch (e) {
+ this.fireEvent('loadexception', this, options, null, e);
+ callback.call(scope, null, options, false);
+ return;
+ }
+
+ // filtering
+ if (params.filter !== undefined) {
+ result.records = result.records.filter(function(el){
+ if (typeof(el) == 'object') {
+ var att = params.filterCol || 0;
+ return String(el.data[att]).match(params.filter) ? true : false;
+ }
+ else {
+ return String(el).match(params.filter) ? true : false;
+ }
+ });
+ result.totalRecords = result.records.length;
+ }
+
+ // sorting
+ if (params.sort !== undefined) {
+ // use integer as params.sort to specify column, since arrays are not named
+ // params.sort=0; would also match a array without columns
+ var dir = String(params.dir).toUpperCase() == 'DESC' ? -1 : 1;
+ var fn = function(v1, v2){
+ return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
+ };
+ result.records.sort(function(a, b){
+ var v = 0;
+ if (typeof(a) == 'object') {
+ v = fn(a.data[params.sort], b.data[params.sort]) * dir;
+ }
+ else {
+ v = fn(a, b) * dir;
+ }
+ if (v == 0) {
+ v = (a.index < b.index ? -1 : 1);
+ }
+ return v;
+ });
+ }
+ // paging (use undefined cause start can also be 0 (thus false))
+ if (params.start !== undefined && params.limit !== undefined) {
+ result.records = result.records.slice(params.start, params.start + params.limit);
+ }
+ callback.call(scope, result, options, true);
+ }
+});
+
+//backwards compat.
+Ext.data.PagingMemoryProxy = Ext.ux.data.PagingMemoryProxy;
+Ext.ux.PanelResizer = Ext.extend(Ext.util.Observable, {
+ minHeight: 0,
+ maxHeight:10000000,
+
+ constructor: function(config){
+ Ext.apply(this, config);
+ this.events = {};
+ Ext.ux.PanelResizer.superclass.constructor.call(this, config);
+ },
+
+ init : function(p){
+ this.panel = p;
+
+ if(this.panel.elements.indexOf('footer')==-1){
+ p.elements += ',footer';
+ }
+ p.on('render', this.onRender, this);
+ },
+
+ onRender : function(p){
+ this.handle = p.footer.createChild({cls:'x-panel-resize'});
+
+ this.tracker = new Ext.dd.DragTracker({
+ onStart: this.onDragStart.createDelegate(this),
+ onDrag: this.onDrag.createDelegate(this),
+ onEnd: this.onDragEnd.createDelegate(this),
+ tolerance: 3,
+ autoStart: 300
+ });
+ this.tracker.initEl(this.handle);
+ p.on('beforedestroy', this.tracker.destroy, this.tracker);
+ },
+
+ // private
+ onDragStart: function(e){
+ this.dragging = true;
+ this.startHeight = this.panel.el.getHeight();
+ this.fireEvent('dragstart', this, e);
+ },
+
+ // private
+ onDrag: function(e){
+ this.panel.setHeight((this.startHeight-this.tracker.getOffset()[1]).constrain(this.minHeight, this.maxHeight));
+ this.fireEvent('drag', this, e);
+ },
+
+ // private
+ onDragEnd: function(e){
+ this.dragging = false;
+ this.fireEvent('dragend', this, e);
+ }
+});
+Ext.preg('panelresizer', Ext.ux.PanelResizer);Ext.ux.Portal = Ext.extend(Ext.Panel, {
+ layout : 'column',
+ autoScroll : true,
+ cls : 'x-portal',
+ defaultType : 'portalcolumn',
+
+ initComponent : function(){
+ Ext.ux.Portal.superclass.initComponent.call(this);
+ this.addEvents({
+ validatedrop:true,
+ beforedragover:true,
+ dragover:true,
+ beforedrop:true,
+ drop:true
+ });
+ },
+
+ initEvents : function(){
+ Ext.ux.Portal.superclass.initEvents.call(this);
+ this.dd = new Ext.ux.Portal.DropZone(this, this.dropConfig);
+ },
+
+ beforeDestroy : function() {
+ if(this.dd){
+ this.dd.unreg();
+ }
+ Ext.ux.Portal.superclass.beforeDestroy.call(this);
+ }
+});
+
+Ext.reg('portal', Ext.ux.Portal);
+
+Ext.ux.Portal.DropZone = Ext.extend(Ext.dd.DropTarget, {
+
+ constructor : function(portal, cfg){
+ this.portal = portal;
+ Ext.dd.ScrollManager.register(portal.body);
+ Ext.ux.Portal.DropZone.superclass.constructor.call(this, portal.bwrap.dom, cfg);
+ portal.body.ddScrollConfig = this.ddScrollConfig;
+ },
+
+ ddScrollConfig : {
+ vthresh: 50,
+ hthresh: -1,
+ animate: true,
+ increment: 200
+ },
+
+ createEvent : function(dd, e, data, col, c, pos){
+ return {
+ portal: this.portal,
+ panel: data.panel,
+ columnIndex: col,
+ column: c,
+ position: pos,
+ data: data,
+ source: dd,
+ rawEvent: e,
+ status: this.dropAllowed
+ };
+ },
+
+ notifyOver : function(dd, e, data){
+ var xy = e.getXY(), portal = this.portal, px = dd.proxy;
+
+ // case column widths
+ if(!this.grid){
+ this.grid = this.getGrid();
+ }
+
+ // handle case scroll where scrollbars appear during drag
+ var cw = portal.body.dom.clientWidth;
+ if(!this.lastCW){
+ this.lastCW = cw;
+ }else if(this.lastCW != cw){
+ this.lastCW = cw;
+ portal.doLayout();
+ this.grid = this.getGrid();
+ }
+
+ // determine column
+ var col = 0, xs = this.grid.columnX, cmatch = false;
+ for(var len = xs.length; col < len; col++){
+ if(xy[0] < (xs[col].x + xs[col].w)){
+ cmatch = true;
+ break;
+ }
+ }
+ // no match, fix last index
+ if(!cmatch){
+ col--;
+ }
+
+ // find insert position
+ var p, match = false, pos = 0,
+ c = portal.items.itemAt(col),
+ items = c.items.items, overSelf = false;
+
+ for(var len = items.length; pos < len; pos++){
+ p = items[pos];
+ var h = p.el.getHeight();
+ if(h === 0){
+ overSelf = true;
+ }
+ else if((p.el.getY()+(h/2)) > xy[1]){
+ match = true;
+ break;
+ }
+ }
+
+ pos = (match && p ? pos : c.items.getCount()) + (overSelf ? -1 : 0);
+ var overEvent = this.createEvent(dd, e, data, col, c, pos);
+
+ if(portal.fireEvent('validatedrop', overEvent) !== false &&
+ portal.fireEvent('beforedragover', overEvent) !== false){
+
+ // make sure proxy width is fluid
+ px.getProxy().setWidth('auto');
+
+ if(p){
+ px.moveProxy(p.el.dom.parentNode, match ? p.el.dom : null);
+ }else{
+ px.moveProxy(c.el.dom, null);
+ }
+
+ this.lastPos = {c: c, col: col, p: overSelf || (match && p) ? pos : false};
+ this.scrollPos = portal.body.getScroll();
+
+ portal.fireEvent('dragover', overEvent);
+
+ return overEvent.status;
+ }else{
+ return overEvent.status;
+ }
+
+ },
+
+ notifyOut : function(){
+ delete this.grid;
+ },
+
+ notifyDrop : function(dd, e, data){
+ delete this.grid;
+ if(!this.lastPos){
+ return;
+ }
+ var c = this.lastPos.c,
+ col = this.lastPos.col,
+ pos = this.lastPos.p,
+ panel = dd.panel,
+ dropEvent = this.createEvent(dd, e, data, col, c,
+ pos !== false ? pos : c.items.getCount());
+
+ if(this.portal.fireEvent('validatedrop', dropEvent) !== false &&
+ this.portal.fireEvent('beforedrop', dropEvent) !== false){
+
+ dd.proxy.getProxy().remove();
+ panel.el.dom.parentNode.removeChild(dd.panel.el.dom);
+
+ if(pos !== false){
+ c.insert(pos, panel);
+ }else{
+ c.add(panel);
+ }
+
+ c.doLayout();
+
+ this.portal.fireEvent('drop', dropEvent);
+
+ // scroll position is lost on drop, fix it
+ var st = this.scrollPos.top;
+ if(st){
+ var d = this.portal.body.dom;
+ setTimeout(function(){
+ d.scrollTop = st;
+ }, 10);
+ }
+
+ }
+ delete this.lastPos;
+ },
+
+ // internal cache of body and column coords
+ getGrid : function(){
+ var box = this.portal.bwrap.getBox();
+ box.columnX = [];
+ this.portal.items.each(function(c){
+ box.columnX.push({x: c.el.getX(), w: c.el.getWidth()});
+ });
+ return box;
+ },
+
+ // unregister the dropzone from ScrollManager
+ unreg: function() {
+ Ext.dd.ScrollManager.unregister(this.portal.body);
+ Ext.ux.Portal.DropZone.superclass.unreg.call(this);
+ }
+});
+Ext.ux.PortalColumn = Ext.extend(Ext.Container, {
+ layout : 'anchor',
+ //autoEl : 'div',//already defined by Ext.Component
+ defaultType : 'portlet',
+ cls : 'x-portal-column'
+});
+
+Ext.reg('portalcolumn', Ext.ux.PortalColumn);
+Ext.ux.Portlet = Ext.extend(Ext.Panel, {
+ anchor : '100%',
+ frame : true,
+ collapsible : true,
+ draggable : true,
+ cls : 'x-portlet'
+});
+
+Ext.reg('portlet', Ext.ux.Portlet);
+/**
+* @class Ext.ux.ProgressBarPager
+* @extends Object
+* Plugin (ptype = 'tabclosemenu') for displaying a progressbar inside of a paging toolbar instead of plain text
+*
+* @ptype progressbarpager
+* @constructor
+* Create a new ItemSelector
+* @param {Object} config Configuration options
+* @xtype itemselector
+*/
+Ext.ux.ProgressBarPager = Ext.extend(Object, {
+ /**
+ * @cfg {Integer} progBarWidth
+ * <p>The default progress bar width. Default is 225.</p>
+ */
+ progBarWidth : 225,
+ /**
+ * @cfg {String} defaultText
+ * <p>The text to display while the store is loading. Default is 'Loading...'</p>
+ */
+ defaultText : 'Loading...',
+ /**
+ * @cfg {Object} defaultAnimCfg
+ * <p>A {@link Ext.Fx Ext.Fx} configuration object. Default is { duration : 1, easing : 'bounceOut' }.</p>
+ */
+ defaultAnimCfg : {
+ duration : 1,
+ easing : 'bounceOut'
+ },
+ constructor : function(config) {
+ if (config) {
+ Ext.apply(this, config);
+ }
+ },
+ //public
+ init : function (parent) {
+
+ if(parent.displayInfo){
+ this.parent = parent;
+ var ind = parent.items.indexOf(parent.displayItem);
+ parent.remove(parent.displayItem, true);
+ this.progressBar = new Ext.ProgressBar({
+ text : this.defaultText,
+ width : this.progBarWidth,
+ animate : this.defaultAnimCfg
+ });
+
+ parent.displayItem = this.progressBar;
+
+ parent.add(parent.displayItem);
+ parent.doLayout();
+ Ext.apply(parent, this.parentOverrides);
+
+ this.progressBar.on('render', function(pb) {
+ pb.mon(pb.getEl().applyStyles('cursor:pointer'), 'click', this.handleProgressBarClick, this);
+ }, this, {single: true});
+
+ }
+
+ },
+ // private
+ // This method handles the click for the progress bar
+ handleProgressBarClick : function(e){
+ var parent = this.parent,
+ displayItem = parent.displayItem,
+ box = this.progressBar.getBox(),
+ xy = e.getXY(),
+ position = xy[0]-box.x,
+ pages = Math.ceil(parent.store.getTotalCount()/parent.pageSize),
+ newpage = Math.ceil(position/(displayItem.width/pages));
+
+ parent.changePage(newpage);
+ },
+
+ // private, overriddes
+ parentOverrides : {
+ // private
+ // This method updates the information via the progress bar.
+ updateInfo : function(){
+ if(this.displayItem){
+ var count = this.store.getCount(),
+ pgData = this.getPageData(),
+ pageNum = this.readPage(pgData),
+ msg = count == 0 ?
+ this.emptyMsg :
+ String.format(
+ this.displayMsg,
+ this.cursor+1, this.cursor+count, this.store.getTotalCount()
+ );
+
+ pageNum = pgData.activePage; ;
+
+ var pct = pageNum / pgData.pages;
+
+ this.displayItem.updateProgress(pct, msg, this.animate || this.defaultAnimConfig);
+ }
+ }
+ }
+});
+Ext.preg('progressbarpager', Ext.ux.ProgressBarPager);
+
+Ext.ns('Ext.ux.grid');
+
+/**
+ * @class Ext.ux.grid.RowEditor
+ * @extends Ext.Panel
+ * Plugin (ptype = 'roweditor') that adds the ability to rapidly edit full rows in a grid.
+ * A validation mode may be enabled which uses AnchorTips to notify the user of all
+ * validation errors at once.
+ *
+ * @ptype roweditor
+ */
+Ext.ux.grid.RowEditor = Ext.extend(Ext.Panel, {
+ floating: true,
+ shadow: false,
+ layout: 'hbox',
+ cls: 'x-small-editor',
+ buttonAlign: 'center',
+ baseCls: 'x-row-editor',
+ elements: 'header,footer,body',
+ frameWidth: 5,
+ buttonPad: 3,
+ clicksToEdit: 'auto',
+ monitorValid: true,
+ focusDelay: 250,
+ errorSummary: true,
+
+ saveText: 'Save',
+ cancelText: 'Cancel',
+ commitChangesText: 'You need to commit or cancel your changes',
+ errorText: 'Errors',
+
+ defaults: {
+ normalWidth: true
+ },
+
+ initComponent: function(){
+ Ext.ux.grid.RowEditor.superclass.initComponent.call(this);
+ this.addEvents(
+ /**
+ * @event beforeedit
+ * Fired before the row editor is activated.
+ * If the listener returns <tt>false</tt> the editor will not be activated.
+ * @param {Ext.ux.grid.RowEditor} roweditor This object
+ * @param {Number} rowIndex The rowIndex of the row just edited
+ */
+ 'beforeedit',
+ /**
+ * @event canceledit
+ * Fired when the editor is cancelled.
+ * @param {Ext.ux.grid.RowEditor} roweditor This object
+ * @param {Boolean} forced True if the cancel button is pressed, false is the editor was invalid.
+ */
+ 'canceledit',
+ /**
+ * @event validateedit
+ * Fired after a row is edited and passes validation.
+ * If the listener returns <tt>false</tt> changes to the record will not be set.
+ * @param {Ext.ux.grid.RowEditor} roweditor This object
+ * @param {Object} changes Object with changes made to the record.
+ * @param {Ext.data.Record} r The Record that was edited.
+ * @param {Number} rowIndex The rowIndex of the row just edited
+ */
+ 'validateedit',
+ /**
+ * @event afteredit
+ * Fired after a row is edited and passes validation. This event is fired
+ * after the store's update event is fired with this edit.
+ * @param {Ext.ux.grid.RowEditor} roweditor This object
+ * @param {Object} changes Object with changes made to the record.
+ * @param {Ext.data.Record} r The Record that was edited.
+ * @param {Number} rowIndex The rowIndex of the row just edited
+ */
+ 'afteredit'
+ );
+ },
+
+ init: function(grid){
+ this.grid = grid;
+ this.ownerCt = grid;
+ if(this.clicksToEdit === 2){
+ grid.on('rowdblclick', this.onRowDblClick, this);
+ }else{
+ grid.on('rowclick', this.onRowClick, this);
+ if(Ext.isIE){
+ grid.on('rowdblclick', this.onRowDblClick, this);
+ }
+ }
+
+ // stopEditing without saving when a record is removed from Store.
+ grid.getStore().on('remove', function() {
+ this.stopEditing(false);
+ },this);
+
+ grid.on({
+ scope: this,
+ keydown: this.onGridKey,
+ columnresize: this.verifyLayout,
+ columnmove: this.refreshFields,
+ reconfigure: this.refreshFields,
+ beforedestroy : this.beforedestroy,
+ destroy : this.destroy,
+ bodyscroll: {
+ buffer: 250,
+ fn: this.positionButtons
+ }
+ });
+ grid.getColumnModel().on('hiddenchange', this.verifyLayout, this, {delay:1});
+ grid.getView().on('refresh', this.stopEditing.createDelegate(this, []));
+ },
+
+ beforedestroy: function() {
+ this.stopMonitoring();
+ this.grid.getStore().un('remove', this.onStoreRemove, this);
+ this.stopEditing(false);
+ Ext.destroy(this.btns, this.tooltip);
+ },
+
+ refreshFields: function(){
+ this.initFields();
+ this.verifyLayout();
+ },
+
+ isDirty: function(){
+ var dirty;
+ this.items.each(function(f){
+ if(String(this.values[f.id]) !== String(f.getValue())){
+ dirty = true;
+ return false;
+ }
+ }, this);
+ return dirty;
+ },
+
+ startEditing: function(rowIndex, doFocus){
+ if(this.editing && this.isDirty()){
+ this.showTooltip(this.commitChangesText);
+ return;
+ }
+ if(Ext.isObject(rowIndex)){
+ rowIndex = this.grid.getStore().indexOf(rowIndex);
+ }
+ if(this.fireEvent('beforeedit', this, rowIndex) !== false){
+ this.editing = true;
+ var g = this.grid, view = g.getView(),
+ row = view.getRow(rowIndex),
+ record = g.store.getAt(rowIndex);
+
+ this.record = record;
+ this.rowIndex = rowIndex;
+ this.values = {};
+ if(!this.rendered){
+ this.render(view.getEditorParent());
+ }
+ var w = Ext.fly(row).getWidth();
+ this.setSize(w);
+ if(!this.initialized){
+ this.initFields();
+ }
+ var cm = g.getColumnModel(), fields = this.items.items, f, val;
+ for(var i = 0, len = cm.getColumnCount(); i < len; i++){
+ val = this.preEditValue(record, cm.getDataIndex(i));
+ f = fields[i];
+ f.setValue(val);
+ this.values[f.id] = Ext.isEmpty(val) ? '' : val;
+ }
+ this.verifyLayout(true);
+ if(!this.isVisible()){
+ this.setPagePosition(Ext.fly(row).getXY());
+ } else{
+ this.el.setXY(Ext.fly(row).getXY(), {duration:0.15});
+ }
+ if(!this.isVisible()){
+ this.show().doLayout();
+ }
+ if(doFocus !== false){
+ this.doFocus.defer(this.focusDelay, this);
+ }
+ }
+ },
+
+ stopEditing : function(saveChanges){
+ this.editing = false;
+ if(!this.isVisible()){
+ return;
+ }
+ if(saveChanges === false || !this.isValid()){
+ this.hide();
+ this.fireEvent('canceledit', this, saveChanges === false);
+ return;
+ }
+ var changes = {},
+ r = this.record,
+ hasChange = false,
+ cm = this.grid.colModel,
+ fields = this.items.items;
+ for(var i = 0, len = cm.getColumnCount(); i < len; i++){
+ if(!cm.isHidden(i)){
+ var dindex = cm.getDataIndex(i);
+ if(!Ext.isEmpty(dindex)){
+ var oldValue = r.data[dindex],
+ value = this.postEditValue(fields[i].getValue(), oldValue, r, dindex);
+ if(String(oldValue) !== String(value)){
+ changes[dindex] = value;
+ hasChange = true;
+ }
+ }
+ }
+ }
+ if(hasChange && this.fireEvent('validateedit', this, changes, r, this.rowIndex) !== false){
+ r.beginEdit();
+ Ext.iterate(changes, function(name, value){
+ r.set(name, value);
+ });
+ r.endEdit();
+ this.fireEvent('afteredit', this, changes, r, this.rowIndex);
+ }
+ this.hide();
+ },
+
+ verifyLayout: function(force){
+ if(this.el && (this.isVisible() || force === true)){
+ var row = this.grid.getView().getRow(this.rowIndex);
+ this.setSize(Ext.fly(row).getWidth(), Ext.isIE ? Ext.fly(row).getHeight() + 9 : undefined);
+ var cm = this.grid.colModel, fields = this.items.items;
+ for(var i = 0, len = cm.getColumnCount(); i < len; i++){
+ if(!cm.isHidden(i)){
+ var adjust = 0;
+ if(i === (len - 1)){
+ adjust += 3; // outer padding
+ } else{
+ adjust += 1;
+ }
+ fields[i].show();
+ fields[i].setWidth(cm.getColumnWidth(i) - adjust);
+ } else{
+ fields[i].hide();
+ }
+ }
+ this.doLayout();
+ this.positionButtons();
+ }
+ },
+
+ slideHide : function(){
+ this.hide();
+ },
+
+ initFields: function(){
+ var cm = this.grid.getColumnModel(), pm = Ext.layout.ContainerLayout.prototype.parseMargins;
+ this.removeAll(false);
+ for(var i = 0, len = cm.getColumnCount(); i < len; i++){
+ var c = cm.getColumnAt(i),
+ ed = c.getEditor();
+ if(!ed){
+ ed = c.displayEditor || new Ext.form.DisplayField();
+ }
+ if(i == 0){
+ ed.margins = pm('0 1 2 1');
+ } else if(i == len - 1){
+ ed.margins = pm('0 0 2 1');
+ } else{
+ if (Ext.isIE) {
+ ed.margins = pm('0 0 2 0');
+ }
+ else {
+ ed.margins = pm('0 1 2 0');
+ }
+ }
+ ed.setWidth(cm.getColumnWidth(i));
+ ed.column = c;
+ if(ed.ownerCt !== this){
+ ed.on('focus', this.ensureVisible, this);
+ ed.on('specialkey', this.onKey, this);
+ }
+ this.insert(i, ed);
+ }
+ this.initialized = true;
+ },
+
+ onKey: function(f, e){
+ if(e.getKey() === e.ENTER){
+ this.stopEditing(true);
+ e.stopPropagation();
+ }
+ },
+
+ onGridKey: function(e){
+ if(e.getKey() === e.ENTER && !this.isVisible()){
+ var r = this.grid.getSelectionModel().getSelected();
+ if(r){
+ var index = this.grid.store.indexOf(r);
+ this.startEditing(index);
+ e.stopPropagation();
+ }
+ }
+ },
+
+ ensureVisible: function(editor){
+ if(this.isVisible()){
+ this.grid.getView().ensureVisible(this.rowIndex, this.grid.colModel.getIndexById(editor.column.id), true);
+ }
+ },
+
+ onRowClick: function(g, rowIndex, e){
+ if(this.clicksToEdit == 'auto'){
+ var li = this.lastClickIndex;
+ this.lastClickIndex = rowIndex;
+ if(li != rowIndex && !this.isVisible()){
+ return;
+ }
+ }
+ this.startEditing(rowIndex, false);
+ this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
+ },
+
+ onRowDblClick: function(g, rowIndex, e){
+ this.startEditing(rowIndex, false);
+ this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
+ },
+
+ onRender: function(){
+ Ext.ux.grid.RowEditor.superclass.onRender.apply(this, arguments);
+ this.el.swallowEvent(['keydown', 'keyup', 'keypress']);
+ this.btns = new Ext.Panel({
+ baseCls: 'x-plain',
+ cls: 'x-btns',
+ elements:'body',
+ layout: 'table',
+ width: (this.minButtonWidth * 2) + (this.frameWidth * 2) + (this.buttonPad * 4), // width must be specified for IE
+ items: [{
+ ref: 'saveBtn',
+ itemId: 'saveBtn',
+ xtype: 'button',
+ text: this.saveText,
+ width: this.minButtonWidth,
+ handler: this.stopEditing.createDelegate(this, [true])
+ }, {
+ xtype: 'button',
+ text: this.cancelText,
+ width: this.minButtonWidth,
+ handler: this.stopEditing.createDelegate(this, [false])
+ }]
+ });
+ this.btns.render(this.bwrap);
+ },
+
+ afterRender: function(){
+ Ext.ux.grid.RowEditor.superclass.afterRender.apply(this, arguments);
+ this.positionButtons();
+ if(this.monitorValid){
+ this.startMonitoring();
+ }
+ },
+
+ onShow: function(){
+ if(this.monitorValid){
+ this.startMonitoring();
+ }
+ Ext.ux.grid.RowEditor.superclass.onShow.apply(this, arguments);
+ },
+
+ onHide: function(){
+ Ext.ux.grid.RowEditor.superclass.onHide.apply(this, arguments);
+ this.stopMonitoring();
+ this.grid.getView().focusRow(this.rowIndex);
+ },
+
+ positionButtons: function(){
+ if(this.btns){
+ var g = this.grid,
+ h = this.el.dom.clientHeight,
+ view = g.getView(),
+ scroll = view.scroller.dom.scrollLeft,
+ bw = this.btns.getWidth(),
+ width = Math.min(g.getWidth(), g.getColumnModel().getTotalWidth());
+
+ this.btns.el.shift({left: (width/2)-(bw/2)+scroll, top: h - 2, stopFx: true, duration:0.2});
+ }
+ },
+
+ // private
+ preEditValue : function(r, field){
+ var value = r.data[field];
+ return this.autoEncode && typeof value === 'string' ? Ext.util.Format.htmlDecode(value) : value;
+ },
+
+ // private
+ postEditValue : function(value, originalValue, r, field){
+ return this.autoEncode && typeof value == 'string' ? Ext.util.Format.htmlEncode(value) : value;
+ },
+
+ doFocus: function(pt){
+ if(this.isVisible()){
+ var index = 0,
+ cm = this.grid.getColumnModel(),
+ c;
+ if(pt){
+ index = this.getTargetColumnIndex(pt);
+ }
+ for(var i = index||0, len = cm.getColumnCount(); i < len; i++){
+ c = cm.getColumnAt(i);
+ if(!c.hidden && c.getEditor()){
+ c.getEditor().focus();
+ break;
+ }
+ }
+ }
+ },
+
+ getTargetColumnIndex: function(pt){
+ var grid = this.grid,
+ v = grid.view,
+ x = pt.left,
+ cms = grid.colModel.config,
+ i = 0,
+ match = false;
+ for(var len = cms.length, c; c = cms[i]; i++){
+ if(!c.hidden){
+ if(Ext.fly(v.getHeaderCell(i)).getRegion().right >= x){
+ match = i;
+ break;
+ }
+ }
+ }
+ return match;
+ },
+
+ startMonitoring : function(){
+ if(!this.bound && this.monitorValid){
+ this.bound = true;
+ Ext.TaskMgr.start({
+ run : this.bindHandler,
+ interval : this.monitorPoll || 200,
+ scope: this
+ });
+ }
+ },
+
+ stopMonitoring : function(){
+ this.bound = false;
+ if(this.tooltip){
+ this.tooltip.hide();
+ }
+ },
+
+ isValid: function(){
+ var valid = true;
+ this.items.each(function(f){
+ if(!f.isValid(true)){
+ valid = false;
+ return false;
+ }
+ });
+ return valid;
+ },
+
+ // private
+ bindHandler : function(){
+ if(!this.bound){
+ return false; // stops binding
+ }
+ var valid = this.isValid();
+ if(!valid && this.errorSummary){
+ this.showTooltip(this.getErrorText().join(''));
+ }
+ this.btns.saveBtn.setDisabled(!valid);
+ this.fireEvent('validation', this, valid);
+ },
+
+ lastVisibleColumn : function() {
+ var i = this.items.getCount() - 1,
+ c;
+ for(; i >= 0; i--) {
+ c = this.items.items[i];
+ if (!c.hidden) {
+ return c;
+ }
+ }
+ },
+
+ showTooltip: function(msg){
+ var t = this.tooltip;
+ if(!t){
+ t = this.tooltip = new Ext.ToolTip({
+ maxWidth: 600,
+ cls: 'errorTip',
+ width: 300,
+ title: this.errorText,
+ autoHide: false,
+ anchor: 'left',
+ anchorToTarget: true,
+ mouseOffset: [40,0]
+ });
+ }
+ var v = this.grid.getView(),
+ top = parseInt(this.el.dom.style.top, 10),
+ scroll = v.scroller.dom.scrollTop,
+ h = this.el.getHeight();
+
+ if(top + h >= scroll){
+ t.initTarget(this.lastVisibleColumn().getEl());
+ if(!t.rendered){
+ t.show();
+ t.hide();
+ }
+ t.body.update(msg);
+ t.doAutoWidth(20);
+ t.show();
+ }else if(t.rendered){
+ t.hide();
+ }
+ },
+
+ getErrorText: function(){
+ var data = ['<ul>'];
+ this.items.each(function(f){
+ if(!f.isValid(true)){
+ data.push('<li>', f.getActiveError(), '</li>');
+ }
+ });
+ data.push('</ul>');
+ return data;
+ }
+});
+Ext.preg('roweditor', Ext.ux.grid.RowEditor);