Debian Codegraph @

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

raw symbols SCIP
1 define([
2 "dojo/_base/declare",
3 "dojo/_base/array",
4 "dojo/_base/connect",
5 "dojo/_base/lang",
6 "dojo/_base/event",
7 "dojo/_base/html",
8 "dojo/_base/sniff",
9 "dojo/keys",
10 "dojo/on",
11 "dojo/string",
12 "dojo/window",
13 "dojo/date/locale",
14 "./FilterBuilder",
15 "../Dialog",
16 "dijit/form/ComboBox",
17 "dijit/form/TextBox",
18 "dijit/form/NumberTextBox",
19 "dijit/form/DateTextBox",
20 "dijit/form/TimeTextBox",
21 "dijit/form/Button",
22 "dijit/layout/AccordionContainer",
23 "dijit/layout/ContentPane",
24 "dijit/_Widget",
25 "dijit/_TemplatedMixin",
26 "dijit/_WidgetsInTemplateMixin",
27 "dijit/focus",
28 "dojox/html/metrics",
29 "dijit/a11y",
30 "dojo/text!../../templates/FilterDefPane.html",
31 "dojo/text!../../templates/CriteriaBox.html",
32 "dojo/text!../../templates/FilterBoolValueBox.html",
33 "dijit/Tooltip",
34 "dijit/form/Select",
35 "dijit/form/RadioButton",
36 "dojox/html/ellipsis",
37 "../../../cells/dijit"
38 ], function(declare, array, connect, lang, event, html, has, keys, on, string, win, dateLocale,
39 FilterBuilder, Dialog, ComboBox, TextBox, NumberTextBox, DateTextBox, TimeTextBox, Button,
40 AccordionContainer, ContentPane, _Widget, _TemplatedMixin, _WidgetsInTemplateMixin, dijitFocus,
41 metrics, dijitA11y, defPaneTemplate, criteriaTemplate, boolValueTemplate){
42
43 var _tabIdxes = {
44 // summary:
45 // Define tabindexes for elements in the filter definition dialog
46 relSelect: 60,
47 accordionTitle: 70,
48 removeCBoxBtn: -1,
49 colSelect: 90,
50 condSelect: 95,
51 valueBox: 10,
52 addCBoxBtn: 20,
53 filterBtn: 30,
54 clearBtn: 40,
55 cancelBtn: 50
56 };
57 var FilterAccordionContainer = declare("dojox.grid.enhanced.plugins.filter.AccordionContainer", AccordionContainer, {
58 nls: null,
59 addChild: function(/*dijit._Widget*/ child, /*Integer?*/ insertIndex){
60 var pane = arguments[0] = child._pane = new ContentPane({
61 content: child
62 });
63 this.inherited(arguments);
64 this._modifyChild(pane);
65 },
66 removeChild: function(child){
67 var pane = child, isRemoveByUser = false;
68 if(child._pane){
69 isRemoveByUser = true;
70 pane = arguments[0] = child._pane;
71 }
72 this.inherited(arguments);
73 if(isRemoveByUser){
74 this._hackHeight(false, this._titleHeight);
75 var children = this.getChildren();
76 if(children.length === 1){
77 html.style(children[0]._removeCBoxBtn.domNode, "display", "none");
78 }
79 }
80 pane.destroyRecursive();
81 },
82 selectChild: function(child){
83 if(child._pane){
84 arguments[0] = child._pane;
85 }
86 this.inherited(arguments);
87 },
88 resize: function(){
89 this.inherited(arguments);
90 array.forEach(this.getChildren(), this._setupTitleDom);
91 },
92 startup: function(){
93 if(this._started){
94 return;
95 }
96 this.inherited(arguments);
97 if(parseInt(has('ie'), 10) == 7){
98 //IE7 will fire a lot of "onresize" event during initialization.
99 array.some(this._connects, function(cnnt){
100 if((cnnt[0] || {})[1] == "onresize"){
101 this.disconnect(cnnt);
102 return true;
103 }
104 }, this);
105 }
106 array.forEach(this.getChildren(), function(child){
107 this._modifyChild(child, true);
108 }, this);
109 },
110 _onKeyPress: function(/*Event*/ e, /*dijit._Widget*/ fromTitle){
111 // summary:
112 // Overrides base class method, make left/right button do other things.
113 if(this.disabled || e.altKey || !(fromTitle || e.ctrlKey)){
114 return;
115 }
116 var k = keys, c = e.charOrCode, ltr = html._isBodyLtr(), toNext = null;
117 if((fromTitle && c == k.UP_ARROW) || (e.ctrlKey && c == k.PAGE_UP)){
118 toNext = false;
119 }else if((fromTitle && c == k.DOWN_ARROW) || (e.ctrlKey && (c == k.PAGE_DOWN || c == k.TAB))){
120 toNext = true;
121 }else if(c == (ltr ? k.LEFT_ARROW : k.RIGHT_ARROW)){
122 toNext = this._focusOnRemoveBtn ? null : false;
123 this._focusOnRemoveBtn = !this._focusOnRemoveBtn;
124 }else if(c == (ltr ? k.RIGHT_ARROW : k.LEFT_ARROW)){
125 toNext = this._focusOnRemoveBtn ? true : null;
126 this._focusOnRemoveBtn = !this._focusOnRemoveBtn;
127 }else{
128 return;
129 }
130 if(toNext !== null){
131 this._adjacent(toNext)._buttonWidget._onTitleClick();
132 }
133 event.stop(e);
134 win.scrollIntoView(this.selectedChildWidget._buttonWidget.domNode.parentNode);
135 if(has('ie')){
136 //IE will not show focus indicator if tabIndex is -1
137 this.selectedChildWidget._removeCBoxBtn.focusNode.setAttribute("tabIndex", this._focusOnRemoveBtn ? _tabIdxes.accordionTitle : -1);
138 }
139 dijitFocus.focus(this.selectedChildWidget[this._focusOnRemoveBtn ? "_removeCBoxBtn" : "_buttonWidget"].focusNode);
140 },
141 _modifyChild: function(child, isFirst){
142 if(!child || !this._started){
143 return;
144 }
145 html.style(child.domNode, "overflow", "hidden");
146 child._buttonWidget.connect(child._buttonWidget, "_setSelectedAttr", function(){
147 this.focusNode.setAttribute("tabIndex", this.selected ? _tabIdxes.accordionTitle : "-1");
148 });
149 var _this = this;
150 child._buttonWidget.connect(child._buttonWidget.domNode, "onclick", function(){
151 _this._focusOnRemoveBtn = false;
152 });
153 (child._removeCBoxBtn = new Button({
154 label: this.nls.removeRuleButton,
155 showLabel: false,
156 iconClass: "dojoxGridFCBoxRemoveCBoxBtnIcon",
157 tabIndex: _tabIdxes.removeCBoxBtn,
158 onClick: lang.hitch(child.content, "onRemove"),
159 onKeyPress: function(e){
160 _this._onKeyPress(e, child._buttonWidget.contentWidget);
161 }
162 })).placeAt(child._buttonWidget.domNode);
163 var i, children = this.getChildren();
164 if(children.length === 1){
165 child._buttonWidget.set("selected", true);
166 html.style(child._removeCBoxBtn.domNode, "display", "none");
167 }else{
168 for(i = 0; i < children.length; ++i){
169 if(children[i]._removeCBoxBtn){
170 html.style(children[i]._removeCBoxBtn.domNode, "display", "");
171 }
172 }
173 }
174 this._setupTitleDom(child);
175 if(!this._titleHeight){
176 for(i = 0; i < children.length; ++i){
177 if(children[i] != this.selectedChildWidget){
178 this._titleHeight = html.marginBox(children[i]._buttonWidget.domNode.parentNode).h;
179 break;
180 }
181 }
182 }
183 if(!isFirst){
184 this._hackHeight(true, this._titleHeight);
185 }
186 },
187 _hackHeight: function(/* bool */toGrow,/* int */heightDif){
188 var children = this.getChildren(),
189 dn = this.domNode, h = html.style(dn, "height");
190 if(!toGrow){
191 dn.style.height = (h - heightDif) + 'px';
192 }else if(children.length > 1){
193 dn.style.height = (h + heightDif) + 'px';
194 }else{
195 //Only one rule, no need to do anything.
196 return;
197 }
198 this.resize();
199 },
200 _setupTitleDom: function(child){
201 var w = html.contentBox(child._buttonWidget.titleNode).w;
202 if(has('ie') < 8){ w -= 8; }
203 html.style(child._buttonWidget.titleTextNode, "width", w + "px");
204 }
205 });
206 var FilterDefPane = declare("dojox.grid.enhanced.plugins.filter.FilterDefPane",[_Widget, _TemplatedMixin, _WidgetsInTemplateMixin],{
207 templateString: defPaneTemplate,
208 widgetsInTemplate: true,
209 dlg: null,
210 postMixInProperties: function(){
211 this.plugin = this.dlg.plugin;
212 var nls = this.plugin.nls;
213 this._addRuleBtnLabel = nls.addRuleButton;
214 this._cancelBtnLabel = nls.cancelButton;
215 this._clearBtnLabel = nls.clearButton;
216 this._filterBtnLabel = nls.filterButton;
217 this._relAll = nls.relationAll;
218 this._relAny = nls.relationAny;
219 this._relMsgFront = nls.relationMsgFront;
220 this._relMsgTail = nls.relationMsgTail;
221 },
222 postCreate: function(){
223 this.inherited(arguments);
224 // this.connect(this.domNode, "onkeypress", "_onKey");
225 on(this.domNode, "keydown", lang.hitch(this, "_onKey"));
226
227 (this.cboxContainer = new FilterAccordionContainer({
228 nls: this.plugin.nls
229 })).placeAt(this.criteriaPane);
230
231 this._relSelect.set("tabIndex", _tabIdxes.relSelect);
232 this._addCBoxBtn.set("tabIndex", _tabIdxes.addCBoxBtn);
233 this._cancelBtn.set("tabIndex", _tabIdxes.cancelBtn);
234 this._clearFilterBtn.set("tabIndex", _tabIdxes.clearBtn);
235 this._filterBtn.set("tabIndex", _tabIdxes.filterBtn);
236
237 var nls = this.plugin.nls;
238 this._relSelect.domNode.setAttribute("aria-label", nls.waiRelAll);
239 this._addCBoxBtn.domNode.setAttribute("aria-label", nls.waiAddRuleButton);
240 this._cancelBtn.domNode.setAttribute("aria-label", nls.waiCancelButton);
241 this._clearFilterBtn.domNode.setAttribute("aria-label", nls.waiClearButton);
242 this._filterBtn.domNode.setAttribute("aria-label", nls.waiFilterButton);
243
244 this._relSelect.set("value", this.dlg._relOpCls === "logicall" ? "0" : "1");
245 },
246 uninitialize: function(){
247 this.cboxContainer.destroyRecursive();
248 this.plugin = null;
249 this.dlg = null;
250 },
251 _onRelSelectChange: function(val){
252 this.dlg._relOpCls = val == "0" ? "logicall" : "logicany";
253 this._relSelect.domNode.setAttribute("aria-label", this.plugin.nls[val == "0" ? "waiRelAll" : "waiRelAny"]);
254 },
255 _onAddCBox: function(){
256 this.dlg.addCriteriaBoxes(1);
257 },
258 _onCancel: function(){
259 this.dlg.onCancel();
260 },
261 _onClearFilter: function(){
262 this.dlg.onClearFilter();
263 },
264 _onFilter: function(){
265 this.dlg.onFilter();
266 },
267 _onKey: function(e){
268 if(e.keyCode == keys.ENTER){
269 this.dlg.onFilter();
270 }
271 }
272 });
273 var CriteriaBox = declare("dojox.grid.enhanced.plugins.filter.CriteriaBox",[_Widget, _TemplatedMixin, _WidgetsInTemplateMixin],{
274 templateString: criteriaTemplate,
275 widgetsInTemplate: true,
276 dlg: null,
277 postMixInProperties: function(){
278 this.plugin = this.dlg.plugin;
279 this._curValueBox = null;
280
281 var nls = this.plugin.nls;
282 this._colSelectLabel = nls.columnSelectLabel;
283 this._condSelectLabel = nls.conditionSelectLabel;
284 this._valueBoxLabel = nls.valueBoxLabel;
285 this._anyColumnOption = nls.anyColumnOption;
286 },
287 postCreate: function(){
288 var dlg = this.dlg, g = this.plugin.grid;
289 //Select Column
290 this._colSelect.set("tabIndex", _tabIdxes.colSelect);
291 this._colOptions = this._getColumnOptions();
292 this._colSelect.addOption([
293 {label: this.plugin.nls.anyColumnOption, value: "anycolumn", selected: dlg.curColIdx < 0},
294 {value: ""}
295 ].concat(this._colOptions));
296 //Select Condition
297 this._condSelect.set("tabIndex", _tabIdxes.condSelect);
298 this._condSelect.addOption(this._getUsableConditions(dlg.getColumnType(dlg.curColIdx)));
299 this._showSelectOrLabel(this._condSelect, this._condSelectAlt);
300
301 this.connect(g.layout, "moveColumn", "onMoveColumn");
302 var _this = this;
303 setTimeout(function(){
304 var type = dlg.getColumnType(dlg.curColIdx);
305 _this._setValueBoxByType(type);
306 }, 0);
307 },
308 _getColumnOptions: function(){
309 var colIdx = this.dlg.curColIdx >= 0 ? String(this.dlg.curColIdx) : "anycolumn";
310 return array.map(array.filter(this.plugin.grid.layout.cells, function(cell){
311 return !(cell.filterable === false || cell.hidden);
312 }), function(cell){
313 return {
314 label: cell.name || cell.field,
315 value: String(cell.index),
316 selected: colIdx == String(cell.index)
317 };
318 });
319 },
320 onMoveColumn: function(){
321 var tmp = this._onChangeColumn;
322 this._onChangeColumn = function(){};
323 var option = this._colSelect.get("selectedOptions");
324 this._colSelect.removeOption(this._colOptions);
325 this._colOptions = this._getColumnOptions();
326 this._colSelect.addOption(this._colOptions);
327 var i = 0;
328 for(; i < this._colOptions.length; ++i){
329 if(this._colOptions[i].label == option.label){
330 break;
331 }
332 }
333 if(i < this._colOptions.length){
334 this._colSelect.set("value", this._colOptions[i].value);
335 }
336 var _this = this;
337 setTimeout(function(){
338 _this._onChangeColumn = tmp;
339 }, 0);
340 },
341 onRemove: function(){
342 this.dlg.removeCriteriaBoxes(this);
343 },
344 uninitialize: function(){
345 if(this._curValueBox){
346 this._curValueBox.destroyRecursive();
347 this._curValueBox = null;
348 }
349 this.plugin = null;
350 this.dlg = null;
351 },
352 _showSelectOrLabel: function(sel, alt){
353 var options = sel.getOptions();
354 if(options.length == 1){
355 alt.innerHTML = options[0].label;
356 html.style(sel.domNode, "display", "none");
357 html.style(alt, "display", "");
358 }else{
359 html.style(sel.domNode, "display", "");
360 html.style(alt, "display", "none");
361 }
362 },
363 _onChangeColumn: function(val){
364 this._checkValidCriteria();
365 var type = this.dlg.getColumnType(val);
366 this._setConditionsByType(type);
367 this._setValueBoxByType(type);
368 this._updateValueBox();
369 },
370 _onChangeCondition: function(val){
371 this._checkValidCriteria();
372 var f = (val == "range");
373 if(f ^ this._isRange){
374 this._isRange = f;
375 this._setValueBoxByType(this.dlg.getColumnType(this._colSelect.get("value")));
376 }
377 this._updateValueBox();
378 },
379 _updateValueBox: function(cond){
380 this._curValueBox.set("disabled", this._condSelect.get("value") == "isempty");
381 },
382 _checkValidCriteria: function(){
383 // summary:
384 // Check whether the given criteria box is completed. If it is, mark it.
385 setTimeout(lang.hitch(this, function(){
386 this.updateRuleTitle();
387 this.dlg._updatePane();
388 }),0);
389 },
390 _createValueBox: function(/* widget constructor */cls,/* object */arg){
391 // summary:
392 // Create a value input box with given class and arguments
393 var func = lang.hitch(arg.cbox, "_checkValidCriteria");
394 return new cls(lang.mixin(arg,{
395 tabIndex: _tabIdxes.valueBox,
396 onKeyPress: func,
397 onChange: func,
398 "class": "dojoxGridFCBoxValueBox"
399 }));
400 },
401 _createRangeBox: function(/* widget constructor */cls,/* object */arg){
402 // summary:
403 // Create a DIV containing 2 input widgets, which represents a range, with the given class and arguments
404 var func = lang.hitch(arg.cbox, "_checkValidCriteria");
405 lang.mixin(arg,{
406 tabIndex: _tabIdxes.valueBox,
407 onKeyPress: func,
408 onChange: func
409 });
410 var div = html.create("div", {"class": "dojoxGridFCBoxValueBox"}),
411 start = new cls(arg),
412 txt = html.create("span", {"class": "dojoxGridFCBoxRangeValueTxt", "innerHTML": this.plugin.nls.rangeTo}),
413 end = new cls(arg);
414 html.addClass(start.domNode, "dojoxGridFCBoxStartValue");
415 html.addClass(end.domNode, "dojoxGridFCBoxEndValue");
416 div.appendChild(start.domNode);
417 div.appendChild(txt);
418 div.appendChild(end.domNode);
419 div.domNode = div;
420 //Mock functions for set and get (in place of the old attr function)
421 div.set = function(dummy, args){
422 if(lang.isObject(args)){
423 start.set("value", args.start);
424 end.set("value", args.end);
425 }
426 };
427 div.get = function(){
428 var s = start.get("value"),
429 e = end.get("value");
430 return s && e ? {start: s, end: e} : "";
431 };
432 return div;
433 },
434 changeCurrentColumn: function(/* bool */selectCurCol){
435 var colIdx = this.dlg.curColIdx;
436 //Re-populate the columns in case some of them are set to hidden.
437 this._colSelect.removeOption(this._colOptions);
438 this._colOptions = this._getColumnOptions();
439 this._colSelect.addOption(this._colOptions);
440 this._colSelect.set('value', colIdx >= 0 ? String(colIdx) : "anycolumn");
441 this.updateRuleTitle(true);
442 },
443 curColumn: function(){
444 return this._colSelect.getOptions(this._colSelect.get("value")).label;
445 },
446 curCondition: function(){
447 return this._condSelect.getOptions(this._condSelect.get("value")).label;
448 },
449 curValue: function(){
450 var cond = this._condSelect.get("value");
451 if(cond == "isempty"){return "";}
452 return this._curValueBox ? this._curValueBox.get("value") : "";
453 },
454 save: function(){
455 if(this.isEmpty()){
456 return null;
457 }
458 var colIdx = this._colSelect.get("value"),
459 type = this.dlg.getColumnType(colIdx),
460 value = this.curValue(),
461 cond = this._condSelect.get("value");
462 return {
463 "column": colIdx,
464 "condition": cond,
465 "value": value,
466 "formattedVal": this.formatValue(type, cond, value),
467 "type": type,
468 "colTxt": this.curColumn(),
469 "condTxt": this.curCondition()
470 };
471 },
472 load: function(obj){
473 var tmp = [
474 this._onChangeColumn,
475 this._onChangeCondition
476 ];
477 this._onChangeColumn = this._onChangeCondition = function(){};
478 if(obj.column){
479 this._colSelect.set("value", obj.column);
480 }
481 if(obj.type){
482 this._setConditionsByType(obj.type);
483 this._setValueBoxByType(obj.type);
484 }else{
485 obj.type = this.dlg.getColumnType(this._colSelect.get("value"));
486 }
487 if(obj.condition){
488 this._condSelect.set("value", obj.condition);
489 }
490 var value = obj.value || "";
491 if(value || (obj.type != "date" && obj.type != "time")){
492 this._curValueBox.set("value", value);
493 }
494 this._updateValueBox();
495 setTimeout(lang.hitch(this, function(){
496 this._onChangeColumn = tmp[0];
497 this._onChangeCondition = tmp[1];
498 }), 0);
499 },
500 getExpr: function(){
501 if(this.isEmpty()){
502 return null;
503 }
504 var colval = this._colSelect.get("value");
505 return this.dlg.getExprForCriteria({
506 "type": this.dlg.getColumnType(colval),
507 "column": colval,
508 "condition": this._condSelect.get("value"),
509 "value": this.curValue()
510 });
511 },
512 isEmpty: function(){
513 var cond = this._condSelect.get("value");
514 if(cond == "isempty"){return false;}
515 var v = this.curValue();
516 return v === "" || v === null || typeof v == "undefined" || (typeof v == "number" && isNaN(v));
517 },
518 updateRuleTitle: function(isEmpty){
519 var node = this._pane._buttonWidget.titleTextNode;
520 var title = [
521 "<div class='dojoxEllipsis'>"
522 ];
523 if(isEmpty || this.isEmpty()){
524 node.title = string.substitute(this.plugin.nls.ruleTitleTemplate, [this._ruleIndex || 1]);
525 title.push(node.title);
526 }else{
527 var type = this.dlg.getColumnType(this._colSelect.get("value"));
528 var column = this.curColumn();
529 var condition = this.curCondition();
530 var value = this.formatValue(type, this._condSelect.get("value"), this.curValue());
531 title.push(
532 column,
533 "&nbsp;<span class='dojoxGridRuleTitleCondition'>",
534 condition,
535 "</span>&nbsp;",
536 value
537 );
538 node.title = [column, " ", condition, " ", value].join('');
539 }
540 node.innerHTML = title.join('');
541 if(has('mozilla')){
542 var tt = html.create("div", {
543 "style": "width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: 9999;"
544 }, node);
545 tt.title = node.title;
546 }
547 },
548 updateRuleIndex: function(index){
549 if(this._ruleIndex != index){
550 this._ruleIndex = index;
551 if(this.isEmpty()){
552 this.updateRuleTitle();
553 }
554 }
555 },
556 setAriaInfo: function(idx){
557 var dss = string.substitute, nls = this.plugin.nls;
558 this._colSelect.domNode.setAttribute("aria-label", dss(nls.waiColumnSelectTemplate, [idx]));
559 this._condSelect.domNode.setAttribute("aria-label", dss(nls.waiConditionSelectTemplate, [idx]));
560 this._pane._removeCBoxBtn.domNode.setAttribute("aria-label", dss(nls.waiRemoveRuleButtonTemplate, [idx]));
561 this._index = idx;
562 },
563 _getUsableConditions: function(type){
564 var conditions = lang.clone(this.dlg._dataTypeMap[type].conditions);
565 var typeDisabledConds = (this.plugin.args.disabledConditions || {})[type];
566 var colIdx = parseInt(this._colSelect.get("value"), 10);
567 var colDisabledConds = isNaN(colIdx) ?
568 (this.plugin.args.disabledConditions || {})["anycolumn"] :
569 this.plugin.grid.layout.cells[colIdx].disabledConditions;
570 if(!lang.isArray(typeDisabledConds)){
571 typeDisabledConds = [];
572 }
573 if(!lang.isArray(colDisabledConds)){
574 colDisabledConds = [];
575 }
576 var arr = typeDisabledConds.concat(colDisabledConds);
577 if(arr.length){
578 var disabledConds = {};
579 array.forEach(arr, function(c){
580 if(lang.isString(c)){
581 disabledConds[c.toLowerCase()] = true;
582 }
583 });
584 return array.filter(conditions, function(condOption){
585 return !(condOption.value in disabledConds);
586 });
587 }
588 return conditions;
589 },
590 _setConditionsByType: function(/* string */type){
591 var condSelect = this._condSelect;
592 condSelect.removeOption(condSelect.options);
593 condSelect.addOption(this._getUsableConditions(type));
594 this._showSelectOrLabel(this._condSelect, this._condSelectAlt);
595 },
596 _setValueBoxByType: function(/* string */type){
597 if(this._curValueBox){
598 this.valueNode.removeChild(this._curValueBox.domNode);
599 try{
600 this._curValueBox.destroyRecursive();
601 }catch(e){}
602 delete this._curValueBox;
603 }
604 //value box class
605 var vbcls = this.dlg._dataTypeMap[type].valueBoxCls[this._getValueBoxClsInfo(this._colSelect.get("value"), type)],
606 vboxArg = this._getValueBoxArgByType(type);
607 this._curValueBox = this[this._isRange ? "_createRangeBox" : "_createValueBox"](vbcls, vboxArg);
608 this.valueNode.appendChild(this._curValueBox.domNode);
609
610 //Can not move to setAriaInfo, 'cause the value box is created after the defpane is loaded.
611 this._curValueBox.focusNode.setAttribute("aria-label", string.substitute(this.plugin.nls.waiValueBoxTemplate,[this._index]));
612 //Now our cbox is completely ready
613 this.dlg.onRendered(this);
614 },
615 //--------------------------UI Configuration--------------------------------------
616 _getValueBoxArgByType: function(/* string */type){
617 // summary:
618 // Get the arguments for the value box construction.
619 var g = this.plugin.grid,
620 cell = g.layout.cells[parseInt(this._colSelect.get("value"), 10)],
621 res = {
622 cbox: this
623 };
624 if(type == "string"){
625 if(cell && (cell.suggestion || cell.autoComplete)){
626 lang.mixin(res, {
627 store: g.store,
628 searchAttr: cell.field || cell.name,
629 query: g.query || {},
630 fetchProperties: {
631 sort: [{"attribute": cell.field || cell.name}],
632 queryOptions: lang.mixin({
633 ignoreCase: true,
634 deep: true
635 }, g.queryOptions || {})
636 }
637 });
638 }
639 }else if(type == "boolean"){
640 lang.mixin(res, this.dlg.builder.defaultArgs["boolean"]);
641 }
642 if(cell && cell.dataTypeArgs){
643 lang.mixin(res, cell.dataTypeArgs);
644 }
645 return res;
646 },
647 formatValue: function(type, cond, v){
648 // summary:
649 // Format the value to be shown in tooltip.
650 if(cond == "isempty"){return "";}
651 if(type == "date" || type == "time"){
652 var opt = {selector: type},
653 fmt = dateLocale.format;
654 if(cond == "range"){
655 return string.substitute(this.plugin.nls.rangeTemplate, [fmt(v.start, opt), fmt(v.end, opt)]);
656 }
657 return fmt(v, opt);
658 }else if(type == "boolean"){
659 return v ? this._curValueBox._lblTrue : this._curValueBox._lblFalse;
660 }
661 return v;
662 },
663 _getValueBoxClsInfo: function(/* int|string */colIndex, /* string */type){
664 // summary:
665 // Decide which value box to use given data type and column index.
666 var cell = this.plugin.grid.layout.cells[parseInt(colIndex, 10)];
667 //Now we only need to handle string. But maybe we need to handle more types here in the future.
668 if(type == "string"){
669 return (cell && (cell.suggestion || cell.autoComplete)) ? "ac" : "dft";
670 }
671 return "dft";
672 }
673 });
674
675
676 var UniqueComboBox = declare("dojox.grid.enhanced.plugins.filter.UniqueComboBox", ComboBox, {
677 _openResultList: function(results){
678 var cache = {}, s = this.store, colName = this.searchAttr;
679 arguments[0] = array.filter(results, function(item){
680 var key = s.getValue(item, colName), existed = cache[key];
681 cache[key] = true;
682 return !existed;
683 });
684 this.inherited(arguments);
685 },
686 _onKey: function(evt){
687 if(evt.charOrCode === keys.ENTER && this._opened){
688 event.stop(evt);
689 }
690 this.inherited(arguments);
691 }
692 });
693 var BooleanValueBox = declare("dojox.grid.enhanced.plugins.filter.BooleanValueBox", [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
694 templateString: boolValueTemplate,
695 widgetsInTemplate: true,
696 constructor: function(args){
697 var nls = args.cbox.plugin.nls;
698 this._baseId = args.cbox.id;
699 this._lblTrue = args.trueLabel || nls.trueLabel || "true";
700 this._lblFalse = args.falseLabel || nls.falseLabel || "false";
701 this.args = args;
702 },
703 postCreate: function(){
704 this.onChange();
705 },
706 onChange: function(){},
707
708 get: function(prop){
709 return this.rbTrue.get("checked");
710 },
711 set: function(prop, v){
712 this.inherited(arguments);
713 if(prop == "value"){
714 this.rbTrue.set("checked", !!v);
715 this.rbFalse.set("checked", !v);
716 }
717 }
718 });
719 var FilterDefDialog = declare("dojox.grid.enhanced.plugins.filter.FilterDefDialog", null, {
720 // summary:
721 // Create the filter definition UI.
722 curColIdx: -1,
723 _relOpCls: "logicall",
724 _savedCriterias: null,
725 plugin: null,
726 constructor: function(args){
727 var plugin = this.plugin = args.plugin;
728 this.builder = new FilterBuilder();
729 this._setupData();
730 this._cboxes = [];
731 this.defaultType = plugin.args.defaultType || "string";
732
733 (this.filterDefPane = new FilterDefPane({
734 "dlg": this
735 })).startup();
736 (this._defPane = new Dialog({
737 "refNode": this.plugin.grid.domNode,
738 "title": plugin.nls.filterDefDialogTitle,
739 "class": "dojoxGridFDTitlePane",
740 "iconClass": "dojoxGridFDPaneIcon",
741 "content": this.filterDefPane
742 })).startup();
743
744 this._defPane.connect(plugin.grid.layer('filter'), "filterDef", lang.hitch(this, "_onSetFilter"));
745 plugin.grid.setFilter = lang.hitch(this, "setFilter");
746 plugin.grid.getFilter = lang.hitch(this, "getFilter");
747 plugin.grid.getFilterRelation = lang.hitch(this, function(){
748 return this._relOpCls;
749 });
750
751 plugin.connect(plugin.grid.layout, "moveColumn", lang.hitch(this, "onMoveColumn"));
752 },
753 onMoveColumn: function(sourceViewIndex, destViewIndex, cellIndex, targetIndex, before){
754 if(this._savedCriterias && cellIndex != targetIndex){
755 if(before){ --targetIndex; }
756 var min = cellIndex < targetIndex ? cellIndex : targetIndex;
757 var max = cellIndex < targetIndex ? targetIndex : cellIndex;
758 var dir = targetIndex > min ? 1 : -1;
759 array.forEach(this._savedCriterias, function(sc){
760 var idx = parseInt(sc.column, 10);
761 if(!isNaN(idx) && idx >= min && idx <= max){
762 sc.column = String(idx == cellIndex ? idx + (max - min) * dir : idx - dir);
763 }
764 });
765 }
766 },
767 destroy: function(){
768 this._defPane.destroyRecursive();
769 this._defPane = null;
770 this.filterDefPane = null;
771 this.builder = null;
772 this._dataTypeMap = null;
773 this._cboxes = null;
774 var g = this.plugin.grid;
775 g.setFilter = null;
776 g.getFilter = null;
777 g.getFilterRelation = null;
778 this.plugin = null;
779 },
780 _setupData: function(){
781 var nls = this.plugin.nls;
782 this._dataTypeMap = {
783 // summary:
784 // All supported data types
785 "number":{
786 valueBoxCls: {
787 dft: NumberTextBox
788 },
789 conditions:[
790 {label: nls.conditionEqual, value: "equalto", selected: true},
791 {label: nls.conditionNotEqual, value: "notequalto"},
792 {label: nls.conditionLess, value: "lessthan"},
793 {label: nls.conditionLessEqual, value: "lessthanorequalto"},
794 {label: nls.conditionLarger, value: "largerthan"},
795 {label: nls.conditionLargerEqual, value: "largerthanorequalto"},
796 {label: nls.conditionIsEmpty, value: "isempty"}
797 ]
798 },
799 "string":{
800 valueBoxCls: {
801 dft: TextBox,
802 ac: UniqueComboBox //For autoComplete
803 },
804 conditions:[
805 {label: nls.conditionContains, value: "contains", selected: true},
806 {label: nls.conditionIs, value: "equalto"},
807 {label: nls.conditionStartsWith, value: "startswith"},
808 {label: nls.conditionEndWith, value: "endswith"},
809 {label: nls.conditionNotContain, value: "notcontains"},
810 {label: nls.conditionIsNot, value: "notequalto"},
811 {label: nls.conditionNotStartWith, value: "notstartswith"},
812 {label: nls.conditionNotEndWith, value: "notendswith"},
813 {label: nls.conditionIsEmpty, value: "isempty"}
814 ]
815 },
816 "date":{
817 valueBoxCls: {
818 dft: DateTextBox
819 },
820 conditions:[
821 {label: nls.conditionIs, value: "equalto", selected: true},
822 {label: nls.conditionBefore, value: "lessthan"},
823 {label: nls.conditionAfter, value: "largerthan"},
824 {label: nls.conditionRange, value: "range"},
825 {label: nls.conditionIsEmpty, value: "isempty"}
826 ]
827 },
828 "time":{
829 valueBoxCls: {
830 dft: TimeTextBox
831 },
832 conditions:[
833 {label: nls.conditionIs, value: "equalto", selected: true},
834 {label: nls.conditionBefore, value: "lessthan"},
835 {label: nls.conditionAfter, value: "largerthan"},
836 {label: nls.conditionRange, value: "range"},
837 {label: nls.conditionIsEmpty, value: "isempty"}
838 ]
839 },
840 "boolean": {
841 valueBoxCls: {
842 dft: BooleanValueBox
843 },
844 conditions: [
845 {label: nls.conditionIs, value: "equalto", selected: true},
846 {label: nls.conditionIsEmpty, value: "isempty"}
847 ]
848 }
849 };
850 },
851 setFilter: function(rules, ruleRelation){
852 rules = rules || [];
853 if(!lang.isArray(rules)){
854 rules = [rules];
855 }
856 var func = function(){
857 if(rules.length){
858 this._savedCriterias = array.map(rules, function(rule){
859 var type = rule.type || this.defaultType;
860 return {
861 "type": type,
862 "column": String(rule.column),
863 "condition": rule.condition,
864 "value": rule.value,
865 "colTxt": this.getColumnLabelByValue(String(rule.column)),
866 "condTxt": this.getConditionLabelByValue(type, rule.condition),
867 "formattedVal": rule.formattedVal || rule.value
868 };
869 }, this);
870 this._criteriasChanged = true;
871 if(ruleRelation === "logicall" || ruleRelation === "logicany"){
872 this._relOpCls = ruleRelation;
873 }
874 var exprs = array.map(rules, this.getExprForCriteria, this);
875 exprs = this.builder.buildExpression(exprs.length == 1 ? exprs[0] : {
876 "op": this._relOpCls,
877 "data": exprs
878 });
879 this.plugin.grid.layer("filter").filterDef(exprs);
880 this.plugin.filterBar.toggleClearFilterBtn(false);
881 }
882 this._closeDlgAndUpdateGrid();
883 };
884 if(this._savedCriterias){
885 this._clearWithoutRefresh = true;
886 var handle = connect.connect(this, "clearFilter", this, function(){
887 connect.disconnect(handle);
888 this._clearWithoutRefresh = false;
889 func.apply(this);
890 });
891 this.onClearFilter();
892 }else{
893 func.apply(this);
894 }
895 },
896 getFilter: function(){
897 return lang.clone(this._savedCriterias) || [];
898 },
899 getColumnLabelByValue: function(v){
900 var nls = this.plugin.nls;
901 if(v.toLowerCase() == "anycolumn"){
902 return nls["anyColumnOption"];
903 }else{
904 var cell = this.plugin.grid.layout.cells[parseInt(v, 10)];
905 return cell ? (cell.name || cell.field) : "";
906 }
907 },
908 getConditionLabelByValue: function(type, c){
909 var conditions = this._dataTypeMap[type].conditions;
910 for(var i = conditions.length - 1; i >= 0; --i){
911 var cond = conditions[i];
912 if(cond.value == c.toLowerCase()){
913 return cond.label;
914 }
915 }
916 return "";
917 },
918 addCriteriaBoxes: function(/* int */cnt){
919 // summary:
920 // Add *cnt* criteria boxes to the filter definition pane.
921 // Check overflow if necessary.
922 if(typeof cnt != "number" || cnt <= 0){
923 return;
924 }
925 var cbs = this._cboxes,
926 cc = this.filterDefPane.cboxContainer,
927 total = this.plugin.args.ruleCount,
928 len = cbs.length, cbox;
929 //If overflow, add to max rule count.
930 if(total > 0 && len + cnt > total){
931 cnt = total - len;
932 }
933 for(; cnt > 0; --cnt){
934 cbox = new CriteriaBox({
935 dlg: this
936 });
937 cbs.push(cbox);
938 cc.addChild(cbox);
939 }
940 //If there's no content box in it , AccordionContainer can not startup
941 cc.startup();
942 this._updatePane();
943 this._updateCBoxTitles();
944 cc.selectChild(cbs[cbs.length-1]);
945 //Asign an impossibly large scrollTop to scroll the criteria pane to the bottom.
946 this.filterDefPane.criteriaPane.scrollTop = 1000000;
947 if(cbs.length === 4){
948 if(has('ie') <= 6 && !this.__alreadyResizedForIE6){
949 var size = html.position(cc.domNode);
950 size.w -= metrics.getScrollbar().w;
951 cc.resize(size);
952 this.__alreadyResizedForIE6 = true;
953 }else{
954 cc.resize();
955 }
956 }
957 },
958 removeCriteriaBoxes: function(/* int|CriteriaBox|int[] */cnt,/* bool? */isIdx){
959 // summary:
960 // Remove criteria boxes from the filter definition pane.
961 var cbs = this._cboxes, cc = this.filterDefPane.cboxContainer,
962 len = cbs.length, start = len - cnt,
963 end = len - 1, cbox,
964 curIdx = array.indexOf(cbs, cc.selectedChildWidget.content);
965 if(lang.isArray(cnt)){
966 var i, idxes = cnt;
967 idxes.sort();
968 cnt = idxes.length;
969 //find a rule that's not deleted.
970 //must find and focus the last one, or the hack will not work.
971 for(i = len - 1; i >= 0 && array.indexOf(idxes, i) >= 0; --i){}
972 if(i >= 0){
973 //must select before remove
974 if(i != curIdx){
975 cc.selectChild(cbs[i]);
976 }
977 //idxes is sorted from small to large,
978 //so travel reversely won't need change index after delete from array.
979 for(i = cnt-1; i >= 0; --i){
980 if(idxes[i] >= 0 && idxes[i] < len){
981 cc.removeChild(cbs[idxes[i]]);
982 cbs.splice(idxes[i],1);
983 }
984 }
985 }
986 start = cbs.length;
987 }else{
988 if(isIdx === true){
989 if(cnt >= 0 && cnt < len){
990 start = end = cnt;
991 cnt = 1;
992 }else{
993 return;
994 }
995 }else{
996 if(cnt instanceof CriteriaBox){
997 cbox = cnt;
998 cnt = 1;
999 start = end = array.indexOf(cbs, cbox);
1000 }else if(typeof cnt != "number" || cnt <= 0){
1001 return;
1002 }else if(cnt >= len){
1003 cnt = end;
1004 start = 1;
1005 }
1006 }
1007 if(end < start){
1008 return;
1009 }
1010 //must select before remove
1011 if(curIdx >= start && curIdx <= end){
1012 cc.selectChild(cbs[start ? start-1 : end+1]);
1013 }
1014 for(; end >= start; --end){
1015 cc.removeChild(cbs[end]);
1016 }
1017 cbs.splice(start, cnt);
1018 }
1019 this._updatePane();
1020 this._updateCBoxTitles();
1021 if(cbs.length === 3){
1022 //In ie6, resize back to the normal width will cause the title button look strange.
1023 cc.resize();
1024 }
1025 },
1026 getCriteria: function(/* int */idx){
1027 // summary:
1028 // Get the *idx*-th criteria.
1029 if(typeof idx != "number"){
1030 return this._savedCriterias ? this._savedCriterias.length : 0;
1031 }
1032 if(this._savedCriterias && this._savedCriterias[idx]){
1033 return lang.mixin({
1034 relation: this._relOpCls == "logicall" ? this.plugin.nls.and : this.plugin.nls.or
1035 },this._savedCriterias[idx]);
1036 }
1037 return null;
1038 },
1039 getExprForCriteria: function(rule){
1040 if(rule.column == "anycolumn"){
1041 var cells = array.filter(this.plugin.grid.layout.cells, function(cell){
1042 return !(cell.filterable === false || cell.hidden);
1043 });
1044 return {
1045 "op": "logicany",
1046 "data": array.map(cells, function(cell){
1047 return this.getExprForColumn(rule.value, cell.index, rule.type, rule.condition);
1048 }, this)
1049 };
1050 }else{
1051 return this.getExprForColumn(rule.value, rule.column, rule.type, rule.condition);
1052 }
1053 },
1054 getExprForColumn: function(value, colIdx, type, condition){
1055 colIdx = parseInt(colIdx, 10);
1056 var cell = this.plugin.grid.layout.cells[colIdx],
1057 colName = cell.field || cell.name,
1058 obj = {
1059 "datatype": type || this.getColumnType(colIdx),
1060 "args": cell.dataTypeArgs,
1061 "isColumn": true
1062 },
1063 operands = [lang.mixin({"data": this.plugin.args.isServerSide ? colName : cell}, obj)];
1064 obj.isColumn = false;
1065 if(condition == "range"){
1066 operands.push(lang.mixin({"data": value.start}, obj),
1067 lang.mixin({"data": value.end}, obj));
1068 }else if(condition != "isempty"){
1069 operands.push(lang.mixin({"data": value}, obj));
1070 }
1071 return {
1072 "op": condition,
1073 "data": operands
1074 };
1075 },
1076 getColumnType: function(/* int */colIndex){
1077 var cell = this.plugin.grid.layout.cells[parseInt(colIndex, 10)];
1078 if(!cell || !cell.datatype){
1079 return this.defaultType;
1080 }
1081 var type = String(cell.datatype).toLowerCase();
1082 return this._dataTypeMap[type] ? type : this.defaultType;
1083 },
1084 //////////////////////////////////////////////////////////////////////////////////////////////////////////
1085 clearFilter: function(noRefresh){
1086 // summary:
1087 // Clear filter definition.
1088 if(!this._savedCriterias){
1089 return;
1090 }
1091 this._savedCriterias = null;
1092 this.plugin.grid.layer("filter").filterDef(null);
1093 try{
1094 this.plugin.filterBar.toggleClearFilterBtn(true);
1095 this.filterDefPane._clearFilterBtn.set("disabled", true);
1096 this.removeCriteriaBoxes(this._cboxes.length-1);
1097 this._cboxes[0].load({});
1098 }catch(e){
1099 //Any error means the filter is defined outside this plugin.
1100 }
1101 if(noRefresh){
1102 this.closeDialog();
1103 }else{
1104 this._closeDlgAndUpdateGrid();
1105 }
1106 },
1107 showDialog: function(/* int */colIndex){
1108 // summary:
1109 // Show the filter definition dialog.
1110 this._defPane.show();
1111 this.plugin.filterStatusTip.closeDialog();
1112 this._prepareDialog(colIndex);
1113 },
1114 closeDialog: function(){
1115 // summary:
1116 // Close the filter definition dialog.
1117 if(this._defPane.open){
1118 this._defPane.hide();
1119 }
1120 },
1121 onFilter: function(e){
1122 // summary:
1123 // Triggered when the "Filter" button is clicked.
1124 if(this.canFilter()){
1125 this._defineFilter();
1126 this._closeDlgAndUpdateGrid();
1127 this.plugin.filterBar.toggleClearFilterBtn(false);
1128 }
1129 },
1130 onClearFilter: function(e){
1131 // summary:
1132 // Triggered when the "Clear" button is clicked.
1133 if(this._savedCriterias){
1134 if(this._savedCriterias.length >= this.plugin.ruleCountToConfirmClearFilter){
1135 this.plugin.clearFilterDialog.show();
1136 }else{
1137 this.clearFilter(this._clearWithoutRefresh);
1138 }
1139 }
1140 },
1141 onCancel: function(e){
1142 // summary:
1143 // Triggered when the "Cancel" buttton is clicked.
1144 var sc = this._savedCriterias;
1145 var cbs = this._cboxes;
1146 if(sc){
1147 this.addCriteriaBoxes(sc.length - cbs.length);
1148 this.removeCriteriaBoxes(cbs.length - sc.length);
1149 array.forEach(sc, function(c, i){
1150 cbs[i].load(c);
1151 });
1152 }else{
1153 this.removeCriteriaBoxes(cbs.length - 1);
1154 cbs[0].load({});
1155 }
1156 this.closeDialog();
1157 },
1158 onRendered: function(cbox){
1159 // summary:
1160 // Triggered when the rendering of the filter definition dialog is completely finished.
1161 // cbox:
1162 // Current visible criteria box
1163 if(!has('ff')){
1164 var elems = dijitA11y._getTabNavigable(html.byId(cbox.domNode));
1165 dijitFocus.focus(elems.lowest || elems.first);
1166 }else{
1167 var dp = this._defPane;
1168 dp._getFocusItems(dp.domNode);
1169 dijitFocus.focus(dp._firstFocusItem);
1170 }
1171 },
1172 _onSetFilter: function(filterDef){
1173 // summary:
1174 // If someone clear the filter def in the store directly, we must clear it in the UI.
1175 // If someone defines a filter, don't know how to handle it!
1176 if(filterDef === null && this._savedCriterias){
1177 this.clearFilter();
1178 }
1179 },
1180 _prepareDialog: function(/* int */colIndex){
1181 var sc = this._savedCriterias,
1182 cbs = this._cboxes, i, cbox;
1183 this.curColIdx = colIndex;
1184 if(!sc){
1185 if(cbs.length === 0){
1186 this.addCriteriaBoxes(1);
1187 }else{
1188 //Re-populate columns anyway, because we don't know when the column is set to hidden.
1189 for(i = 0; (cbox = cbs[i]); ++i){
1190 cbox.changeCurrentColumn();
1191 }
1192 }
1193 }else if(this._criteriasChanged){
1194 this.filterDefPane._relSelect.set("value", this._relOpCls === "logicall" ? "0" : "1");
1195 this._criteriasChanged = false;
1196 var needNewCBox = sc.length > cbs.length ? sc.length - cbs.length : 0;
1197 this.addCriteriaBoxes(needNewCBox);
1198 this.removeCriteriaBoxes(cbs.length - sc.length);
1199 this.filterDefPane._clearFilterBtn.set("disabled", false);
1200 for(i = 0; i < cbs.length - needNewCBox; ++i){
1201 cbs[i].load(sc[i]);
1202 }
1203 if(needNewCBox > 0){
1204 var handled = [], handle = connect.connect(this, "onRendered", function(cbox){
1205 var i = array.indexOf(cbs, cbox);
1206 if(!handled[i]){
1207 handled[i] = true;
1208 if(--needNewCBox === 0){
1209 connect.disconnect(handle);
1210 }
1211 cbox.load(sc[i]);
1212 }
1213 });
1214 }
1215 }
1216 //Since we're allowed to remove cboxes when the definition pane is not shown,
1217 //we have to resize the container to have a correct _verticalSpace.
1218 this.filterDefPane.cboxContainer.resize();
1219 },
1220 _defineFilter: function(){
1221 var cbs = this._cboxes,
1222 filterCboxes = function(method){
1223 return array.filter(array.map(cbs, function(cbox){
1224 return cbox[method]();
1225 }), function(result){
1226 return !!result;
1227 });
1228 },
1229 exprs = filterCboxes("getExpr");
1230 this._savedCriterias = filterCboxes("save");
1231 exprs = exprs.length == 1 ? exprs[0] : {
1232 "op": this._relOpCls,
1233 "data": exprs
1234 };
1235 exprs = this.builder.buildExpression(exprs);
1236
1237 this.plugin.grid.layer("filter").filterDef(exprs);
1238 this.filterDefPane._clearFilterBtn.set("disabled", false);
1239 },
1240 _updateCBoxTitles: function(){
1241 for(var cbs = this._cboxes, i = cbs.length; i > 0; --i){
1242 cbs[i - 1].updateRuleIndex(i);
1243 cbs[i - 1].setAriaInfo(i);
1244 }
1245 },
1246 _updatePane: function(){
1247 var cbs = this._cboxes,
1248 defPane = this.filterDefPane;
1249 defPane._addCBoxBtn.set("disabled", cbs.length == this.plugin.args.ruleCount);
1250 defPane._filterBtn.set("disabled", !this.canFilter());
1251 },
1252 canFilter: function(){
1253 return array.filter(this._cboxes, function(cbox){
1254 return !cbox.isEmpty();
1255 }).length > 0;
1256 },
1257 _closeDlgAndUpdateGrid: function(){
1258 this.closeDialog();
1259 var g = this.plugin.grid;
1260 g.showMessage(g.loadingMessage);
1261 setTimeout(lang.hitch(g, g._refresh), this._defPane.duration + 10);
1262 }
1263 });
1264
1265 return FilterDefDialog;
1266 });