Debian Codegraph @

dojox/grid/enhanced/plugins/filter/FilterLayer.js

raw symbols SCIP
1 define([
2 "dojo/_base/declare",
3 "dojo/_base/lang",
4 "dojo/_base/kernel",
5 "dojo/_base/json",
6 "../_StoreLayer"
7 ], function(declare, lang, kernel, json, layers){
8
9 var cmdSetFilter = "filter",
10 cmdClearFilter = "clear",
11 hitchIfCan = function(scope, func){
12 return func ? lang.hitch(scope || kernel.global, func) : function(){};
13 },
14 shallowClone = function(obj){
15 var res = {};
16 if(obj && lang.isObject(obj)){
17 for(var name in obj){
18 res[name] = obj[name];
19 }
20 }
21 return res;
22 };
23 var _FilterLayerMixin = declare("dojox.grid.enhanced.plugins.filter._FilterLayerMixin", null, {
24 /*=====
25 // _filter: _ConditionExpr
26 // The filter definition
27 _filter: null,
28
29 filterDef: function(filter){
30 // summary:
31 // Get/set/clear the filter definition
32 // tags:
33 // public
34 // filter: (_ConditionExpr|null)?
35 // - null: clear filter definition
36 // - undefined: it's getter
37 // returns:
38 // A filter definition if it's getter.
39 },
40 =====*/
41 tags: ["sizeChange"],
42 name: function(){
43 // summary:
44 // override from _StoreLayer.name
45 return "filter"; //string
46 },
47 onFilterDefined: function(filter){},
48
49 onFiltered: function(filteredSize, totalSize){
50 // summary:
51 // Called when store data is filtered. This event is before *onComplete*, after *onBegin*.
52 // tags:
53 // callback extension
54 // filteredSize: Integer
55 // The number of remaining fetched items after filtering.
56 // totalSize: Integer
57 // The number of original fetched items.
58 }
59 });
60 var ServerSideFilterLayer = declare("dojox.grid.enhanced.plugins.filter.ServerSideFilterLayer", [layers._ServerSideLayer, _FilterLayerMixin], {
61 constructor: function(args){
62 this._onUserCommandLoad = args.setupFilterQuery || this._onUserCommandLoad;
63 this.filterDef(null);
64 },
65 filterDef: function(/* (_ConditionExpr|null)? */filter){
66 // summary:
67 // See _FilterLayerMixin.filterDef
68 if(filter){
69 this._filter = filter;
70 var obj = filter.toObject();
71 //Stateless implementation will need to parse the filter object.
72 this.command(cmdSetFilter, this._isStateful ? json.toJson(obj) : obj);
73 this.command(cmdClearFilter, null);
74 this.useCommands(true);
75 this.onFilterDefined(filter);
76 }else if(filter === null){
77 this._filter = null;
78 this.command(cmdSetFilter, null);
79 this.command(cmdClearFilter, true);
80 this.useCommands(true);
81 this.onFilterDefined(null);
82 }
83 return this._filter; //_ConditionExpr
84 },
85 onCommandLoad: function(/* (in)string */responce, /* (in|out)keywordArgs */ userRequest){
86 // summary:
87 // override from _ServerSideLayer.onCommandLoad
88 this.inherited(arguments);
89 var oldOnBegin = userRequest.onBegin;
90 if(this._isStateful){
91 var filteredSize;
92 if(responce){
93 this.command(cmdSetFilter, null);
94 this.command(cmdClearFilter, null);
95 this.useCommands(false);
96 var sizes = responce.split(',');
97 if(sizes.length >= 2){
98 filteredSize = this._filteredSize = parseInt(sizes[0], 10);
99 this.onFiltered(filteredSize, parseInt(sizes[1], 10));
100 }else{
101 //Error here.
102 return;
103 }
104 }else{
105 filteredSize = this._filteredSize;
106 }
107 if(this.enabled()){
108 userRequest.onBegin = function(size, req){
109 hitchIfCan(userRequest.scope, oldOnBegin)(filteredSize, req);
110 };
111 }
112 }else{
113 var _this = this;
114 userRequest.onBegin = function(size, req){
115 if(!_this._filter){
116 _this._storeSize = size;
117 }
118 _this.onFiltered(size, _this._storeSize || size);
119 req.onBegin = oldOnBegin;
120 hitchIfCan(userRequest.scope, oldOnBegin)(size, req);
121 };
122 }
123 }
124 });
125 var ClientSideFilterLayer = declare("dojox.grid.enhanced.plugins.filter.ClientSideFilterLayer", [layers._StoreLayer, _FilterLayerMixin], {
126 // summary:
127 // Add a client side filter layer on top of the data store,
128 // so any filter expression can be applied to the store.
129 /*=====
130 // _items: Array,
131 // Cached items (may contain holes)
132 _items: [],
133
134 // _result: Array,
135 // Current fetch result
136 _result: [],
137
138 // _resultStartIdx: Integer,
139 // The index in cache of the first result item
140 _resultStartIdx: 0,
141
142 // _indexMap: Array,
143 // A map from the row index of this._items to the row index of the original store.
144 _indexMap: null,
145
146 // _getter: function(datarow, colArg, rowIndex, store);
147 // A user defined way to get data from store
148 _getter: null,
149
150 // _nextUnfetchedIdx: Integer
151 // The index of the next item in the store that is never fetched.
152 _nextUnfetchedIdx: 0,
153 =====*/
154 // _storeSize: Integer
155 // The actual size of the original store
156 _storeSize: -1,
157
158 // _fetchAll
159 // If the store is small or store size must be correct when onBegin is called,
160 // we should fetch and filter all the items on the first query.
161 _fetchAll: true,
162
163 constructor: function(args){
164 this.filterDef(null);
165 args = lang.isObject(args) ? args : {};
166 this.fetchAllOnFirstFilter(args.fetchAll);
167 this._getter = lang.isFunction(args.getter) ? args.getter : this._defaultGetter;
168 },
169 _defaultGetter: function(datarow, colName, rowIndex, store){
170 return store.getValue(datarow, colName);
171 },
172 filterDef: function(/* (_ConditionExpr|null)? */filter){
173 // summary:
174 // See _FilterLayerMixin.filterDef
175 if(filter !== undefined){
176 this._filter = filter;
177 this.invalidate();
178 this.onFilterDefined(filter);
179 }
180 return this._filter; //_ConditionExpr
181 },
182 setGetter: function(/* function */getter){
183 // summary:
184 // Set the user defined way to retrieve data from store.
185 // tags:
186 // public
187 // getter: function(datarow, colArg, rowIndex, store);
188 if(lang.isFunction(getter)){
189 this._getter = getter;
190 }
191 },
192 fetchAllOnFirstFilter: function(/* bool? */toFetchAll){
193 // summary:
194 // The get/set function for fetchAll.
195 // tags:
196 // public
197 // toFetchAll: boolean?
198 // If provided, it's a set function, otherwise it's a get function.
199 // returns:
200 // Whether fetch all on first filter if this is a getter
201 if(toFetchAll !== undefined){
202 this._fetchAll = !!toFetchAll;
203 }
204 return this._fetchAll; //Boolean
205 },
206 invalidate: function(){
207 // summary:
208 // Clear all the status information of this layer
209 // tags:
210 // private
211 this._items = [];
212 this._nextUnfetchedIdx = 0;
213 this._result = [];
214 this._indexMap = [];
215 this._resultStartIdx = 0;
216 },
217 //----------------Private Functions-----------------------------
218 _fetch: function(userRequest,filterRequest){
219 // summary:
220 // Implement _StoreLayer._fetch
221 // tags:
222 // private callback
223 // filterRequest: dojo/data/api/Request
224 // The actual request used in store.fetch.
225 // This function is called recursively to fill the result store items
226 // until the user specified item count is reached. Only in recursive calls,
227 // this parameter is valid.
228 if(!this._filter){
229 //If we don't have any filter, use the original request and fetch.
230 var old_onbegin = userRequest.onBegin, _this = this;
231 userRequest.onBegin = function(size, r){
232 hitchIfCan(userRequest.scope, old_onbegin)(size, r);
233 _this.onFiltered(size, size);
234 };
235 this.originFetch(userRequest);
236 return userRequest;
237 }
238 try{
239 //If the fetch is at the beginning, user's start position is used;
240 //If we are in a recursion, our own request is used.
241 var start = filterRequest ? filterRequest._nextResultItemIdx : userRequest.start;
242 start = start || 0;
243 if(!filterRequest){
244 //Initially, we have no results.
245 this._result = [];
246 this._resultStartIdx = start;
247 var sortStr;
248 if(lang.isArray(userRequest.sort) && userRequest.sort.length > 0 &&
249 //Sort info will stay here in every re-fetch, so remember it!
250 (sortStr = json.toJson(userRequest.sort)) != this._lastSortInfo){
251 //If we should sort data, all the old caches are no longer valid.
252 this.invalidate();
253 this._lastSortInfo = sortStr;
254 }
255 }
256 //this._result contains the current fetch result (of every recursion).
257 var end = typeof userRequest.count == "number" ?
258 start + userRequest.count - this._result.length : this._items.length;
259 //Try to retrieve all the items from our cache.
260 //Only need items after userRequest.start, test it in case start is smaller.
261 if(this._result.length){
262 this._result = this._result.concat(this._items.slice(start, end));
263 }else{
264 this._result = this._items.slice(userRequest.start, typeof userRequest.count == "number" ?
265 userRequest.start + userRequest.count : this._items.length);
266 }
267 if(this._result.length >= userRequest.count || this._hasReachedStoreEnd()){
268 //We already have had enough items, or we have to stop fetching because there's nothing more to fetch.
269 this._completeQuery(userRequest);
270 }else{
271 //User's request hasn't been finished yet. Fetch more.
272 if(!filterRequest){
273 //Initially, we've got to create a new request object.
274 filterRequest = shallowClone(userRequest);
275 //Use our own onBegin function to remember the total size of the original store.
276 filterRequest.onBegin = lang.hitch(this, this._onFetchBegin);
277 filterRequest.onComplete = lang.hitch(this, function(items, req){
278 //We've fetched some more, so march ahead!
279 this._nextUnfetchedIdx += items.length;
280 //Actual filtering work goes here. Survived items are added to our cache.
281 //req is our own request object.
282 this._doFilter(items, req.start, userRequest);
283 //Recursively call this function. Let's do this again!
284 this._fetch(userRequest, req);
285 });
286 }
287 //Fetch starts from the next unfetched item.
288 filterRequest.start = this._nextUnfetchedIdx;
289 //If store is small, we should only fetch once.
290 if(this._fetchAll){
291 delete filterRequest.count;
292 }
293 //Remember we've (maybe) already added something to our result array, so next time we should not start over again.
294 filterRequest._nextResultItemIdx = end < this._items.length ? end : this._items.length;
295 //Actual fetch work goes here.
296 this.originFetch(filterRequest);
297 }
298 }catch(e){
299 if(userRequest.onError){
300 hitchIfCan(userRequest.scope, userRequest.onError)(e, userRequest);
301 }else{
302 throw e;
303 }
304 }
305 return userRequest;
306 },
307 _hasReachedStoreEnd: function(){
308 // summary:
309 // Check whether all the items in the original store have been fetched.
310 // tags:
311 // private
312 return this._storeSize >= 0 && this._nextUnfetchedIdx >= this._storeSize; //Boolean
313 },
314 _applyFilter: function(/* data item */datarow,/* Integer */rowIndex){
315 // summary:
316 // Apply the filter to a row of data
317 // tags:
318 // private
319 // returns:
320 // whether this row survived the filter.
321 var g = this._getter, s = this._store;
322 try{
323 return !!(this._filter.applyRow(datarow, function(item, arg){
324 return g(item, arg, rowIndex, s);
325 }).getValue());
326 }catch(e){
327 console.warn("FilterLayer._applyFilter() error: ", e);
328 return false;
329 }
330 },
331 _doFilter: function(/* Array */items,/* Integer */startIdx,/* object */userRequest){
332 // summary:
333 // Use the filter expression to filter items. Survived items are stored in this._items.
334 // The given items start from "startIdx" in the original store.
335 // tags:
336 // private
337 for(var i = 0, cnt = 0; i < items.length; ++i){
338 if(this._applyFilter(items[i], startIdx + i)){
339 hitchIfCan(userRequest.scope, userRequest.onItem)(items[i], userRequest);
340 cnt += this._addCachedItems(items[i], this._items.length);
341 this._indexMap.push(startIdx + i);
342 }
343 }
344 },
345 _onFetchBegin: function(/* Integer */size,/* request object */req){
346 // summary:
347 // This function is used to replace the user's onFetchBegin in store.fetch
348 // tags:
349 // private
350 this._storeSize = size;
351 },
352 _completeQuery: function(/* request object */userRequest){
353 // summary:
354 // Logically, the user's query is completed here, i.e., all the filtered results are ready.
355 // (or their index mappings are ready)
356 // tags:
357 // private
358 var size = this._items.length;
359 if(this._nextUnfetchedIdx < this._storeSize){
360 //FIXME: There's still some items in the original store that are not fetched & filtered.
361 //So we have to estimate a little bigger size to allow scrolling to these unfetched items.
362 //However, this behavior is ONLY correct in Grid! Any better way to do this?
363 size++;
364 }
365 hitchIfCan(userRequest.scope, userRequest.onBegin)(size,userRequest);
366 this.onFiltered(this._items.length, this._storeSize);
367 hitchIfCan(userRequest.scope, userRequest.onComplete)(this._result, userRequest);
368 },
369 _addCachedItems: function(/* Array */items,/* Integer */filterStartIdx){
370 // summary:
371 // Add data items to the cache. The insert point is at *filterStartIdx*
372 // tags:
373 // private
374 // items: Array
375 // Data items to add.
376 // filterStartIdx: Integer
377 // The start point to insert in the cache.
378 if(!lang.isArray(items)){
379 items = [items];
380 }
381 for(var k = 0; k < items.length; ++k){
382 this._items[filterStartIdx + k] = items[k];
383 }
384 return items.length;
385 },
386 onRowMappingChange: function(mapping){
387 //This function runs in FilterLayer scope!
388 if(this._filter){
389 var m = lang.clone(mapping),
390 alreadyUpdated = {};
391 for(var r in m){
392 r = parseInt(r, 10);
393 mapping[this._indexMap[r]] = this._indexMap[m[r]];
394 if(!alreadyUpdated[this._indexMap[r]]){
395 alreadyUpdated[this._indexMap[r]] = true;
396 }
397 if(!alreadyUpdated[r]){
398 alreadyUpdated[r] = true;
399 delete mapping[r];
400 }
401 }
402 }
403 }
404 });
405
406 return lang.mixin({
407 ServerSideFilterLayer: ServerSideFilterLayer,
408 ClientSideFilterLayer: ClientSideFilterLayer
409 }, layers);
410 });