Upgrade to ExtJS 4.0.7 - Released 10/19/2011
[extjs.git] / src / util / Filter.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * Represents a filter that can be applied to a {@link Ext.util.MixedCollection MixedCollection}. Can either simply
17  * filter on a property/value pair or pass in a filter function with custom logic. Filters are always used in the
18  * context of MixedCollections, though {@link Ext.data.Store Store}s frequently create them when filtering and searching
19  * on their records. Example usage:
20  *
21  *     //set up a fictional MixedCollection containing a few people to filter on
22  *     var allNames = new Ext.util.MixedCollection();
23  *     allNames.addAll([
24  *         {id: 1, name: 'Ed',    age: 25},
25  *         {id: 2, name: 'Jamie', age: 37},
26  *         {id: 3, name: 'Abe',   age: 32},
27  *         {id: 4, name: 'Aaron', age: 26},
28  *         {id: 5, name: 'David', age: 32}
29  *     ]);
30  *
31  *     var ageFilter = new Ext.util.Filter({
32  *         property: 'age',
33  *         value   : 32
34  *     });
35  *
36  *     var longNameFilter = new Ext.util.Filter({
37  *         filterFn: function(item) {
38  *             return item.name.length > 4;
39  *         }
40  *     });
41  *
42  *     //a new MixedCollection with the 3 names longer than 4 characters
43  *     var longNames = allNames.filter(longNameFilter);
44  *
45  *     //a new MixedCollection with the 2 people of age 24:
46  *     var youngFolk = allNames.filter(ageFilter);
47  *
48  */
49 Ext.define('Ext.util.Filter', {
50
51     /* Begin Definitions */
52
53     /* End Definitions */
54     /**
55      * @cfg {String} property
56      * The property to filter on. Required unless a {@link #filterFn} is passed
57      */
58     
59     /**
60      * @cfg {Function} filterFn
61      * A custom filter function which is passed each item in the {@link Ext.util.MixedCollection} in turn. Should return
62      * true to accept each item or false to reject it
63      */
64     
65     /**
66      * @cfg {Boolean} anyMatch
67      * True to allow any match - no regex start/end line anchors will be added.
68      */
69     anyMatch: false,
70     
71     /**
72      * @cfg {Boolean} exactMatch
73      * True to force exact match (^ and $ characters added to the regex). Ignored if anyMatch is true.
74      */
75     exactMatch: false,
76     
77     /**
78      * @cfg {Boolean} caseSensitive
79      * True to make the regex case sensitive (adds 'i' switch to regex).
80      */
81     caseSensitive: false,
82     
83     /**
84      * @cfg {String} root
85      * Optional root property. This is mostly useful when filtering a Store, in which case we set the root to 'data' to
86      * make the filter pull the {@link #property} out of the data object of each item
87      */
88
89     /**
90      * Creates new Filter.
91      * @param {Object} [config] Config object
92      */
93     constructor: function(config) {
94         var me = this;
95         Ext.apply(me, config);
96         
97         //we're aliasing filter to filterFn mostly for API cleanliness reasons, despite the fact it dirties the code here.
98         //Ext.util.Sorter takes a sorterFn property but allows .sort to be called - we do the same here
99         me.filter = me.filter || me.filterFn;
100         
101         if (me.filter === undefined) {
102             if (me.property === undefined || me.value === undefined) {
103                 // Commented this out temporarily because it stops us using string ids in models. TODO: Remove this once
104                 // Model has been updated to allow string ids
105                 
106                 // Ext.Error.raise("A Filter requires either a property or a filterFn to be set");
107             } else {
108                 me.filter = me.createFilterFn();
109             }
110             
111             me.filterFn = me.filter;
112         }
113     },
114     
115     /**
116      * @private
117      * Creates a filter function for the configured property/value/anyMatch/caseSensitive options for this Filter
118      */
119     createFilterFn: function() {
120         var me       = this,
121             matcher  = me.createValueMatcher(),
122             property = me.property;
123         
124         return function(item) {
125             var value = me.getRoot.call(me, item)[property];
126             return matcher === null ? value === null : matcher.test(value);
127         };
128     },
129     
130     /**
131      * @private
132      * Returns the root property of the given item, based on the configured {@link #root} property
133      * @param {Object} item The item
134      * @return {Object} The root property of the object
135      */
136     getRoot: function(item) {
137         var root = this.root;
138         return root === undefined ? item : item[root];
139     },
140     
141     /**
142      * @private
143      * Returns a regular expression based on the given value and matching options
144      */
145     createValueMatcher : function() {
146         var me            = this,
147             value         = me.value,
148             anyMatch      = me.anyMatch,
149             exactMatch    = me.exactMatch,
150             caseSensitive = me.caseSensitive,
151             escapeRe      = Ext.String.escapeRegex;
152             
153         if (value === null) {
154             return value;
155         }
156         
157         if (!value.exec) { // not a regex
158             value = String(value);
159
160             if (anyMatch === true) {
161                 value = escapeRe(value);
162             } else {
163                 value = '^' + escapeRe(value);
164                 if (exactMatch === true) {
165                     value += '$';
166                 }
167             }
168             value = new RegExp(value, caseSensitive ? '' : 'i');
169          }
170          
171          return value;
172     }
173 });