9351f6213249cd1c335e46bdae3087effa3db28f
[odoo/odoo.git] / addons / web / static / src / js / search.js
1 openerp.web.search = function(instance) {
2 var QWeb = instance.web.qweb,
3       _t =  instance.web._t,
4      _lt = instance.web._lt;
5 _.mixin({
6     sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
7 });
8
9 /** @namespace */
10 var my = instance.web.search = {};
11
12 var B = Backbone;
13 my.FacetValue = B.Model.extend({
14
15 });
16 my.FacetValues = B.Collection.extend({
17     model: my.FacetValue
18 });
19 my.Facet = B.Model.extend({
20     initialize: function (attrs) {
21         var values = attrs.values;
22         delete attrs.values;
23
24         B.Model.prototype.initialize.apply(this, arguments);
25
26         this.values = new my.FacetValues(values || []);
27         this.values.on('add remove change reset', function () {
28             this.trigger('change', this);
29         }, this);
30     },
31     get: function (key) {
32         if (key !== 'values') {
33             return B.Model.prototype.get.call(this, key);
34         }
35         return this.values.toJSON();
36     },
37     set: function (key, value) {
38         if (key !== 'values') {
39             return B.Model.prototype.set.call(this, key, value);
40         }
41         this.values.reset(value);
42     },
43     toJSON: function () {
44         var out = {};
45         var attrs = this.attributes;
46         for(var att in attrs) {
47             if (!attrs.hasOwnProperty(att) || att === 'field') {
48                 continue;
49             }
50             out[att] = attrs[att];
51         }
52         out.values = this.values.toJSON();
53         return out;
54     }
55 });
56 my.SearchQuery = B.Collection.extend({
57     model: my.Facet,
58     initialize: function () {
59         B.Collection.prototype.initialize.apply(
60             this, arguments);
61         this.on('change', function (facet) {
62             if(!facet.values.isEmpty()) { return; }
63
64             this.remove(facet, {silent: true});
65         }, this);
66     },
67     add: function (values, options) {
68         options || (options = {});
69         if (!(values instanceof Array)) {
70             values = [values];
71         }
72
73         _(values).each(function (value) {
74             var model = this._prepareModel(value, options);
75             var previous = this.detect(function (facet) {
76                 return facet.get('category') === model.get('category')
77                     && facet.get('field') === model.get('field');
78             });
79             if (previous) {
80                 previous.values.add(model.get('values'));
81                 return;
82             }
83             B.Collection.prototype.add.call(this, model, options);
84         }, this);
85         return this;
86     },
87     toggle: function (value, options) {
88         options || (options = {});
89
90         var facet = this.detect(function (facet) {
91             return facet.get('category') === value.category
92                 && facet.get('field') === value.field;
93         });
94         if (!facet) {
95             return this.add(value, options);
96         }
97
98         var changed = false;
99         _(value.values).each(function (val) {
100             var already_value = facet.values.detect(function (v) {
101                 return v.get('value') === val.value
102                     && v.get('label') === val.label;
103             });
104             // toggle value
105             if (already_value) {
106                 facet.values.remove(already_value, {silent: true});
107             } else {
108                 facet.values.add(val, {silent: true});
109             }
110             changed = true;
111         });
112         // "Commit" changes to values array as a single call, so observers of
113         // change event don't get misled by intermediate incomplete toggling
114         // states
115         facet.trigger('change', facet);
116         return this;
117     }
118 });
119
120 function assert(condition, message) {
121     if(!condition) {
122         throw new Error(message);
123     }
124 }
125 my.InputView = instance.web.Widget.extend({
126     template: 'SearchView.InputView',
127     start: function () {
128         var p = this._super.apply(this, arguments);
129         this.$el.on('focus', this.proxy('onFocus'));
130         this.$el.on('blur', this.proxy('onBlur'));
131         this.$el.on('keydown', this.proxy('onKeydown'));
132         return p;
133     },
134     onFocus: function () {
135         this.trigger('focused', this);
136     },
137     onBlur: function () {
138         this.$el.text('');
139         this.trigger('blurred', this);
140     },
141     getSelection: function () {
142         // get Text node
143         var root = this.$el[0].childNodes[0];
144         if (!root || !root.textContent) {
145             // if input does not have a child node, or the child node is an
146             // empty string, then the selection can only be (0, 0)
147             return {start: 0, end: 0};
148         }
149         if (window.getSelection) {
150             var domRange = window.getSelection().getRangeAt(0);
151             assert(domRange.startContainer === root,
152                    "selection should be in the input view");
153             assert(domRange.endContainer === root,
154                    "selection should be in the input view");
155             return {
156                 start: domRange.startOffset,
157                 end: domRange.endOffset
158             }
159         } else if (document.selection) {
160             var ieRange = document.selection.createRange();
161             var rangeParent = ieRange.parentElement();
162             assert(rangeParent === root,
163                    "selection should be in the input view");
164             var offsetRange = document.body.createTextRange();
165             offsetRange = offsetRange.moveToElementText(rangeParent);
166             offsetRange.setEndPoint("EndToStart", ieRange);
167             var start = offsetRange.text.length;
168             return {
169                 start: start,
170                 end: start + ieRange.text.length
171             }
172         }
173         throw new Error("Could not get caret position");
174     },
175     onKeydown: function (e) {
176         var sel;
177         switch (e.which) {
178         // Do not insert newline, but let it bubble so searchview can use it
179         case $.ui.keyCode.ENTER:
180             e.preventDefault();
181             break;
182
183         // FIXME: may forget content if non-empty but caret at index 0, ok?
184         case $.ui.keyCode.BACKSPACE:
185             sel = this.getSelection();
186             if (sel.start === 0 && sel.start === sel.end) {
187                 e.preventDefault();
188                 var preceding = this.getParent().siblingSubview(this, -1);
189                 if (preceding && (preceding instanceof my.FacetView)) {
190                     preceding.model.destroy();
191                 }
192             }
193             break;
194
195         // let left/right events propagate to view if caret is at input border
196         // and not a selection
197         case $.ui.keyCode.LEFT:
198             sel = this.getSelection();
199             if (sel.start !== 0 || sel.start !== sel.end) {
200                 e.stopPropagation();
201             }
202             break;
203         case $.ui.keyCode.RIGHT:
204             sel = this.getSelection();
205             var len = this.$el.text().length;
206             if (sel.start !== len || sel.start !== sel.end) {
207                 e.stopPropagation();
208             }
209             break;
210         }
211     }
212 });
213 my.FacetView = instance.web.Widget.extend({
214     template: 'SearchView.FacetView',
215     init: function (parent, model) {
216         this._super(parent);
217         this.model = model;
218         this.model.on('change', this.model_changed, this);
219     },
220     destroy: function () {
221         this.model.off('change', this.model_changed, this);
222         this._super();
223     },
224     start: function () {
225         var self = this;
226         this.$el.on('focus', function () { self.trigger('focused', self); });
227         this.$el.on('blur', function () { self.trigger('blurred', self); });
228         this.$el.on('click', function (e) {
229             if ($(e.target).is('.oe_facet_remove')) {
230                 self.model.destroy();
231                 return false;
232             }
233             self.$el.focus();
234             e.stopPropagation();
235         });
236         this.$el.on('keydown', function (e) {
237             var keys = $.ui.keyCode;
238             switch (e.which) {
239             case keys.BACKSPACE:
240             case keys.DELETE:
241                 self.model.destroy();
242                 return false;
243             }
244         });
245         var $e = self.$el.find('> span:last-child');
246         var q = $.when(this._super());
247         return q.pipe(function () {
248             var values = self.model.values.map(function (value) {
249                 return new my.FacetValueView(self, value).appendTo($e);
250             });
251
252             return $.when.apply(null, values);
253         });
254     },
255     model_changed: function () {
256         this.$el.text(this.$el.text() + '*');
257     }
258 });
259 my.FacetValueView = instance.web.Widget.extend({
260     template: 'SearchView.FacetView.Value',
261     init: function (parent, model) {
262         this._super(parent);
263         this.model = model;
264         this.model.on('change', this.model_changed, this);
265     },
266     destroy: function () {
267         this.model.off('change', this.model_changed, this);
268         this._super();
269     },
270     model_changed: function () {
271         this.$el.text(this.$el.text() + '*');
272     }
273 });
274
275 instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
276     template: "SearchView",
277     /**
278      * @constructs instance.web.SearchView
279      * @extends instance.web.Widget
280      *
281      * @param parent
282      * @param dataset
283      * @param view_id
284      * @param defaults
285      * @param hidden
286      */
287     init: function(parent, dataset, view_id, defaults, hidden) {
288         this._super(parent);
289         this.dataset = dataset;
290         this.model = dataset.model;
291         this.view_id = view_id;
292
293         this.defaults = defaults || {};
294         this.has_defaults = !_.isEmpty(this.defaults);
295
296         this.inputs = [];
297         this.controls = {};
298
299         this.hidden = !!hidden;
300         this.headless = this.hidden && !this.has_defaults;
301
302         this.input_subviews = [];
303
304         this.ready = $.Deferred();
305     },
306     start: function() {
307         var self = this;
308         var p = this._super();
309
310         this.setup_global_completion();
311         this.query = new my.SearchQuery()
312                 .on('add change reset remove', this.proxy('do_search'))
313                 .on('add change reset remove', this.proxy('renderFacets'));
314
315         if (this.hidden) {
316             this.$el.hide();
317         }
318         if (this.headless) {
319             this.ready.resolve();
320         } else {
321             var load_view = this.rpc("/web/searchview/load", {
322                 model: this.model,
323                 view_id: this.view_id,
324                 context: this.dataset.get_context() });
325
326             $.when(load_view)
327                 .pipe(function(r) {
328                     self.search_view_loaded(r)
329                 }).fail(function () {
330                     self.ready.reject.apply(null, arguments);
331                 });
332         }
333
334         // Launch a search on clicking the oe_searchview_search button
335         this.$el.on('click', 'button.oe_searchview_search', function (e) {
336             e.stopImmediatePropagation();
337             self.do_search();
338         });
339
340         this.$el.on('keydown',
341                 '.oe_searchview_input, .oe_searchview_facet', function (e) {
342             switch(e.which) {
343             case $.ui.keyCode.LEFT:
344                 self.focusPreceding(this);
345                 e.preventDefault();
346                 break;
347             case $.ui.keyCode.RIGHT:
348                 self.focusFollowing(this);
349                 e.preventDefault();
350                 break;
351             }
352         });
353
354         this.$el.on('click', '.oe_searchview_clear', function (e) {
355             e.stopImmediatePropagation();
356             self.query.reset();
357         });
358         this.$el.on('click', '.oe_searchview_unfold_drawer', function (e) {
359             e.stopImmediatePropagation();
360             self.$el.toggleClass('oe_searchview_open_drawer');
361         });
362         instance.web.bus.on('click', this, function(ev) {
363             if ($(ev.target).parents('.oe_searchview').length === 0) {
364                 self.$el.removeClass('oe_searchview_open_drawer');
365             }
366         });
367         // Focus last input if the view itself is clicked (empty section of
368         // facets element)
369         this.$el.on('click', function (e) {
370             if (e.target === self.$el.find('.oe_searchview_facets')[0]) {
371                 self.$el.find('.oe_searchview_input:last').focus();
372             }
373         });
374         // when the completion list opens/refreshes, automatically select the
375         // first completion item so if the user just hits [RETURN] or [TAB] it
376         // automatically selects it
377         this.$el.on('autocompleteopen', function () {
378             var menu = self.$el.data('autocomplete').menu;
379             menu.activate(
380                 $.Event({ type: "mouseenter" }),
381                 menu.element.children().first());
382         });
383
384         return $.when(p, this.ready);
385     },
386     show: function () {
387         this.$el.show();
388     },
389     hide: function () {
390         this.$el.hide();
391     },
392
393     subviewForRoot: function (subview_root) {
394         return _(this.input_subviews).detect(function (subview) {
395             return subview.$el[0] === subview_root;
396         });
397     },
398     siblingSubview: function (subview, direction, wrap_around) {
399         var index = _(this.input_subviews).indexOf(subview) + direction;
400         if (wrap_around && index < 0) {
401             index = this.input_subviews.length - 1;
402         } else if (wrap_around && index >= this.input_subviews.length) {
403             index = 0;
404         }
405         return this.input_subviews[index];
406     },
407     focusPreceding: function (subview_root) {
408         return this.siblingSubview(
409             this.subviewForRoot(subview_root), -1, true)
410                 .$el.focus();
411     },
412     focusFollowing: function (subview_root) {
413         return this.siblingSubview(
414             this.subviewForRoot(subview_root), +1, true)
415                 .$el.focus();
416     },
417
418     /**
419      * Sets up thingie where all the mess is put?
420      */
421     select_for_drawer: function () {
422         return _(this.inputs).filter(function (input) {
423             return input.in_drawer();
424         });
425     },
426     /**
427      * Sets up search view's view-wide auto-completion widget
428      */
429     setup_global_completion: function () {
430         var self = this;
431
432         // autocomplete only correctly handles being initialized on the actual
433         // editable element (and only an element with a @value in 1.8 e.g.
434         // input or textarea), cheat by setting val() on $el
435         this.$el.on('keydown', function () {
436             // keydown is triggered *before* the element's value is set, so
437             // delay this. Pray that setTimeout are executed in FIFO (if they
438             // have the same delay) as autocomplete uses the exact same trick.
439             // FIXME: brittle as fuck
440             setTimeout(function () {
441                 self.$el.val(self.currentInputValue());
442             }, 0);
443
444         });
445
446         this.$el.autocomplete({
447             source: this.proxy('complete_global_search'),
448             select: this.proxy('select_completion'),
449             focus: function (e) { e.preventDefault(); },
450             html: true,
451             minLength: 1,
452             delay: 0
453         }).data('autocomplete')._renderItem = function (ul, item) {
454             // item of completion list
455             var $item = $( "<li></li>" )
456                 .data( "item.autocomplete", item )
457                 .appendTo( ul );
458
459             if (item.facet !== undefined) {
460                 // regular completion item
461                 return $item.append(
462                     (item.label)
463                         ? $('<a>').html(item.label)
464                         : $('<a>').text(item.value));
465             }
466             return $item.text(item.label)
467                 .css({
468                     borderTop: '1px solid #cccccc',
469                     margin: 0,
470                     padding: 0,
471                     zoom: 1,
472                     'float': 'left',
473                     clear: 'left',
474                     width: '100%'
475                 });
476         };
477     },
478     /**
479      * Gets value out of the currently focused "input" (a
480      * div[contenteditable].oe_searchview_input)
481      */
482     currentInputValue: function () {
483         return this.$el.find('div.oe_searchview_input:focus').text();
484     },
485     /**
486      * Provide auto-completion result for req.term (an array to `resp`)
487      *
488      * @param {Object} req request to complete
489      * @param {String} req.term searched term to complete
490      * @param {Function} resp response callback
491      */
492     complete_global_search:  function (req, resp) {
493         $.when.apply(null, _(this.inputs).chain()
494             .invoke('complete', req.term)
495             .value()).then(function () {
496                 resp(_(_(arguments).compact()).flatten(true));
497         });
498     },
499
500     /**
501      * Action to perform in case of selection: create a facet (model)
502      * and add it to the search collection
503      *
504      * @param {Object} e selection event, preventDefault to avoid setting value on object
505      * @param {Object} ui selection information
506      * @param {Object} ui.item selected completion item
507      */
508     select_completion: function (e, ui) {
509         e.preventDefault();
510
511         var input_index = _(this.input_subviews).indexOf(
512             this.subviewForRoot(
513                 this.$el.find('div.oe_searchview_input:focus')[0]));
514         this.query.add(ui.item.facet, {at: input_index / 2});
515     },
516     childFocused: function () {
517         this.$el.addClass('oe_focused');
518     },
519     childBlurred: function () {
520         var val = this.$el.val();
521         this.$el.val('');
522         var complete = this.$el.data('autocomplete');
523         if ((val && complete.term === undefined) || complete.previous !== undefined) {
524             throw new Error("new jquery.ui version altering implementation" +
525                             " details relied on");
526         }
527         delete complete.term;
528         this.$el.removeClass('oe_focused')
529                      .trigger('blur');
530     },
531     /**
532      *
533      * @param {openerp.web.search.SearchQuery | openerp.web.search.Facet} _1
534      * @param {openerp.web.search.Facet} [_2]
535      * @param {Object} [options]
536      */
537     renderFacets: function (_1, _2, options) {
538         // _1: model if event=change, otherwise collection
539         // _2: undefined if event=change, otherwise model
540         var self = this;
541         var started = [];
542         var $e = this.$el.find('div.oe_searchview_facets');
543         _.invoke(this.input_subviews, 'destroy');
544         this.input_subviews = [];
545
546         var i = new my.InputView(this);
547         started.push(i.appendTo($e));
548         this.input_subviews.push(i);
549         this.query.each(function (facet) {
550             var f = new my.FacetView(this, facet);
551             started.push(f.appendTo($e));
552             self.input_subviews.push(f);
553
554             var i = new my.InputView(this);
555             started.push(i.appendTo($e));
556             self.input_subviews.push(i);
557         }, this);
558         _.each(this.input_subviews, function (childView) {
559             childView.on('focused', self, self.proxy('childFocused'));
560             childView.on('blurred', self, self.proxy('childBlurred'));
561         });
562
563         $.when.apply(null, started).then(function () {
564             var input_to_focus;
565             // options.at: facet inserted at given index, focus next input
566             // otherwise just focus last input
567             if (!options || typeof options.at !== 'number') {
568                 input_to_focus = _.last(self.input_subviews);
569             } else {
570                 input_to_focus = self.input_subviews[(options.at + 1) * 2];
571             }
572
573             input_to_focus.$el.focus();
574         });
575     },
576
577     /**
578      * Builds a list of widget rows (each row is an array of widgets)
579      *
580      * @param {Array} items a list of nodes to convert to widgets
581      * @param {Object} fields a mapping of field names to (ORM) field attributes
582      * @param {String} [group_name] name of the group to put the new controls in
583      */
584     make_widgets: function (items, fields, group_name) {
585         group_name = group_name || null;
586         if (!(group_name in this.controls)) {
587             this.controls[group_name] = [];
588         }
589         var self = this, group = this.controls[group_name];
590         var filters = [];
591         _.each(items, function (item) {
592             if (filters.length && item.tag !== 'filter') {
593                 group.push(new instance.web.search.FilterGroup(filters, this));
594                 filters = [];
595             }
596
597             switch (item.tag) {
598             case 'separator': case 'newline':
599                 break;
600             case 'filter':
601                 filters.push(new instance.web.search.Filter(item, this));
602                 break;
603             case 'group':
604                 self.make_widgets(item.children, fields, item.attrs.string);
605                 break;
606             case 'field':
607                 group.push(this.make_field(item, fields[item['attrs'].name]));
608                 // filters
609                 self.make_widgets(item.children, fields, group_name);
610                 break;
611             }
612         }, this);
613
614         if (filters.length) {
615             group.push(new instance.web.search.FilterGroup(filters, this));
616         }
617     },
618     /**
619      * Creates a field for the provided field descriptor item (which comes
620      * from fields_view_get)
621      *
622      * @param {Object} item fields_view_get node for the field
623      * @param {Object} field fields_get result for the field
624      * @returns instance.web.search.Field
625      */
626     make_field: function (item, field) {
627         var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]);
628         if(obj) {
629             return new (obj) (item, field, this);
630         } else {
631             console.group('Unknown field type ' + field.type);
632             console.error('View node', item);
633             console.info('View field', field);
634             console.info('In view', this);
635             console.groupEnd();
636             return null;
637         }
638     },
639
640     add_common_inputs: function() {
641         // add Filters to this.inputs, need view.controls filled
642         (new instance.web.search.Filters(this));
643         // add custom filters to this.inputs
644         (new instance.web.search.CustomFilters(this));
645         // add Advanced to this.inputs
646         (new instance.web.search.Advanced(this));
647     },
648
649     search_view_loaded: function(data) {
650         var self = this;
651         this.fields_view = data.fields_view;
652         if (data.fields_view.type !== 'search' ||
653             data.fields_view.arch.tag !== 'search') {
654                 throw new Error(_.str.sprintf(
655                     "Got non-search view after asking for a search view: type %s, arch root %s",
656                     data.fields_view.type, data.fields_view.arch.tag));
657         }
658         this.make_widgets(
659             data.fields_view['arch'].children,
660             data.fields_view.fields);
661
662         this.add_common_inputs();
663
664         // build drawer
665         var drawer_started = $.when.apply(
666             null, _(this.select_for_drawer()).invoke(
667                 'appendTo', this.$el.find('.oe_searchview_drawer')));
668         
669         // load defaults
670         var defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
671             'facet_for_defaults', this.defaults)).then(function () {
672                 self.query.reset(_(arguments).compact(), {preventSearch: true});
673             });
674         
675         return $.when(drawer_started, defaults_fetched)
676             .then(function () { 
677                 self.trigger("search_view_loaded", data);
678                 self.ready.resolve();
679             });
680     },
681     /**
682      * Extract search data from the view's facets.
683      *
684      * Result is an object with 4 (own) properties:
685      *
686      * errors
687      *     An array of any error generated during data validation and
688      *     extraction, contains the validation error objects
689      * domains
690      *     Array of domains
691      * contexts
692      *     Array of contexts
693      * groupbys
694      *     Array of domains, in groupby order rather than view order
695      *
696      * @return {Object}
697      */
698     build_search_data: function () {
699         var domains = [], contexts = [], groupbys = [], errors = [];
700
701         this.query.each(function (facet) {
702             var field = facet.get('field');
703             try {
704                 var domain = field.get_domain(facet);
705                 if (domain) {
706                     domains.push(domain);
707                 }
708                 var context = field.get_context(facet);
709                 if (context) {
710                     contexts.push(context);
711                 }
712                 var group_by = field.get_groupby(facet);
713                 if (group_by) {
714                     groupbys.push.apply(groupbys, group_by);
715                 }
716             } catch (e) {
717                 if (e instanceof instance.web.search.Invalid) {
718                     errors.push(e);
719                 } else {
720                     throw e;
721                 }
722             }
723         });
724         return {
725             domains: domains,
726             contexts: contexts,
727             groupbys: groupbys,
728             errors: errors
729         };
730     }, 
731     /**
732      * Performs the search view collection of widget data.
733      *
734      * If the collection went well (all fields are valid), then triggers
735      * :js:func:`instance.web.SearchView.on_search`.
736      *
737      * If at least one field failed its validation, triggers
738      * :js:func:`instance.web.SearchView.on_invalid` instead.
739      */
740     do_search: function (_query, options) {
741         if (options && options.preventSearch) {
742             return;
743         }
744         var search = this.build_search_data();
745         if (!_.isEmpty(search.errors)) {
746             this.on_invalid(search.errors);
747             return;
748         }
749         this.trigger('search_data', search.domains, search.contexts, search.groupbys);
750     },
751     /**
752      * Triggered after the SearchView has collected all relevant domains and
753      * contexts.
754      *
755      * It is provided with an Array of domains and an Array of contexts, which
756      * may or may not be evaluated (each item can be either a valid domain or
757      * context, or a string to evaluate in order in the sequence)
758      *
759      * It is also passed an array of contexts used for group_by (they are in
760      * the correct order for group_by evaluation, which contexts may not be)
761      *
762      * @event
763      * @param {Array} domains an array of literal domains or domain references
764      * @param {Array} contexts an array of literal contexts or context refs
765      * @param {Array} groupbys ordered contexts which may or may not have group_by keys
766      */
767     /**
768      * Triggered after a validation error in the SearchView fields.
769      *
770      * Error objects have three keys:
771      * * ``field`` is the name of the invalid field
772      * * ``value`` is the invalid value
773      * * ``message`` is the (in)validation message provided by the field
774      *
775      * @event
776      * @param {Array} errors a never-empty array of error objects
777      */
778     on_invalid: function (errors) {
779         this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
780         this.trigger('invalid_search', errors);
781     }
782 });
783
784 /**
785  * Registry of search fields, called by :js:class:`instance.web.SearchView` to
786  * find and instantiate its field widgets.
787  */
788 instance.web.search.fields = new instance.web.Registry({
789     'char': 'instance.web.search.CharField',
790     'text': 'instance.web.search.CharField',
791     'boolean': 'instance.web.search.BooleanField',
792     'integer': 'instance.web.search.IntegerField',
793     'id': 'instance.web.search.IntegerField',
794     'float': 'instance.web.search.FloatField',
795     'selection': 'instance.web.search.SelectionField',
796     'datetime': 'instance.web.search.DateTimeField',
797     'date': 'instance.web.search.DateField',
798     'many2one': 'instance.web.search.ManyToOneField',
799     'many2many': 'instance.web.search.CharField',
800     'one2many': 'instance.web.search.CharField'
801 });
802 instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{
803     /**
804      * Exception thrown by search widgets when they hold invalid values,
805      * which they can not return when asked.
806      *
807      * @constructs instance.web.search.Invalid
808      * @extends instance.web.Class
809      *
810      * @param field the name of the field holding an invalid value
811      * @param value the invalid value
812      * @param message validation failure message
813      */
814     init: function (field, value, message) {
815         this.field = field;
816         this.value = value;
817         this.message = message;
818     },
819     toString: function () {
820         return _.str.sprintf(
821             _t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
822             {fieldname: this.field, value: this.value, message: this.message}
823         );
824     }
825 });
826 instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{
827     template: null,
828     /**
829      * Root class of all search widgets
830      *
831      * @constructs instance.web.search.Widget
832      * @extends instance.web.Widget
833      *
834      * @param view the ancestor view of this widget
835      */
836     init: function (view) {
837         this._super(view);
838         this.view = view;
839     }
840 });
841 instance.web.search.add_expand_listener = function($root) {
842     $root.find('a.searchview_group_string').click(function (e) {
843         $root.toggleClass('folded expanded');
844         e.stopPropagation();
845         e.preventDefault();
846     });
847 };
848 instance.web.search.Group = instance.web.search.Widget.extend({
849     template: 'SearchView.group',
850     init: function (view_section, view, fields) {
851         this._super(view);
852         this.attrs = view_section.attrs;
853         this.lines = view.make_widgets(
854             view_section.children, fields);
855     }
856 });
857
858 instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{
859     _in_drawer: false,
860     /**
861      * @constructs instance.web.search.Input
862      * @extends instance.web.search.Widget
863      *
864      * @param view
865      */
866     init: function (view) {
867         this._super(view);
868         this.view.inputs.push(this);
869         this.style = undefined;
870     },
871     /**
872      * Fetch auto-completion values for the widget.
873      *
874      * The completion values should be an array of objects with keys category,
875      * label, value prefixed with an object with keys type=section and label
876      *
877      * @param {String} value value to complete
878      * @returns {jQuery.Deferred<null|Array>}
879      */
880     complete: function (value) {
881         return $.when(null)
882     },
883     /**
884      * Returns a Facet instance for the provided defaults if they apply to
885      * this widget, or null if they don't.
886      *
887      * This default implementation will try calling
888      * :js:func:`instance.web.search.Input#facet_for` if the widget's name
889      * matches the input key
890      *
891      * @param {Object} defaults
892      * @returns {jQuery.Deferred<null|Object>}
893      */
894     facet_for_defaults: function (defaults) {
895         if (!this.attrs ||
896             !(this.attrs.name in defaults && defaults[this.attrs.name])) {
897             return $.when(null);
898         }
899         return this.facet_for(defaults[this.attrs.name]);
900     },
901     in_drawer: function () {
902         return !!this._in_drawer;
903     },
904     get_context: function () {
905         throw new Error(
906             "get_context not implemented for widget " + this.attrs.type);
907     },
908     get_groupby: function () {
909         throw new Error(
910             "get_groupby not implemented for widget " + this.attrs.type);
911     },
912     get_domain: function () {
913         throw new Error(
914             "get_domain not implemented for widget " + this.attrs.type);
915     },
916     load_attrs: function (attrs) {
917         if (attrs.modifiers) {
918             attrs.modifiers = JSON.parse(attrs.modifiers);
919             attrs.invisible = attrs.modifiers.invisible || false;
920             if (attrs.invisible) {
921                 this.style = 'display: none;'
922             }
923         }
924         this.attrs = attrs;
925     }
926 });
927 instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
928     template: 'SearchView.filters',
929     icon: 'q',
930     completion_label: _lt("Filter on: %s"),
931     /**
932      * Inclusive group of filters, creates a continuous "button" with clickable
933      * sections (the normal display for filters is to be a self-contained button)
934      *
935      * @constructs instance.web.search.FilterGroup
936      * @extends instance.web.search.Input
937      *
938      * @param {Array<instance.web.search.Filter>} filters elements of the group
939      * @param {instance.web.SearchView} view view in which the filters are contained
940      */
941     init: function (filters, view) {
942         // If all filters are group_by and we're not initializing a GroupbyGroup,
943         // create a GroupbyGroup instead of the current FilterGroup
944         if (!(this instanceof instance.web.search.GroupbyGroup) &&
945               _(filters).all(function (f) {
946                   return f.attrs.context && f.attrs.context.group_by; })) {
947             return new instance.web.search.GroupbyGroup(filters, view);
948         }
949         this._super(view);
950         this.filters = filters;
951         this.view.query.on('add remove change reset', this.proxy('search_change'));
952     },
953     start: function () {
954         this.$el.on('click', 'li', this.proxy('toggle_filter'));
955         return $.when(null);
956     },
957     /**
958      * Handles change of the search query: any of the group's filter which is
959      * in the search query should be visually checked in the drawer
960      */
961     search_change: function () {
962         var self = this;
963         var $filters = this.$el.find('> li').removeClass('oe_selected');
964         var facet = this.view.query.find(_.bind(this.match_facet, this));
965         if (!facet) { return; }
966         facet.values.each(function (v) {
967             var i = _(self.filters).indexOf(v.get('value'));
968             if (i === -1) { return; }
969             $filters.eq(i).addClass('oe_selected');
970         });
971     },
972     /**
973      * Matches the group to a facet, in order to find if the group is
974      * represented in the current search query
975      */
976     match_facet: function (facet) {
977         return facet.get('field') === this;
978     },
979     make_facet: function (values) {
980         return {
981             category: _t("Filter"),
982             icon: this.icon,
983             values: values,
984             field: this
985         }
986     },
987     make_value: function (filter) {
988         return {
989             label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
990             value: filter
991         };
992     },
993     facet_for_defaults: function (defaults) {
994         var self = this;
995         var fs = _(this.filters).chain()
996             .filter(function (f) {
997                 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
998             }).map(function (f) {
999                 return self.make_value(f);
1000             }).value();
1001         if (_.isEmpty(fs)) { return $.when(null); }
1002         return $.when(this.make_facet(fs));
1003     },
1004     /**
1005      * Fetches contexts for all enabled filters in the group
1006      *
1007      * @param {openerp.web.search.Facet} facet
1008      * @return {*} combined contexts of the enabled filters in this group
1009      */
1010     get_context: function (facet) {
1011         var contexts = facet.values.chain()
1012             .map(function (f) { return f.get('value').attrs.context; })
1013             .reject(_.isEmpty)
1014             .value();
1015
1016         if (!contexts.length) { return; }
1017         if (contexts.length === 1) { return contexts[0]; }
1018         return _.extend(new instance.web.CompoundContext, {
1019             __contexts: contexts
1020         });
1021     },
1022     /**
1023      * Fetches group_by sequence for all enabled filters in the group
1024      *
1025      * @param {VS.model.SearchFacet} facet
1026      * @return {Array} enabled filters in this group
1027      */
1028     get_groupby: function (facet) {
1029         return  facet.values.chain()
1030             .map(function (f) { return f.get('value').attrs.context; })
1031             .reject(_.isEmpty)
1032             .value();
1033     },
1034     /**
1035      * Handles domains-fetching for all the filters within it: groups them.
1036      *
1037      * @param {VS.model.SearchFacet} facet
1038      * @return {*} combined domains of the enabled filters in this group
1039      */
1040     get_domain: function (facet) {
1041         var domains = facet.values.chain()
1042             .map(function (f) { return f.get('value').attrs.domain; })
1043             .reject(_.isEmpty)
1044             .value();
1045
1046         if (!domains.length) { return; }
1047         if (domains.length === 1) { return domains[0]; }
1048         for (var i=domains.length; --i;) {
1049             domains.unshift(['|']);
1050         }
1051         return _.extend(new instance.web.CompoundDomain(), {
1052             __domains: domains
1053         });
1054     },
1055     toggle_filter: function (e) {
1056         this.toggle(this.filters[$(e.target).index()]);
1057     },
1058     toggle: function (filter) {
1059         this.view.query.toggle(this.make_facet([this.make_value(filter)]));
1060     },
1061     complete: function (item) {
1062         var self = this;
1063         item = item.toLowerCase();
1064         var facet_values = _(this.filters).chain()
1065             .filter(function (filter) {
1066                 var at = {
1067                     string: filter.attrs.string || '',
1068                     help: filter.attrs.help || '',
1069                     name: filter.attrs.name || ''
1070                 };
1071                 var include = _.str.include;
1072                 return include(at.string.toLowerCase(), item)
1073                     || include(at.help.toLowerCase(), item)
1074                     || include(at.name.toLowerCase(), item);
1075             })
1076             .map(this.make_value)
1077             .value();
1078         if (_(facet_values).isEmpty()) { return $.when(null); }
1079         return $.when(_.map(facet_values, function (facet_value) {
1080             return {
1081                 label: _.str.sprintf(self.completion_label.toString(),
1082                                      facet_value.label),
1083                 facet: self.make_facet([facet_value])
1084             }
1085         }));
1086     }
1087 });
1088 instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
1089     icon: 'w',
1090     completion_label: _lt("Group by: %s"),
1091     init: function (filters, view) {
1092         this._super(filters, view);
1093         // Not flanders: facet unicity is handled through the
1094         // (category, field) pair of facet attributes. This is all well and
1095         // good for regular filter groups where a group matches a facet, but for
1096         // groupby we want a single facet. So cheat: add an attribute on the
1097         // view which proxies to the first GroupbyGroup, so it can be used
1098         // for every GroupbyGroup and still provides the various methods needed
1099         // by the search view. Use weirdo name to avoid risks of conflicts
1100         if (!this.getParent()._s_groupby) {
1101             this.getParent()._s_groupby = {
1102                 help: "See GroupbyGroup#init",
1103                 get_context: this.proxy('get_context'),
1104                 get_domain: this.proxy('get_domain'),
1105                 get_groupby: this.proxy('get_groupby')
1106             }
1107         }
1108     },
1109     match_facet: function (facet) {
1110         return facet.get('field') === this.getParent()._s_groupby;
1111     },
1112     make_facet: function (values) {
1113         return {
1114             category: _t("GroupBy"),
1115             icon: this.icon,
1116             values: values,
1117             field: this.getParent()._s_groupby
1118         };
1119     }
1120 });
1121 instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
1122     template: 'SearchView.filter',
1123     /**
1124      * Implementation of the OpenERP filters (button with a context and/or
1125      * a domain sent as-is to the search view)
1126      *
1127      * Filters are only attributes holder, the actual work (compositing
1128      * domains and contexts, converting between facets and filters) is
1129      * performed by the filter group.
1130      *
1131      * @constructs instance.web.search.Filter
1132      * @extends instance.web.search.Input
1133      *
1134      * @param node
1135      * @param view
1136      */
1137     init: function (node, view) {
1138         this._super(view);
1139         this.load_attrs(node.attrs);
1140     },
1141     facet_for: function () { return $.when(null); },
1142     get_context: function () { },
1143     get_domain: function () { },
1144 });
1145 instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
1146     template: 'SearchView.field',
1147     default_operator: '=',
1148     /**
1149      * @constructs instance.web.search.Field
1150      * @extends instance.web.search.Input
1151      *
1152      * @param view_section
1153      * @param field
1154      * @param view
1155      */
1156     init: function (view_section, field, view) {
1157         this._super(view);
1158         this.load_attrs(_.extend({}, field, view_section.attrs));
1159     },
1160     facet_for: function (value) {
1161         return $.when({
1162             field: this,
1163             category: this.attrs.string || this.attrs.name,
1164             values: [{label: String(value), value: value}]
1165         });
1166     },
1167     value_from: function (facetValue) {
1168         return facetValue.get('value');
1169     },
1170     get_context: function (facet) {
1171         var self = this;
1172         // A field needs a context to send when active
1173         var context = this.attrs.context;
1174         if (_.isEmpty(context) || !facet.values.length) {
1175             return;
1176         }
1177         var contexts = facet.values.map(function (facetValue) {
1178             return new instance.web.CompoundContext(context)
1179                 .set_eval_context({self: self.value_from(facetValue)});
1180         });
1181
1182         if (contexts.length === 1) { return contexts[0]; }
1183
1184         return _.extend(new instance.web.CompoundContext, {
1185             __contexts: contexts
1186         });
1187     },
1188     get_groupby: function () { },
1189     /**
1190      * Function creating the returned domain for the field, override this
1191      * methods in children if you only need to customize the field's domain
1192      * without more complex alterations or tests (and without the need to
1193      * change override the handling of filter_domain)
1194      *
1195      * @param {String} name the field's name
1196      * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1197      * @param {Number|String} value parsed value for the field
1198      * @returns {Array<Array>} domain to include in the resulting search
1199      */
1200     make_domain: function (name, operator, facet) {
1201         return [[name, operator, this.value_from(facet)]];
1202     },
1203     get_domain: function (facet) {
1204         if (!facet.values.length) { return; }
1205
1206         var value_to_domain;
1207         var self = this;
1208         var domain = this.attrs['filter_domain'];
1209         if (domain) {
1210             value_to_domain = function (facetValue) {
1211                 return new instance.web.CompoundDomain(domain)
1212                     .set_eval_context({self: self.value_from(facetValue)});
1213             };
1214         } else {
1215             value_to_domain = function (facetValue) {
1216                 return self.make_domain(
1217                     self.attrs.name,
1218                     self.attrs.operator || self.default_operator,
1219                     facetValue);
1220             };
1221         }
1222         var domains = facet.values.map(value_to_domain);
1223
1224         if (domains.length === 1) { return domains[0]; }
1225         for (var i = domains.length; --i;) {
1226             domains.unshift(['|']);
1227         }
1228
1229         return _.extend(new instance.web.CompoundDomain, {
1230             __domains: domains
1231         });
1232     }
1233 });
1234 /**
1235  * Implementation of the ``char`` OpenERP field type:
1236  *
1237  * * Default operator is ``ilike`` rather than ``=``
1238  *
1239  * * The Javascript and the HTML values are identical (strings)
1240  *
1241  * @class
1242  * @extends instance.web.search.Field
1243  */
1244 instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
1245     default_operator: 'ilike',
1246     complete: function (value) {
1247         if (_.isEmpty(value)) { return $.when(null); }
1248         var label = _.str.sprintf(_.str.escapeHTML(
1249             _t("Search %(field)s for: %(value)s")), {
1250                 field: '<em>' + this.attrs.string + '</em>',
1251                 value: '<strong>' + _.str.escapeHTML(value) + '</strong>'});
1252         return $.when([{
1253             label: label,
1254             facet: {
1255                 category: this.attrs.string,
1256                 field: this,
1257                 values: [{label: value, value: value}]
1258             }
1259         }]);
1260     }
1261 });
1262 instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
1263     value_from: function () {
1264         if (!this.$el.val()) {
1265             return null;
1266         }
1267         var val = this.parse(this.$el.val()),
1268           check = Number(this.$el.val());
1269         if (isNaN(val) || val !== check) {
1270             this.$el.addClass('error');
1271             throw new instance.web.search.Invalid(
1272                 this.attrs.name, this.$el.val(), this.error_message);
1273         }
1274         this.$el.removeClass('error');
1275         return val;
1276     }
1277 });
1278 /**
1279  * @class
1280  * @extends instance.web.search.NumberField
1281  */
1282 instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
1283     error_message: _t("not a valid integer"),
1284     parse: function (value) {
1285         try {
1286             return instance.web.parse_value(value, {'widget': 'integer'});
1287         } catch (e) {
1288             return NaN;
1289         }
1290     }
1291 });
1292 /**
1293  * @class
1294  * @extends instance.web.search.NumberField
1295  */
1296 instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
1297     error_message: _t("not a valid number"),
1298     parse: function (value) {
1299         try {
1300             return instance.web.parse_value(value, {'widget': 'float'});
1301         } catch (e) {
1302             return NaN;
1303         }
1304     }
1305 });
1306
1307 /**
1308  * Utility function for m2o & selection fields taking a selection/name_get pair
1309  * (value, name) and converting it to a Facet descriptor
1310  *
1311  * @param {instance.web.search.Field} field holder field
1312  * @param {Array} pair pair value to convert
1313  */
1314 function facet_from(field, pair) {
1315     return {
1316         field: field,
1317         category: field['attrs'].string,
1318         values: [{label: pair[1], value: pair[0]}]
1319     };
1320 }
1321
1322 /**
1323  * @class
1324  * @extends instance.web.search.Field
1325  */
1326 instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
1327     // This implementation is a basic <select> field, but it may have to be
1328     // altered to be more in line with the GTK client, which uses a combo box
1329     // (~ jquery.autocomplete):
1330     // * If an option was selected in the list, behave as currently
1331     // * If something which is not in the list was entered (via the text input),
1332     //   the default domain should become (`ilike` string_value) but **any
1333     //   ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1334     //   is specified. So at least get_domain needs to be quite a bit
1335     //   overridden (if there's no @value and there is no filter_domain and
1336     //   there is no @operator, return [[name, 'ilike', str_val]]
1337     template: 'SearchView.field.selection',
1338     init: function () {
1339         this._super.apply(this, arguments);
1340         // prepend empty option if there is no empty option in the selection list
1341         this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1342             return !item[1];
1343         });
1344     },
1345     complete: function (needle) {
1346         var self = this;
1347         var results = _(this.attrs.selection).chain()
1348             .filter(function (sel) {
1349                 var value = sel[0], label = sel[1];
1350                 if (!value) { return false; }
1351                 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1352             })
1353             .map(function (sel) {
1354                 return {
1355                     label: sel[1],
1356                     facet: facet_from(self, sel)
1357                 };
1358             }).value();
1359         if (_.isEmpty(results)) { return $.when(null); }
1360         return $.when.call(null, [{
1361             label: this.attrs.string
1362         }].concat(results));
1363     },
1364     facet_for: function (value) {
1365         var match = _(this.attrs.selection).detect(function (sel) {
1366             return sel[0] === value;
1367         });
1368         if (!match) { return $.when(null); }
1369         return $.when(facet_from(this, match));
1370     }
1371 });
1372 instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
1373     /**
1374      * @constructs instance.web.search.BooleanField
1375      * @extends instance.web.search.BooleanField
1376      */
1377     init: function () {
1378         this._super.apply(this, arguments);
1379         this.attrs.selection = [
1380             [true, _t("Yes")],
1381             [false, _t("No")]
1382         ];
1383     }
1384 });
1385 /**
1386  * @class
1387  * @extends instance.web.search.DateField
1388  */
1389 instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
1390     value_from: function (facetValue) {
1391         return instance.web.date_to_str(facetValue.get('value'));
1392     },
1393     complete: function (needle) {
1394         var d = Date.parse(needle);
1395         if (!d) { return $.when(null); }
1396         var date_string = instance.web.format_value(d, this.attrs);
1397         var label = _.str.sprintf(_.str.escapeHTML(
1398             _t("Search %(field)s at: %(value)s")), {
1399                 field: '<em>' + this.attrs.string + '</em>',
1400                 value: '<strong>' + date_string + '</strong>'});
1401         return $.when([{
1402             label: label,
1403             facet: {
1404                 category: this.attrs.string,
1405                 field: this,
1406                 values: [{label: date_string, value: d}]
1407             }
1408         }]);
1409     }
1410 });
1411 /**
1412  * Implementation of the ``datetime`` openerp field type:
1413  *
1414  * * Uses the same widget as the ``date`` field type (a simple date)
1415  *
1416  * * Builds a slighly more complex, it's a datetime range (includes time)
1417  *   spanning the whole day selected by the date widget
1418  *
1419  * @class
1420  * @extends instance.web.DateField
1421  */
1422 instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
1423     value_from: function (facetValue) {
1424         return instance.web.datetime_to_str(facetValue.get('value'));
1425     }
1426 });
1427 instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
1428     default_operator: {},
1429     init: function (view_section, field, view) {
1430         this._super(view_section, field, view);
1431         this.model = new instance.web.Model(this.attrs.relation);
1432     },
1433     complete: function (needle) {
1434         var self = this;
1435         // TODO: context
1436         // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1437         return this.model.call('name_search', [], {
1438             name: needle,
1439             limit: 8,
1440             context: {}
1441         }).pipe(function (results) {
1442             if (_.isEmpty(results)) { return null; }
1443             return [{label: self.attrs.string}].concat(
1444                 _(results).map(function (result) {
1445                     return {
1446                         label: result[1],
1447                         facet: facet_from(self, result)
1448                     };
1449                 }));
1450         });
1451     },
1452     facet_for: function (value) {
1453         var self = this;
1454         if (value instanceof Array) {
1455             if (value.length === 2 && _.isString(value[1])) {
1456                 return $.when(facet_from(this, value));
1457             }
1458             assert(value.length <= 1,
1459                    _t("M2O search fields do not currently handle multiple default values"));
1460             // there are many cases of {search_default_$m2ofield: [id]}, need
1461             // to handle this as if it were a single value.
1462             value = value[0];
1463         }
1464         return this.model.call('name_get', [value]).pipe(function (names) {
1465             if (_(names).isEmpty()) { return null; }
1466             return facet_from(self, names[0]);
1467         })
1468     },
1469     value_from: function (facetValue) {
1470         return facetValue.get('label');
1471     },
1472     make_domain: function (name, operator, facetValue) {
1473         if (operator === this.default_operator) {
1474             return [[name, '=', facetValue.get('value')]];
1475         }
1476         return this._super(name, operator, facetValue);
1477     },
1478     get_context: function (facet) {
1479         var values = facet.values;
1480         if (_.isEmpty(this.attrs.context) && values.length === 1) {
1481             var c = {};
1482             c['default_' + this.attrs.name] = values.at(0).get('value');
1483             return c;
1484         }
1485         return this._super(facet);
1486     }
1487 });
1488
1489 instance.web.search.CustomFilters = instance.web.search.Input.extend({
1490     template: 'SearchView.CustomFilters',
1491     _in_drawer: true,
1492     start: function () {
1493         var self = this;
1494         this.model = new instance.web.Model('ir.filters');
1495         this.filters = {};
1496         this.view.query
1497             .on('remove', function (facet) {
1498                 if (!facet.get('is_custom_filter')) {
1499                     return;
1500                 }
1501                 self.clear_selection();
1502             })
1503             .on('reset', this.proxy('clear_selection'));
1504         this.$el.on('submit', 'form', this.proxy('save_current'));
1505         this.$el.on('click', 'h4', function () {
1506             self.$el.toggleClass('oe_opened');
1507         });
1508         // FIXME: local eval of domain and context to get rid of special endpoint
1509         return this.rpc('/web/searchview/get_filters', {
1510             model: this.view.model
1511         }).pipe(this.proxy('set_filters'));
1512     },
1513     clear_selection: function () {
1514         this.$el.find('li.oe_selected').removeClass('oe_selected');
1515     },
1516     append_filter: function (filter) {
1517         var self = this;
1518         var key = _.str.sprintf('(%s)%s', filter.user_id, filter.name);
1519
1520         var $filter;
1521         if (key in this.filters) {
1522             $filter = this.filters[key];
1523         } else {
1524             var id = filter.id;
1525             $filter = this.filters[key] = $('<li></li>')
1526                 .appendTo(this.$el.find('.oe_searchview_custom_list'))
1527                 .addClass(filter.user_id ? 'oe_searchview_custom_private'
1528                                          : 'oe_searchview_custom_public')
1529                 .text(filter.name);
1530
1531             $('<a class="oe_searchview_custom_delete">x</a>')
1532                 .click(function (e) {
1533                     e.stopPropagation();
1534                     self.model.call('unlink', [id]).then(function () {
1535                         $filter.remove();
1536                     });
1537                 })
1538                 .appendTo($filter);
1539         }
1540
1541         $filter.unbind('click').click(function () {
1542             self.view.query.reset([{
1543                 category: _t("Custom Filter"),
1544                 icon: 'M',
1545                 field: {
1546                     get_context: function () { return filter.context; },
1547                     get_groupby: function () { return [filter.context]; },
1548                     get_domain: function () { return filter.domain; }
1549                 },
1550                 is_custom_filter: true,
1551                 values: [{label: filter.name, value: null}]
1552             }]);
1553             $filter.addClass('oe_selected');
1554         });
1555     },
1556     set_filters: function (filters) {
1557         _(filters).map(_.bind(this.append_filter, this));
1558     },
1559     save_current: function () {
1560         var self = this;
1561         var $name = this.$el.find('input:first');
1562         var private_filter = !this.$el.find('input:last').prop('checked');
1563
1564         var search = this.view.build_search_data();
1565         this.rpc('/web/session/eval_domain_and_context', {
1566             domains: search.domains,
1567             contexts: search.contexts,
1568             group_by_seq: search.groupbys || []
1569         }).then(function (results) {
1570             if (!_.isEmpty(results.group_by)) {
1571                 results.context.group_by = results.group_by;
1572             }
1573             var filter = {
1574                 name: $name.val(),
1575                 user_id: private_filter ? instance.session.uid : false,
1576                 model_id: self.view.model,
1577                 context: results.context,
1578                 domain: results.domain
1579             };
1580             // FIXME: current context?
1581             return self.model.call('create_or_replace', [filter]).then(function (id) {
1582                 filter.id = id;
1583                 self.append_filter(filter);
1584                 self.$el
1585                     .removeClass('oe_opened')
1586                     .find('form')[0].reset();
1587             });
1588         });
1589         return false;
1590     }
1591 });
1592
1593 instance.web.search.Filters = instance.web.search.Input.extend({
1594     template: 'SearchView.Filters',
1595     _in_drawer: true,
1596     start: function () {
1597         var self = this;
1598         var running_count = 0;
1599         // get total filters count
1600         var is_group = function (i) { return i instanceof instance.web.search.FilterGroup; };
1601         var filters_count = _(this.view.controls).chain()
1602             .flatten()
1603             .filter(is_group)
1604             .map(function (i) { return i.filters.length; })
1605             .sum()
1606             .value();
1607
1608         var col1 = [], col2 = _(this.view.controls).map(function (inputs, group) {
1609             var filters = _(inputs).filter(is_group);
1610             return {
1611                 name: group === 'null' ? "<span class='oe_i'>q</span> " + _t("Filters") : "<span class='oe_i'>w</span> " + group,
1612                 filters: filters,
1613                 length: _(filters).chain().map(function (i) {
1614                     return i.filters.length; }).sum().value()
1615             };
1616         });
1617
1618         while (col2.length) {
1619             // col1 + group should be smaller than col2 + group
1620             if ((running_count + col2[0].length) <= (filters_count - running_count)) {
1621                 running_count += col2[0].length;
1622                 col1.push(col2.shift());
1623             } else {
1624                 break;
1625             }
1626         }
1627
1628         return $.when(
1629             this.render_column(col1, $('<div>').appendTo(this.$el)),
1630             this.render_column(col2, $('<div>').appendTo(this.$el)));
1631     },
1632     render_column: function (column, $el) {
1633         return $.when.apply(null, _(column).map(function (group) {
1634             $('<h3>').html(group.name).appendTo($el);
1635             return $.when.apply(null,
1636                 _(group.filters).invoke('appendTo', $el));
1637         }));
1638     }
1639 });
1640
1641 instance.web.search.Advanced = instance.web.search.Input.extend({
1642     template: 'SearchView.advanced',
1643     _in_drawer: true,
1644     start: function () {
1645         var self = this;
1646         this.$el
1647             .on('keypress keydown keyup', function (e) { e.stopPropagation(); })
1648             .on('click', 'h4', function () {
1649                 self.$el.toggleClass('oe_opened');
1650             }).on('click', 'button.oe_add_condition', function () {
1651                 self.append_proposition();
1652             }).on('submit', 'form', function (e) {
1653                 e.preventDefault();
1654                 self.commit_search();
1655             });
1656         return $.when(
1657             this._super(),
1658             this.rpc("/web/searchview/fields_get", {model: this.view.model}).then(function(data) {
1659                 self.fields = _.extend({
1660                     id: { string: 'ID', type: 'id' }
1661                 }, data.fields);
1662         })).then(function () {
1663             self.append_proposition();
1664         });
1665     },
1666     append_proposition: function () {
1667         return (new instance.web.search.ExtendedSearchProposition(this, this.fields))
1668             .appendTo(this.$el.find('ul'));
1669     },
1670     commit_search: function () {
1671         var self = this;
1672         // Get domain sections from all propositions
1673         var children = this.getChildren();
1674         var propositions = _.invoke(children, 'get_proposition');
1675         var domain = _(propositions).pluck('value');
1676         for (var i = domain.length; --i;) {
1677             domain.unshift('|');
1678         }
1679
1680         this.view.query.add({
1681             category: _t("Advanced"),
1682             values: propositions,
1683             field: {
1684                 get_context: function () { },
1685                 get_domain: function () { return domain;},
1686                 get_groupby: function () { }
1687             }
1688         });
1689
1690         // remove all propositions
1691         _.invoke(children, 'destroy');
1692         // add new empty proposition
1693         this.append_proposition();
1694         // TODO: API on searchview
1695         this.view.$el.removeClass('oe_searchview_open_drawer');
1696     }
1697 });
1698
1699 instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
1700     template: 'SearchView.extended_search.proposition',
1701     /**
1702      * @constructs instance.web.search.ExtendedSearchProposition
1703      * @extends instance.web.Widget
1704      *
1705      * @param parent
1706      * @param fields
1707      */
1708     init: function (parent, fields) {
1709         this._super(parent);
1710         this.fields = _(fields).chain()
1711             .map(function(val, key) { return _.extend({}, val, {'name': key}); })
1712             .sortBy(function(field) {return field.string;})
1713             .value();
1714         this.attrs = {_: _, fields: this.fields, selected: null};
1715         this.value = null;
1716     },
1717     start: function () {
1718         var _this = this;
1719         this.$el.find(".searchview_extended_prop_field").change(function() {
1720             _this.changed();
1721         });
1722         this.$el.find('.searchview_extended_delete_prop').click(function () {
1723             _this.destroy();
1724         });
1725         this.changed();
1726     },
1727     changed: function() {
1728         var nval = this.$el.find(".searchview_extended_prop_field").val();
1729         if(this.attrs.selected == null || nval != this.attrs.selected.name) {
1730             this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
1731         }
1732     },
1733     /**
1734      * Selects the provided field object
1735      *
1736      * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
1737      */
1738     select_field: function(field) {
1739         var self = this;
1740         if(this.attrs.selected != null) {
1741             this.value.destroy();
1742             this.value = null;
1743             this.$el.find('.searchview_extended_prop_op').html('');
1744         }
1745         this.attrs.selected = field;
1746         if(field == null) {
1747             return;
1748         }
1749
1750         var type = field.type;
1751         var Field = instance.web.search.custom_filters.get_object(type);
1752         if(!Field) {
1753             Field = instance.web.search.custom_filters.get_object("char");
1754         }
1755         this.value = new Field(this, field);
1756         _.each(this.value.operators, function(operator) {
1757             $('<option>', {value: operator.value})
1758                 .text(String(operator.text))
1759                 .appendTo(self.$el.find('.searchview_extended_prop_op'));
1760         });
1761         var $value_loc = this.$el.find('.searchview_extended_prop_value').empty();
1762         this.value.appendTo($value_loc);
1763
1764     },
1765     get_proposition: function() {
1766         if ( this.attrs.selected == null)
1767             return null;
1768         var field = this.attrs.selected;
1769         var op = this.$el.find('.searchview_extended_prop_op')[0];
1770         var operator = op.options[op.selectedIndex];
1771         return {
1772             label: _.str.sprintf(_t('%(field)s %(operator)s "%(value)s"'), {
1773                 field: field.string,
1774                 // According to spec, HTMLOptionElement#label should return
1775                 // HTMLOptionElement#text when not defined/empty, but it does
1776                 // not in older Webkit (between Safari 5.1.5 and Chrome 17) and
1777                 // Gecko (pre Firefox 7) browsers, so we need a manual fallback
1778                 // for those
1779                 operator: operator.label || operator.text,
1780                 value: this.value}),
1781             value: [field.name, operator.value, this.value.get_value()]
1782         };
1783     }
1784 });
1785
1786 instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
1787     init: function (parent, field) {
1788         this._super(parent);
1789         this.field = field;
1790     },
1791     /**
1792      * Returns a human-readable version of the value, in case the "logical"
1793      * and the "semantic" values of a field differ (as for selection fields,
1794      * for instance).
1795      *
1796      * The default implementation simply returns the value itself.
1797      *
1798      * @return {String} human-readable version of the value
1799      */
1800     toString: function () {
1801         return this.get_value();
1802     }
1803 });
1804 instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
1805     template: 'SearchView.extended_search.proposition.char',
1806     operators: [
1807         {value: "ilike", text: _lt("contains")},
1808         {value: "not ilike", text: _lt("doesn't contain")},
1809         {value: "=", text: _lt("is equal to")},
1810         {value: "!=", text: _lt("is not equal to")}
1811     ],
1812     get_value: function() {
1813         return this.$el.val();
1814     }
1815 });
1816 instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
1817     template: 'SearchView.extended_search.proposition.empty',
1818     operators: [
1819         {value: "=", text: _lt("is equal to")},
1820         {value: "!=", text: _lt("is not equal to")},
1821         {value: ">", text: _lt("greater than")},
1822         {value: "<", text: _lt("less than")},
1823         {value: ">=", text: _lt("greater or equal than")},
1824         {value: "<=", text: _lt("less or equal than")}
1825     ],
1826     /**
1827      * Date widgets live in view_form which is not yet loaded when this is
1828      * initialized -_-
1829      */
1830     widget: function () { return instance.web.DateTimeWidget; },
1831     get_value: function() {
1832         return this.datewidget.get_value();
1833     },
1834     start: function() {
1835         var ready = this._super();
1836         this.datewidget = new (this.widget())(this);
1837         this.datewidget.appendTo(this.$el);
1838         return ready;
1839     }
1840 });
1841 instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
1842     widget: function () { return instance.web.DateWidget; }
1843 });
1844 instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
1845     template: 'SearchView.extended_search.proposition.integer',
1846     operators: [
1847         {value: "=", text: _lt("is equal to")},
1848         {value: "!=", text: _lt("is not equal to")},
1849         {value: ">", text: _lt("greater than")},
1850         {value: "<", text: _lt("less than")},
1851         {value: ">=", text: _lt("greater or equal than")},
1852         {value: "<=", text: _lt("less or equal than")}
1853     ],
1854     toString: function () {
1855         return this.$el.val();
1856     },
1857     get_value: function() {
1858         try {
1859             return instance.web.parse_value(this.$el.val(), {'widget': 'integer'});
1860         } catch (e) {
1861             return "";
1862         }
1863     }
1864 });
1865 instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
1866     operators: [{value: "=", text: _lt("is")}]
1867 });
1868 instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
1869     template: 'SearchView.extended_search.proposition.float',
1870     operators: [
1871         {value: "=", text: _lt("is equal to")},
1872         {value: "!=", text: _lt("is not equal to")},
1873         {value: ">", text: _lt("greater than")},
1874         {value: "<", text: _lt("less than")},
1875         {value: ">=", text: _lt("greater or equal than")},
1876         {value: "<=", text: _lt("less or equal than")}
1877     ],
1878     toString: function () {
1879         return this.$el.val();
1880     },
1881     get_value: function() {
1882         try {
1883             return instance.web.parse_value(this.$el.val(), {'widget': 'float'});
1884         } catch (e) {
1885             return "";
1886         }
1887     }
1888 });
1889 instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
1890     template: 'SearchView.extended_search.proposition.selection',
1891     operators: [
1892         {value: "=", text: _lt("is")},
1893         {value: "!=", text: _lt("is not")}
1894     ],
1895     toString: function () {
1896         var select = this.$el[0];
1897         var option = select.options[select.selectedIndex];
1898         return option.label || option.text;
1899     },
1900     get_value: function() {
1901         return this.$el.val();
1902     }
1903 });
1904 instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
1905     template: 'SearchView.extended_search.proposition.empty',
1906     operators: [
1907         {value: "=", text: _lt("is true")},
1908         {value: "!=", text: _lt("is false")}
1909     ],
1910     toString: function () { return ''; },
1911     get_value: function() {
1912         return true;
1913     }
1914 });
1915
1916 instance.web.search.custom_filters = new instance.web.Registry({
1917     'char': 'instance.web.search.ExtendedSearchProposition.Char',
1918     'text': 'instance.web.search.ExtendedSearchProposition.Char',
1919     'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
1920     'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
1921     'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
1922
1923     'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
1924     'date': 'instance.web.search.ExtendedSearchProposition.Date',
1925     'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
1926     'float': 'instance.web.search.ExtendedSearchProposition.Float',
1927     'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
1928     'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
1929
1930     'id': 'instance.web.search.ExtendedSearchProposition.Id'
1931 });
1932
1933 };
1934
1935 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: