4 var instance = openerp;
5 openerp.web.search = {};
7 var QWeb = instance.web.qweb,
9 _lt = instance.web._lt;
12 var my = instance.web.search = {};
15 my.FacetValue = B.Model.extend({
18 my.FacetValues = B.Collection.extend({
21 my.Facet = B.Model.extend({
22 initialize: function (attrs) {
23 var values = attrs.values;
26 B.Model.prototype.initialize.apply(this, arguments);
28 this.values = new my.FacetValues(values || []);
29 this.values.on('add remove change reset', function (_, options) {
30 this.trigger('change', this, options);
34 if (key !== 'values') {
35 return B.Model.prototype.get.call(this, key);
37 return this.values.toJSON();
39 set: function (key, value) {
40 if (key !== 'values') {
41 return B.Model.prototype.set.call(this, key, value);
43 this.values.reset(value);
47 var attrs = this.attributes;
48 for(var att in attrs) {
49 if (!attrs.hasOwnProperty(att) || att === 'field') {
52 out[att] = attrs[att];
54 out.values = this.values.toJSON();
58 my.SearchQuery = B.Collection.extend({
60 initialize: function () {
61 B.Collection.prototype.initialize.apply(
63 this.on('change', function (facet) {
64 if(!facet.values.isEmpty()) { return; }
66 this.remove(facet, {silent: true});
69 add: function (values, options) {
70 options = options || {};
74 } else if (!(values instanceof Array)) {
78 _(values).each(function (value) {
79 var model = this._prepareModel(value, options);
80 var previous = this.detect(function (facet) {
81 return facet.get('category') === model.get('category')
82 && facet.get('field') === model.get('field');
85 previous.values.add(model.get('values'), _.omit(options, 'at', 'merge'));
88 B.Collection.prototype.add.call(this, model, options);
90 // warning: in backbone 1.0+ add is supposed to return the added models,
91 // but here toggle may delegate to add and return its value directly.
92 // return value of neither seems actually used but should be tested
93 // before change, probably
96 toggle: function (value, options) {
97 options = options || {};
99 var facet = this.detect(function (facet) {
100 return facet.get('category') === value.category
101 && facet.get('field') === value.field;
104 return this.add(value, options);
108 _(value.values).each(function (val) {
109 var already_value = facet.values.detect(function (v) {
110 return v.get('value') === val.value
111 && v.get('label') === val.label;
115 facet.values.remove(already_value, {silent: true});
117 facet.values.add(val, {silent: true});
121 // "Commit" changes to values array as a single call, so observers of
122 // change event don't get misled by intermediate incomplete toggling
124 facet.trigger('change', facet);
129 function assert(condition, message) {
131 throw new Error(message);
134 my.InputView = instance.web.Widget.extend({
135 template: 'SearchView.InputView',
137 focus: function () { this.trigger('focused', this); },
138 blur: function () { this.$el.text(''); this.trigger('blurred', this); },
139 keydown: 'onKeydown',
142 getSelection: function () {
145 var root = this.el.childNodes[0];
146 if (!root || !root.textContent) {
147 // if input does not have a child node, or the child node is an
148 // empty string, then the selection can only be (0, 0)
149 return {start: 0, end: 0};
151 var range = window.getSelection().getRangeAt(0);
152 // In Firefox, depending on the way text is selected (drag, double- or
153 // triple-click) the range may start or end on the parent of the
154 // selected text node‽ Check for this condition and fixup the range
155 // note: apparently with C-a this can go even higher?
156 if (range.startContainer === this.el && range.startOffset === 0) {
157 range.setStart(root, 0);
159 if (range.endContainer === this.el && range.endOffset === 1) {
160 range.setEnd(root, root.length);
162 assert(range.startContainer === root,
163 "selection should be in the input view");
164 assert(range.endContainer === root,
165 "selection should be in the input view");
167 start: range.startOffset,
171 onKeydown: function (e) {
175 // Do not insert newline, but let it bubble so searchview can use it
176 case $.ui.keyCode.ENTER:
180 // FIXME: may forget content if non-empty but caret at index 0, ok?
181 case $.ui.keyCode.BACKSPACE:
182 sel = this.getSelection();
183 if (sel.start === 0 && sel.start === sel.end) {
185 var preceding = this.getParent().siblingSubview(this, -1);
186 if (preceding && (preceding instanceof my.FacetView)) {
187 preceding.model.destroy();
192 // let left/right events propagate to view if caret is at input border
193 // and not a selection
194 case $.ui.keyCode.LEFT:
195 sel = this.getSelection();
196 if (sel.start !== 0 || sel.start !== sel.end) {
200 case $.ui.keyCode.RIGHT:
201 sel = this.getSelection();
202 var len = this.$el.text().length;
203 if (sel.start !== len || sel.start !== sel.end) {
209 setCursorAtEnd: function () {
211 var sel = window.getSelection();
212 sel.removeAllRanges();
213 var range = document.createRange();
214 // in theory, range.selectNodeContents should work here. In practice,
215 // MSIE9 has issues from time to time, instead of selecting the inner
216 // text node it would select the reference node instead (e.g. in demo
217 // data, company news, copy across the "Company News" link + the title,
218 // from about half the link to half the text, paste in search box then
219 // hit the left arrow key, getSelection would blow up).
221 // Explicitly selecting only the inner text node (only child node
222 // since we've normalized the parent) avoids the issue
223 range.selectNode(this.el.childNodes[0]);
224 range.collapse(false);
227 onPaste: function () {
229 // In MSIE and Webkit, it is possible to get various representations of
230 // the clipboard data at this point e.g.
231 // window.clipboardData.getData('Text') and
232 // event.clipboardData.getData('text/plain') to ensure we have a plain
233 // text representation of the object (and probably ensure the object is
234 // pastable as well, so nobody puts an image in the search view)
235 // (nb: since it's not possible to alter the content of the clipboard
236 // — at least in Webkit — to ensure only textual content is available,
237 // using this would require 1. getting the text data; 2. manually
238 // inserting the text data into the content; and 3. cancelling the
241 // But Firefox doesn't support the clipboard API (as of FF18)
242 // although it correctly triggers the paste event (Opera does not even
243 // do that) => implement lowest-denominator system where onPaste
244 // triggers a followup "cleanup" pass after the data has been pasted
245 setTimeout(function () {
246 // Read text content (ignore pasted HTML)
247 var data = this.$el.text();
250 // paste raw text back in
251 this.$el.empty().text(data);
253 // Set the cursor at the end of the text, so the cursor is not lost
254 // in some kind of error-spawning limbo.
255 this.setCursorAtEnd();
259 my.FacetView = instance.web.Widget.extend({
260 template: 'SearchView.FacetView',
262 'focus': function () { this.trigger('focused', this); },
263 'blur': function () { this.trigger('blurred', this); },
264 'click': function (e) {
265 if ($(e.target).is('.oe_facet_remove')) {
266 this.model.destroy();
272 'keydown': function (e) {
273 var keys = $.ui.keyCode;
277 this.model.destroy();
282 init: function (parent, model) {
285 this.model.on('change', this.model_changed, this);
287 destroy: function () {
288 this.model.off('change', this.model_changed, this);
293 var $e = this.$('> span:last-child');
294 return $.when(this._super()).then(function () {
295 return $.when.apply(null, self.model.values.map(function (value) {
296 return new my.FacetValueView(self, value).appendTo($e);
300 model_changed: function () {
301 this.$el.text(this.$el.text() + '*');
304 my.FacetValueView = instance.web.Widget.extend({
305 template: 'SearchView.FacetView.Value',
306 init: function (parent, model) {
309 this.model.on('change', this.model_changed, this);
311 destroy: function () {
312 this.model.off('change', this.model_changed, this);
315 model_changed: function () {
316 this.$el.text(this.$el.text() + '*');
320 instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
321 template: "SearchView",
323 // focus last input if view itself is clicked
324 'click': function (e) {
325 if (e.target === this.$('.oe_searchview_facets')[0]) {
326 this.$('.oe_searchview_input:last').focus();
330 'click div.oe_searchview_search': function (e) {
331 e.stopImmediatePropagation();
334 'click .oe_searchview_unfold_drawer': function (e) {
335 e.stopImmediatePropagation();
336 $(e.target).toggleClass('fa-caret-down')
337 .toggleClass('fa-caret-up');
338 localStorage.visible_search_menu = !(localStorage.visible_search_menu === 'true');
339 this.toggle_buttons();
341 'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
343 case $.ui.keyCode.LEFT:
344 this.focusPreceding(e.target);
347 case $.ui.keyCode.RIGHT:
348 if (!this.autocomplete.is_expandable()) {
349 this.focusFollowing(e.target);
355 'autocompleteopen': function () {
356 this.$el.autocomplete('widget').css('z-index', 9999);
360 * @constructs instance.web.SearchView
361 * @extends instance.web.Widget
367 * @param {Object} [options]
368 * @param {Boolean} [options.hidden=false] hide the search view
369 * @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
371 init: function(parent, dataset, view_id, defaults, options) {
372 this.options = _.defaults(options || {}, {
374 disable_custom_filters: false,
377 this.query = undefined;
378 this.dataset = dataset;
379 this.view_id = view_id;
380 this.search_fields = [];
383 this.visible_filters = !!(localStorage.visible_search_menu === 'true');
384 this.input_subviews = []; // for user input in searchbar
385 this.defaults = defaults || {};
386 this.headless = this.options.hidden && _.isEmpty(this.defaults);
387 this.$buttons = this.options.$buttons;
389 this.filter_menu = undefined;
390 this.groupby_menu = undefined;
391 this.favorite_menu = undefined
397 this.toggle_visibility(false);
398 this.$facets_container = this.$('div.oe_searchview_facets');
399 this.setup_global_completion();
400 this.query = new my.SearchQuery()
401 .on('add change reset remove', this.proxy('do_search'))
402 .on('change', this.proxy('renderChangedFacets'))
403 .on('add reset remove', this.proxy('renderFacets'));
404 var load_view = instance.web.fields_view_get({
405 model: this.dataset._model,
406 view_id: this.view_id,
408 context: this.dataset.get_context(),
410 this.$('.oe_searchview_unfold_drawer')
411 .toggleClass('fa-caret-down', !this.visible_filters)
412 .toggleClass('fa-caret-up', this.visible_filters);
413 return $.when(this._super(), this.alive($.when(load_view))
414 .then(this.view_loaded.bind(this)));
416 view_loaded: function (r) {
418 this.fields_view_get = r;
419 this.prepare_search_inputs();
422 var fields_def = new instance.web.Model(this.dataset.model).call('fields_get', {
423 context: this.dataset.context
426 this.groupby_menu = new my.GroupByMenu(this, this.groupbys, fields_def);
427 this.filter_menu = new my.FilterMenu(this, this.filters, fields_def);
428 this.favorite_menu = new my.FavoriteMenu(this, this.query, this.dataset.model);
430 this.filter_menu.appendTo(this.$buttons);
431 this.groupby_menu.appendTo(this.$buttons);
432 var custom_filters_ready = this.favorite_menu.appendTo(this.$buttons);
434 return $.when(custom_filters_ready).then(this.proxy('set_default_filters'));
436 set_default_filters: function (a, b) {
438 default_custom_filter = this.$buttons && this.favorite_menu.get_default_filter();
439 if (default_custom_filter) {
440 return this.favorite_menu.toggle_filter(default_custom_filter, true);
442 if (!_.isEmpty(this.defaults)) {
443 var inputs = this.search_fields.concat(this.filters, this.groupbys),
444 defaults = _.invoke(inputs, 'facet_for_defaults', this.defaults);
445 return $.when.apply(null, defaults).then(function () {
446 self.query.reset(_(arguments).compact(), {preventSearch: true});
449 this.query.reset([], {preventSearch: true});
453 * Performs the search view collection of widget data.
455 * If the collection went well (all fields are valid), then triggers
456 * :js:func:`instance.web.SearchView.on_search`.
458 * If at least one field failed its validation, triggers
459 * :js:func:`instance.web.SearchView.on_invalid` instead.
462 * @param {Object} [options]
464 do_search: function (_query, options) {
465 if (options && options.preventSearch) {
468 var search = this.build_search_data();
469 this.trigger('search_data', search.domains, search.contexts, search.groupbys);
472 * Extract search data from the view's facets.
474 * Result is an object with 3 (own) properties:
481 * Array of domains, in groupby order rather than view order
485 build_search_data: function () {
486 var domains = [], contexts = [], groupbys = [];
488 this.query.each(function (facet) {
489 var field = facet.get('field');
490 var domain = field.get_domain(facet);
492 domains.push(domain);
494 var context = field.get_context(facet);
496 contexts.push(context);
498 var group_by = field.get_groupby(facet);
500 groupbys.push.apply(groupbys, group_by);
509 toggle_visibility: function (is_visible) {
510 this.$el.toggle(!this.headless && is_visible);
511 this.$buttons && this.$buttons.toggle(!this.headless && is_visible && this.visible_filters);
513 toggle_buttons: function (is_visible) {
514 this.visible_filters = is_visible || !this.visible_filters;
515 this.$buttons && this.$buttons.toggle(this.visible_filters);
518 * Sets up search view's view-wide auto-completion widget
520 setup_global_completion: function () {
522 this.autocomplete = new my.AutoComplete(this, {
523 source: this.proxy('complete_global_search'),
524 select: this.proxy('select_completion'),
526 get_search_string: function () {
527 return self.$('div.oe_searchview_input').text();
530 this.autocomplete.appendTo(this.$el);
533 * Provide auto-completion result for req.term (an array to `resp`)
535 * @param {Object} req request to complete
536 * @param {String} req.term searched term to complete
537 * @param {Function} resp response callback
539 complete_global_search: function (req, resp) {
540 var inputs = this.search_fields.concat(this.filters, this.groupbys);
541 $.when.apply(null, _(inputs).chain()
542 .filter(function (input) { return input.visible(); })
543 .invoke('complete', req.term)
544 .value()).then(function () {
545 resp(_(arguments).chain()
552 * Action to perform in case of selection: create a facet (model)
553 * and add it to the search collection
555 * @param {Object} e selection event, preventDefault to avoid setting value on object
556 * @param {Object} ui selection information
557 * @param {Object} ui.item selected completion item
559 select_completion: function (e, ui) {
561 var input_index = _(this.input_subviews).indexOf(
563 this.$('div.oe_searchview_input:focus')[0]));
564 this.query.add(ui.item.facet, {at: input_index / 2});
566 subviewForRoot: function (subview_root) {
567 return _(this.input_subviews).detect(function (subview) {
568 return subview.$el[0] === subview_root;
571 siblingSubview: function (subview, direction, wrap_around) {
572 var index = _(this.input_subviews).indexOf(subview) + direction;
573 if (wrap_around && index < 0) {
574 index = this.input_subviews.length - 1;
575 } else if (wrap_around && index >= this.input_subviews.length) {
578 return this.input_subviews[index];
580 focusPreceding: function (subview_root) {
581 return this.siblingSubview(
582 this.subviewForRoot(subview_root), -1, true)
585 focusFollowing: function (subview_root) {
586 return this.siblingSubview(
587 this.subviewForRoot(subview_root), +1, true)
591 * @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
592 * @param {openerp.web.search.Facet}
593 * @param {Object} [options]
595 renderFacets: function (collection, model, options) {
598 _.invoke(this.input_subviews, 'destroy');
599 this.input_subviews = [];
601 var i = new my.InputView(this);
602 started.push(i.appendTo(this.$facets_container));
603 this.input_subviews.push(i);
604 this.query.each(function (facet) {
605 var f = new my.FacetView(this, facet);
606 started.push(f.appendTo(self.$facets_container));
607 self.input_subviews.push(f);
609 var i = new my.InputView(this);
610 started.push(i.appendTo(self.$facets_container));
611 self.input_subviews.push(i);
613 _.each(this.input_subviews, function (childView) {
614 childView.on('focused', self, self.proxy('childFocused'));
615 childView.on('blurred', self, self.proxy('childBlurred'));
618 $.when.apply(null, started).then(function () {
619 if (options && options.focus_input === false) return;
621 // options.at: facet inserted at given index, focus next input
622 // otherwise just focus last input
623 if (!options || typeof options.at !== 'number') {
624 input_to_focus = _.last(self.input_subviews);
626 input_to_focus = self.input_subviews[(options.at + 1) * 2];
628 input_to_focus.$el.focus();
631 childFocused: function () {
632 this.$el.addClass('active');
634 childBlurred: function () {
635 var val = this.$el.val();
637 this.$el.removeClass('active')
639 this.autocomplete.close();
642 * Call the renderFacets method with the correct arguments.
643 * This is due to the fact that change events are called with two arguments
644 * (model, options) while add, reset and remove events are called with
645 * (collection, model, options) as arguments
647 renderChangedFacets: function (model, options) {
648 this.renderFacets(undefined, model, options);
650 // it should parse the arch field of the view, instantiate the corresponding
651 // filters/fields, and put them in the correct variables:
652 // * this.search_fields is a list of all the fields,
653 // * this.filters: groups of filters
654 // * this.group_by: group_bys
655 prepare_search_inputs: function () {
657 arch = this.fields_view_get.arch;
659 var filters = [].concat.apply([], _.map(arch.children, function (item) {
660 return item.tag !== 'group' ? eval_item(item) : item.children.map(eval_item);
662 function eval_item (item) {
663 var category = 'filters';
664 if (item.attrs.context) {
666 var context = instance.web.pyeval.eval('context', item.attrs.context);
667 if (context.group_by) {
668 category = 'group_by';
677 var current_group = [],
678 current_category = 'filters',
679 categories = {filters: this.filters, group_by: this.groupbys};
681 _.each(filters.concat({category:'filters', item: 'separator'}), function (filter) {
682 if (filter.item.tag === 'filter' && filter.category === current_category) {
683 return current_group.push(new my.Filter(filter.item, self));
685 if (current_group.length) {
686 var group = new my.FilterGroup(current_group, self);
687 categories[current_category].push(group);
690 if (filter.item.tag === 'field') {
691 var attrs = filter.item.attrs,
692 field = self.fields_view_get.fields[attrs.name],
693 Obj = my.fields.get_any([attrs.widget, field.type]);
695 self.search_fields.push(new (Obj) (filter.item, field, self));
698 if (filter.item.tag === 'filter') {
699 current_group.push(new my.Filter(filter.item, self));
701 current_category = filter.category;
707 * Registry of search fields, called by :js:class:`instance.web.SearchView` to
708 * find and instantiate its field widgets.
710 instance.web.search.fields = new instance.web.Registry({
711 'char': 'instance.web.search.CharField',
712 'text': 'instance.web.search.CharField',
713 'html': 'instance.web.search.CharField',
714 'boolean': 'instance.web.search.BooleanField',
715 'integer': 'instance.web.search.IntegerField',
716 'id': 'instance.web.search.IntegerField',
717 'float': 'instance.web.search.FloatField',
718 'selection': 'instance.web.search.SelectionField',
719 'datetime': 'instance.web.search.DateTimeField',
720 'date': 'instance.web.search.DateField',
721 'many2one': 'instance.web.search.ManyToOneField',
722 'many2many': 'instance.web.search.CharField',
723 'one2many': 'instance.web.search.CharField'
726 instance.web.search.Input = instance.web.Widget.extend( /** @lends instance.web.search.Input# */{
728 * @constructs instance.web.search.Input
729 * @extends instance.web.Widget
733 init: function (parent) {
738 * Fetch auto-completion values for the widget.
740 * The completion values should be an array of objects with keys category,
741 * label, value prefixed with an object with keys type=section and label
743 * @param {String} value value to complete
744 * @returns {jQuery.Deferred<null|Array>}
746 complete: function (value) {
750 * Returns a Facet instance for the provided defaults if they apply to
751 * this widget, or null if they don't.
753 * This default implementation will try calling
754 * :js:func:`instance.web.search.Input#facet_for` if the widget's name
755 * matches the input key
757 * @param {Object} defaults
758 * @returns {jQuery.Deferred<null|Object>}
760 facet_for_defaults: function (defaults) {
762 !(this.attrs.name in defaults && defaults[this.attrs.name])) {
765 return this.facet_for(defaults[this.attrs.name]);
767 get_context: function () {
769 "get_context not implemented for widget " + this.attrs.type);
771 get_groupby: function () {
773 "get_groupby not implemented for widget " + this.attrs.type);
775 get_domain: function () {
777 "get_domain not implemented for widget " + this.attrs.type);
779 load_attrs: function (attrs) {
780 attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
784 * Returns whether the input is "visible". The default behavior is to
785 * query the ``modifiers.invisible`` flag on the input's description or
790 visible: function () {
791 return !this.attrs.modifiers.invisible;
793 // var parent = this;
794 // while ((parent = parent.getParent()) &&
795 // ( (parent instanceof instance.web.search.Group)
796 // || (parent instanceof instance.web.search.Input))) {
797 // if (!parent.visible()) {
804 instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
805 template: 'SearchView.filters',
807 completion_label: _lt("Filter on: %s"),
809 * Inclusive group of filters, creates a continuous "button" with clickable
810 * sections (the normal display for filters is to be a self-contained button)
812 * @constructs instance.web.search.FilterGroup
813 * @extends instance.web.search.Input
815 * @param {Array<instance.web.search.Filter>} filters elements of the group
816 * @param {instance.web.SearchView} parent parent in which the filters are contained
818 init: function (filters, parent) {
819 // If all filters are group_by and we're not initializing a GroupbyGroup,
820 // create a GroupbyGroup instead of the current FilterGroup
821 if (!(this instanceof instance.web.search.GroupbyGroup) &&
822 _(filters).all(function (f) {
823 if (!f.attrs.context) { return false; }
824 var c = instance.web.pyeval.eval('context', f.attrs.context);
825 return !_.isEmpty(c.group_by);})) {
826 return new instance.web.search.GroupbyGroup(filters, parent);
829 this.filters = filters;
830 this.searchview = parent;
831 this.searchview.query.on('add remove change reset', this.proxy('search_change'));
834 this.$el.on('click', 'a', this.proxy('toggle_filter'));
838 * Handles change of the search query: any of the group's filter which is
839 * in the search query should be visually checked in the drawer
841 search_change: function () {
843 var $filters = this.$el.removeClass('selected');
844 var facet = this.searchview.query.find(_.bind(this.match_facet, this));
845 if (!facet) { return; }
846 facet.values.each(function (v) {
847 var i = _(self.filters).indexOf(v.get('value'));
848 if (i === -1) { return; }
849 $filters.filter(function () {
850 return Number($(this).data('index')) === i;
851 }).addClass('selected');
855 * Matches the group to a facet, in order to find if the group is
856 * represented in the current search query
858 match_facet: function (facet) {
859 return facet.get('field') === this;
861 make_facet: function (values) {
863 category: _t("Filter"),
869 make_value: function (filter) {
871 label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
875 facet_for_defaults: function (defaults) {
877 var fs = _(this.filters).chain()
878 .filter(function (f) {
879 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
880 }).map(function (f) {
881 return self.make_value(f);
883 if (_.isEmpty(fs)) { return $.when(null); }
884 return $.when(this.make_facet(fs));
887 * Fetches contexts for all enabled filters in the group
889 * @param {openerp.web.search.Facet} facet
890 * @return {*} combined contexts of the enabled filters in this group
892 get_context: function (facet) {
893 var contexts = facet.values.chain()
894 .map(function (f) { return f.get('value').attrs.context; })
899 if (!contexts.length) { return; }
900 if (contexts.length === 1) { return contexts[0]; }
901 return _.extend(new instance.web.CompoundContext(), {
906 * Fetches group_by sequence for all enabled filters in the group
908 * @param {VS.model.SearchFacet} facet
909 * @return {Array} enabled filters in this group
911 get_groupby: function (facet) {
912 return facet.values.chain()
913 .map(function (f) { return f.get('value').attrs.context; })
919 * Handles domains-fetching for all the filters within it: groups them.
921 * @param {VS.model.SearchFacet} facet
922 * @return {*} combined domains of the enabled filters in this group
924 get_domain: function (facet) {
925 var domains = facet.values.chain()
926 .map(function (f) { return f.get('value').attrs.domain; })
931 if (!domains.length) { return; }
932 if (domains.length === 1) { return domains[0]; }
933 for (var i=domains.length; --i;) {
934 domains.unshift(['|']);
936 return _.extend(new instance.web.CompoundDomain(), {
940 toggle_filter: function (e) {
942 this.toggle(this.filters[Number($(e.target).parent().data('index'))]);
944 toggle: function (filter, options) {
945 this.searchview.query.toggle(this.make_facet([this.make_value(filter)]), options);
947 is_visible: function () {
948 return _.some(this.filters, function (filter) {
949 return !filter.attrs.invisible;
952 complete: function (item) {
954 item = item.toLowerCase();
955 var facet_values = _(this.filters).chain()
956 .filter(function (filter) { return filter.visible(); })
957 .filter(function (filter) {
959 string: filter.attrs.string || '',
960 help: filter.attrs.help || '',
961 name: filter.attrs.name || ''
963 var include = _.str.include;
964 return include(at.string.toLowerCase(), item)
965 || include(at.help.toLowerCase(), item)
966 || include(at.name.toLowerCase(), item);
968 .map(this.make_value)
970 if (_(facet_values).isEmpty()) { return $.when(null); }
971 return $.when(_.map(facet_values, function (facet_value) {
973 label: _.str.sprintf(self.completion_label.toString(),
974 _.escape(facet_value.label)),
975 facet: self.make_facet([facet_value])
980 instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
982 completion_label: _lt("Group by: %s"),
983 init: function (filters, parent) {
984 this._super(filters, parent);
985 this.searchview = parent;
986 // Not flanders: facet unicity is handled through the
987 // (category, field) pair of facet attributes. This is all well and
988 // good for regular filter groups where a group matches a facet, but for
989 // groupby we want a single facet. So cheat: add an attribute on the
990 // view which proxies to the first GroupbyGroup, so it can be used
991 // for every GroupbyGroup and still provides the various methods needed
992 // by the search view. Use weirdo name to avoid risks of conflicts
993 if (!this.searchview._s_groupby) {
994 this.searchview._s_groupby = {
995 help: "See GroupbyGroup#init",
996 get_context: this.proxy('get_context'),
997 get_domain: this.proxy('get_domain'),
998 get_groupby: this.proxy('get_groupby')
1002 match_facet: function (facet) {
1003 return facet.get('field') === this.searchview._s_groupby;
1005 make_facet: function (values) {
1007 category: _t("GroupBy"),
1010 field: this.searchview._s_groupby
1014 instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
1015 template: 'SearchView.filter',
1017 * Implementation of the OpenERP filters (button with a context and/or
1018 * a domain sent as-is to the search view)
1020 * Filters are only attributes holder, the actual work (compositing
1021 * domains and contexts, converting between facets and filters) is
1022 * performed by the filter group.
1024 * @constructs instance.web.search.Filter
1025 * @extends instance.web.search.Input
1030 init: function (node, parent) {
1031 this._super(parent);
1032 this.load_attrs(node.attrs);
1034 facet_for: function () { return $.when(null); },
1035 get_context: function () { },
1036 get_domain: function () { },
1039 instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
1040 template: 'SearchView.field',
1041 default_operator: '=',
1043 * @constructs instance.web.search.Field
1044 * @extends instance.web.search.Input
1046 * @param view_section
1050 init: function (view_section, field, parent) {
1051 this._super(parent);
1052 this.load_attrs(_.extend({}, field, view_section.attrs));
1054 facet_for: function (value) {
1057 category: this.attrs.string || this.attrs.name,
1058 values: [{label: String(value), value: value}]
1061 value_from: function (facetValue) {
1062 return facetValue.get('value');
1064 get_context: function (facet) {
1066 // A field needs a context to send when active
1067 var context = this.attrs.context;
1068 if (_.isEmpty(context) || !facet.values.length) {
1071 var contexts = facet.values.map(function (facetValue) {
1072 return new instance.web.CompoundContext(context)
1073 .set_eval_context({self: self.value_from(facetValue)});
1076 if (contexts.length === 1) { return contexts[0]; }
1078 return _.extend(new instance.web.CompoundContext(), {
1079 __contexts: contexts
1082 get_groupby: function () { },
1084 * Function creating the returned domain for the field, override this
1085 * methods in children if you only need to customize the field's domain
1086 * without more complex alterations or tests (and without the need to
1087 * change override the handling of filter_domain)
1089 * @param {String} name the field's name
1090 * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1091 * @param {Number|String} facet parsed value for the field
1092 * @returns {Array<Array>} domain to include in the resulting search
1094 make_domain: function (name, operator, facet) {
1095 return [[name, operator, this.value_from(facet)]];
1097 get_domain: function (facet) {
1098 if (!facet.values.length) { return; }
1100 var value_to_domain;
1102 var domain = this.attrs['filter_domain'];
1104 value_to_domain = function (facetValue) {
1105 return new instance.web.CompoundDomain(domain)
1106 .set_eval_context({self: self.value_from(facetValue)});
1109 value_to_domain = function (facetValue) {
1110 return self.make_domain(
1112 self.attrs.operator || self.default_operator,
1116 var domains = facet.values.map(value_to_domain);
1118 if (domains.length === 1) { return domains[0]; }
1119 for (var i = domains.length; --i;) {
1120 domains.unshift(['|']);
1123 return _.extend(new instance.web.CompoundDomain(), {
1129 * Implementation of the ``char`` OpenERP field type:
1131 * * Default operator is ``ilike`` rather than ``=``
1133 * * The Javascript and the HTML values are identical (strings)
1136 * @extends instance.web.search.Field
1138 instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
1139 default_operator: 'ilike',
1140 complete: function (value) {
1141 if (_.isEmpty(value)) { return $.when(null); }
1142 var label = _.str.sprintf(_.str.escapeHTML(
1143 _t("Search %(field)s for: %(value)s")), {
1144 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1145 value: '<strong>' + _.escape(value) + '</strong>'});
1149 category: this.attrs.string,
1151 values: [{label: value, value: value}]
1156 instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
1157 complete: function (value) {
1158 var val = this.parse(value);
1159 if (isNaN(val)) { return $.when(); }
1160 var label = _.str.sprintf(
1161 _t("Search %(field)s for: %(value)s"), {
1162 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1163 value: '<strong>' + _.escape(value) + '</strong>'});
1167 category: this.attrs.string,
1169 values: [{label: value, value: val}]
1176 * @extends instance.web.search.NumberField
1178 instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
1179 error_message: _t("not a valid integer"),
1180 parse: function (value) {
1182 return instance.web.parse_value(value, {'widget': 'integer'});
1190 * @extends instance.web.search.NumberField
1192 instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
1193 error_message: _t("not a valid number"),
1194 parse: function (value) {
1196 return instance.web.parse_value(value, {'widget': 'float'});
1204 * Utility function for m2o & selection fields taking a selection/name_get pair
1205 * (value, name) and converting it to a Facet descriptor
1207 * @param {instance.web.search.Field} field holder field
1208 * @param {Array} pair pair value to convert
1210 function facet_from(field, pair) {
1213 category: field.attrs.string,
1214 values: [{label: pair[1], value: pair[0]}]
1220 * @extends instance.web.search.Field
1222 instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
1223 // This implementation is a basic <select> field, but it may have to be
1224 // altered to be more in line with the GTK client, which uses a combo box
1225 // (~ jquery.autocomplete):
1226 // * If an option was selected in the list, behave as currently
1227 // * If something which is not in the list was entered (via the text input),
1228 // the default domain should become (`ilike` string_value) but **any
1229 // ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1230 // is specified. So at least get_domain needs to be quite a bit
1231 // overridden (if there's no @value and there is no filter_domain and
1232 // there is no @operator, return [[name, 'ilike', str_val]]
1233 template: 'SearchView.field.selection',
1235 this._super.apply(this, arguments);
1236 // prepend empty option if there is no empty option in the selection list
1237 this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1241 complete: function (needle) {
1243 var results = _(this.attrs.selection).chain()
1244 .filter(function (sel) {
1245 var value = sel[0], label = sel[1];
1246 if (!value) { return false; }
1247 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1249 .map(function (sel) {
1251 label: _.escape(sel[1]),
1252 facet: facet_from(self, sel)
1255 if (_.isEmpty(results)) { return $.when(null); }
1256 return $.when.call(null, [{
1257 label: _.escape(this.attrs.string)
1258 }].concat(results));
1260 facet_for: function (value) {
1261 var match = _(this.attrs.selection).detect(function (sel) {
1262 return sel[0] === value;
1264 if (!match) { return $.when(null); }
1265 return $.when(facet_from(this, match));
1268 instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
1270 * @constructs instance.web.search.BooleanField
1271 * @extends instance.web.search.BooleanField
1274 this._super.apply(this, arguments);
1275 this.attrs.selection = [
1283 * @extends instance.web.search.DateField
1285 instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
1286 value_from: function (facetValue) {
1287 return instance.web.date_to_str(facetValue.get('value'));
1289 complete: function (needle) {
1290 var d = Date.parse(needle);
1291 if (!d) { return $.when(null); }
1292 var date_string = instance.web.format_value(d, this.attrs);
1293 var label = _.str.sprintf(_.str.escapeHTML(
1294 _t("Search %(field)s at: %(value)s")), {
1295 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1296 value: '<strong>' + date_string + '</strong>'});
1300 category: this.attrs.string,
1302 values: [{label: date_string, value: d}]
1308 * Implementation of the ``datetime`` openerp field type:
1310 * * Uses the same widget as the ``date`` field type (a simple date)
1312 * * Builds a slighly more complex, it's a datetime range (includes time)
1313 * spanning the whole day selected by the date widget
1316 * @extends instance.web.DateField
1318 instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
1319 value_from: function (facetValue) {
1320 return instance.web.datetime_to_str(facetValue.get('value'));
1323 instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
1324 default_operator: {},
1325 init: function (view_section, field, parent) {
1326 this._super(view_section, field, parent);
1327 this.model = new instance.web.Model(this.attrs.relation);
1328 this.searchview = parent;
1331 complete: function (value) {
1332 if (_.isEmpty(value)) { return $.when(null); }
1333 var label = _.str.sprintf(_.str.escapeHTML(
1334 _t("Search %(field)s for: %(value)s")), {
1335 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1336 value: '<strong>' + _.escape(value) + '</strong>'});
1340 category: this.attrs.string,
1342 values: [{label: value, value: value, operator: 'ilike'}]
1344 expand: this.expand.bind(this),
1348 expand: function (needle) {
1350 // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1351 var context = instance.web.pyeval.eval(
1352 'contexts', [this.searchview.dataset.get_context()]);
1353 return this.model.call('name_search', [], {
1355 args: (typeof this.attrs.domain === 'string') ? [] : this.attrs.domain,
1358 }).then(function (results) {
1359 if (_.isEmpty(results)) { return null; }
1360 return _(results).map(function (result) {
1362 label: _.escape(result[1]),
1363 facet: facet_from(self, result)
1368 facet_for: function (value) {
1370 if (value instanceof Array) {
1371 if (value.length === 2 && _.isString(value[1])) {
1372 return $.when(facet_from(this, value));
1374 assert(value.length <= 1,
1375 _t("M2O search fields do not currently handle multiple default values"));
1376 // there are many cases of {search_default_$m2ofield: [id]}, need
1377 // to handle this as if it were a single value.
1380 return this.model.call('name_get', [value]).then(function (names) {
1381 if (_(names).isEmpty()) { return null; }
1382 return facet_from(self, names[0]);
1385 value_from: function (facetValue) {
1386 return facetValue.get('label');
1388 make_domain: function (name, operator, facetValue) {
1389 operator = facetValue.get('operator') || operator;
1392 case this.default_operator:
1393 return [[name, '=', facetValue.get('value')]];
1395 return [[name, 'ilike', facetValue.get('value')]];
1397 return [[name, 'child_of', facetValue.get('value')]];
1399 return this._super(name, operator, facetValue);
1401 get_context: function (facet) {
1402 var values = facet.values;
1403 if (_.isEmpty(this.attrs.context) && values.length === 1) {
1405 c['default_' + this.attrs.name] = values.at(0).get('value');
1408 return this._super(facet);
1412 instance.web.search.FilterMenu = instance.web.Widget.extend({
1413 template: 'SearchView.FilterMenu',
1415 'click .oe-add-filter': function () {
1416 this.toggle_custom_filter_menu();
1418 'click li': function (event) {event.stopImmediatePropagation();},
1419 'hidden.bs.dropdown': function () {
1420 this.toggle_custom_filter_menu(false);
1422 'click .oe-add-condition': 'append_proposition',
1423 'click .oe-apply-filter': 'commit_search',
1425 init: function (parent, filters, fields_def) {
1427 this._super(parent);
1428 this.filters = filters || [];
1429 this.searchview = parent;
1430 this.propositions = [];
1431 this.fields_def = fields_def.then(function (data) {
1433 id: { string: 'ID', type: 'id', searchable: true }
1435 _.each(data, function(field_def, field_name) {
1436 if (field_def.selectable !== false && field_name !== 'id') {
1437 fields[field_name] = field_def;
1443 start: function () {
1445 this.$menu = this.$('.filters-menu');
1446 this.$add_filter = this.$('.oe-add-filter');
1447 this.$apply_filter = this.$('.oe-apply-filter');
1448 this.$add_filter_menu = this.$('.oe-add-filter-menu');
1449 _.each(this.filters, function (group) {
1450 if (group.is_visible()) {
1451 group.insertBefore(self.$add_filter);
1452 $('<li>').addClass('divider').insertBefore(self.$add_filter);
1455 this.append_proposition().then(function (prop) {
1459 toggle_custom_filter_menu: function (is_open) {
1461 .toggleClass('closed-menu', !is_open)
1462 .toggleClass('open-menu', is_open);
1463 this.$add_filter_menu.toggle(is_open);
1464 if (this.$add_filter.hasClass('closed-menu') && (!this.propositions.length)) {
1465 this.append_proposition();
1467 this.$('.oe-filter-condition').toggle(is_open);
1469 append_proposition: function () {
1471 return this.fields_def.then(function (fields) {
1472 var prop = new instance.web.search.ExtendedSearchProposition(self, fields);
1473 self.propositions.push(prop);
1474 prop.insertBefore(self.$add_filter_menu);
1475 self.$apply_filter.prop('disabled', false);
1479 remove_proposition: function (prop) {
1480 this.propositions = _.reject(this.propositions, function (p) { return p === prop});
1481 if (!this.propositions.length) {
1482 this.$apply_filter.prop('disabled', true);
1486 commit_search: function () {
1488 filters = _.invoke(this.propositions, 'get_filter'),
1489 filters_widgets = _.map(filters, function (filter) {
1490 return new my.Filter(filter, self);
1492 var filter_group = new my.FilterGroup(filters_widgets, this.searchview);
1493 filter_group.insertBefore(this.$add_filter);
1494 $('<li>').addClass('divider').insertBefore(self.$add_filter);
1496 filters_widgets.forEach(function (filter) {
1497 self.searchview.query.add(filter_group.make_facet([filter_group.make_value(filter)]), {silent: true});
1499 this.searchview.query.trigger('reset');
1501 _.invoke(this.propositions, 'destroy');
1502 this.propositions = [];
1503 this.append_proposition();
1504 this.toggle_custom_filter_menu(false);
1508 instance.web.search.GroupByMenu = instance.web.Widget.extend({
1509 template: 'SearchView.GroupByMenu',
1511 'click li': function (event) {
1512 event.stopImmediatePropagation();
1514 'hidden.bs.dropdown': function () {
1515 this.toggle_add_menu(false);
1517 'click .add-custom-group a': function () {
1518 this.toggle_add_menu();
1521 init: function (parent, groups, fields_def) {
1522 this._super(parent);
1523 this.groups = groups || [];
1524 this.groupable_fields = {};
1525 this.searchview = parent;
1526 this.fields_def = fields_def.then(this.proxy('get_groupable_fields'));
1528 start: function () {
1530 this.$menu = this.$('.group-by-menu');
1531 var divider = this.$menu.find('.divider');
1532 _.invoke(this.groups, 'insertBefore', divider);
1533 if (this.groups.length) {
1536 this.$add_group = this.$menu.find('.add-custom-group');
1537 this.fields_def.then(function () {
1538 self.$menu.append(QWeb.render('GroupByMenuSelector', self));
1539 self.$add_group_menu = self.$('.oe-add-group');
1540 self.$group_selector = self.$('.oe-group-selector');
1541 self.$('.oe-select-group').click(function (event) {
1542 self.toggle_add_menu(false);
1543 var field = self.$group_selector.find(':selected').data('name');
1544 self.add_groupby_to_menu(field);
1548 get_groupable_fields: function (fields) {
1550 groupable_types = ['many2one', 'char', 'boolean', 'selection', 'date', 'datetime'];
1552 _.each(fields, function (field, name) {
1553 if (field.store && _.contains(groupable_types, field.type)) {
1554 self.groupable_fields[name] = field;
1558 toggle_add_menu: function (is_open) {
1560 .toggleClass('closed-menu', !is_open)
1561 .toggleClass('open-menu', is_open);
1562 this.$add_group_menu.toggle(is_open);
1563 if (this.$add_group.hasClass('open-menu')) {
1564 this.$group_selector.focus();
1567 add_groupby_to_menu: function (field_name) {
1568 var filter = new my.Filter({attrs:{
1569 context:"{'group_by':'" + field_name + "''}",
1570 name: this.groupable_fields[field_name].string,
1571 }}, this.searchview);
1572 var group = new my.FilterGroup([filter], this.searchview),
1573 divider = this.$('.divider').show();
1574 group.insertBefore(divider);
1575 group.toggle(filter);
1579 instance.web.search.FavoriteMenu = instance.web.Widget.extend({
1580 template: 'SearchView.FavoriteMenu',
1582 'click li': function (event) {
1583 event.stopImmediatePropagation();
1585 'click .oe-save-search a': function () {
1586 this.toggle_save_menu();
1588 'click .oe-save-name button': 'save_favorite',
1589 'hidden.bs.dropdown': function () {
1593 init: function (parent, query, target_model) {
1594 this._super.apply(this,arguments);
1595 this.searchview = parent;
1597 this.target_model = target_model;
1598 this.model = new instance.web.Model('ir.filters');
1601 var action = instance.client.action_manager.inner_action;
1602 this.action_id = action && action.id;
1604 start: function () {
1606 this.$save_search = this.$('.oe-save-search');
1607 this.$save_name = this.$('.oe-save-name');
1608 this.$inputs = this.$save_name.find('input');
1609 this.$divider = this.$('.divider');
1611 var $shared_filter = $(this.$inputs[1]),
1612 $default_filter = $(this.$inputs[2]);
1613 $shared_filter.click(function () {$default_filter.prop('checked', false)});
1614 $default_filter.click(function () {$shared_filter.prop('checked', false)});
1617 .on('remove', function (facet) {
1618 if (facet.get('is_custom_filter')) {
1619 self.clear_selection();
1622 .on('reset', this.proxy('clear_selection'));
1623 return this.model.call('get_filters', [this.target_model, this.action_id])
1624 .done(this.proxy('prepare_dropdown_menu'));
1626 prepare_dropdown_menu: function (filters) {
1627 filters.map(this.append_filter.bind(this));
1629 toggle_save_menu: function (is_open) {
1631 .toggleClass('closed-menu', !is_open)
1632 .toggleClass('open-menu', is_open);
1633 this.$save_name.toggle(is_open);
1634 if (this.$save_search.hasClass('open-menu')) {
1635 this.$save_name.find('input').first().focus();
1638 close_menus: function () {
1639 this.toggle_save_menu(false);
1641 save_favorite: function () {
1643 filter_name = this.$inputs[0].value,
1644 shared_filter = this.$inputs[1].checked,
1645 default_filter = this.$inputs[2].checked;
1646 if (!filter_name.length){
1647 this.do_warn(_t("Error"), _t("Filter name is required."));
1648 this.$inputs.first().focus();
1651 var search = this.searchview.build_search_data(),
1652 results = instance.web.pyeval.sync_eval_domains_and_contexts({
1653 domains: search.domains,
1654 contexts: search.contexts,
1655 group_by_seq: search.groupbys || [],
1657 if (!_.isEmpty(results.group_by)) {
1658 results.context.group_by = results.group_by;
1660 // Don't save user_context keys in the custom filter, otherwise end
1661 // up with e.g. wrong uid or lang stored *and used in subsequent
1663 var ctx = results.context;
1664 _(_.keys(instance.session.user_context)).each(function (key) {
1669 user_id: shared_filter ? false : instance.session.uid,
1670 model_id: this.searchview.dataset.model,
1671 context: results.context,
1672 domain: results.domain,
1673 is_default: default_filter,
1674 action_id: this.action_id,
1676 return this.model.call('create_or_replace', [filter]).done(function (id) {
1678 self.toggle_save_menu(false);
1679 self.$save_name.find('input').val('').prop('checked', false);
1680 self.append_filter(filter);
1681 self.toggle_filter(filter, true);
1684 get_default_filter: function () {
1685 var personal_filter = _.find(this.filters, function (filter) {
1686 return filter.user_id && filter.is_default;
1688 if (personal_filter) {
1689 return personal_filter;
1691 return _.find(this.filters, function (filter) {
1692 return !filter.user_id && filter.is_default;
1696 * Generates a mapping key (in the filters and $filter mappings) for the
1697 * filter descriptor object provided (as returned by ``get_filters``).
1699 * The mapping key is guaranteed to be unique for a given (user_id, name)
1702 * @param {Object} filter
1703 * @param {String} filter.name
1704 * @param {Number|Pair<Number, String>} [filter.user_id]
1705 * @return {String} mapping key corresponding to the filter
1707 key_for: function (filter) {
1708 var user_id = filter.user_id,
1709 action_id = filter.action_id,
1710 uid = (user_id instanceof Array) ? user_id[0] : user_id,
1711 act_id = (action_id instanceof Array) ? action_id[0] : action_id;
1712 return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
1715 * Generates a :js:class:`~instance.web.search.Facet` descriptor from a
1718 * @param {Object} filter
1719 * @param {String} filter.name
1720 * @param {Object} [filter.context]
1721 * @param {Array} [filter.domain]
1724 facet_for: function (filter) {
1726 category: _t("Custom Filter"),
1729 get_context: function () { return filter.context; },
1730 get_groupby: function () { return [filter.context]; },
1731 get_domain: function () { return filter.domain; }
1734 is_custom_filter: true,
1735 values: [{label: filter.name, value: null}]
1738 clear_selection: function () {
1739 this.$('li.selected').removeClass('selected');
1741 append_filter: function (filter) {
1743 key = this.key_for(filter),
1745 warning = _t("This filter is global and will be removed for everybody if you continue.");
1747 this.$divider.show();
1748 if (key in this.$filters) {
1749 $filter = this.$filters[key];
1751 this.filters[key] = filter;
1752 $filter = $('<li></li>')
1753 .insertBefore(this.$divider)
1754 .toggleClass('oe_searchview_custom_default', filter.is_default)
1755 .append($('<a>').text(filter.name));
1757 this.$filters[key] = $filter;
1758 this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
1759 : 'oe_searchview_custom_public')
1761 .addClass('fa fa-trash-o')
1762 .click(function (event) {
1763 event.stopImmediatePropagation();
1764 self.remove_filter(filter, $filter, key);
1768 this.$filters[key].unbind('click').click(function (event) {
1769 event.stopPropagation();
1770 self.toggle_filter(filter);
1773 toggle_filter: function (filter, preventSearch) {
1774 var current = this.query.find(function (facet) {
1775 return facet.get('_id') === filter.id;
1778 this.query.remove(current);
1779 this.$filters[this.key_for(filter)].removeClass('selected');
1782 this.query.reset([this.facet_for(filter)], {
1783 preventSearch: preventSearch || false});
1784 this.$filters[this.key_for(filter)].addClass('selected');
1786 remove_filter: function (filter, $filter, key) {
1788 var warning = _t("This filter is global and will be removed for everybody if you continue.");
1789 if (!(filter.user_id || confirm(warning))) {
1792 this.model.call('unlink', [filter.id]).done(function () {
1794 delete self.$filters[key];
1795 delete self.filters[key];
1796 if (_.isEmpty(self.filters)) {
1797 self.$('li.divider').remove();
1803 instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
1804 template: 'SearchView.extended_search.proposition',
1806 'change .searchview_extended_prop_field': 'changed',
1807 'change .searchview_extended_prop_op': 'operator_changed',
1808 'click .searchview_extended_delete_prop': function (e) {
1809 e.stopPropagation();
1810 this.getParent().remove_proposition(this);
1814 * @constructs instance.web.search.ExtendedSearchProposition
1815 * @extends instance.web.Widget
1820 init: function (parent, fields) {
1821 this._super(parent);
1822 this.fields = _(fields).chain()
1823 .map(function(val, key) { return _.extend({}, val, {'name': key}); })
1824 .filter(function (field) { return !field.deprecated && field.searchable; })
1825 .sortBy(function(field) {return field.string;})
1827 this.attrs = {_: _, fields: this.fields, selected: null};
1830 start: function () {
1831 return this._super().done(this.proxy('changed'));
1833 changed: function() {
1834 var nval = this.$(".searchview_extended_prop_field").val();
1835 if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
1836 this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
1839 operator_changed: function (e) {
1840 var $value = this.$('.searchview_extended_prop_value');
1841 switch ($(e.target).val()) {
1851 * Selects the provided field object
1853 * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
1855 select_field: function(field) {
1857 if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
1858 this.value.destroy();
1860 this.$('.searchview_extended_prop_op').html('');
1862 this.attrs.selected = field;
1863 if(field === null || field === undefined) {
1867 var type = field.type;
1868 var Field = instance.web.search.custom_filters.get_object(type);
1870 Field = instance.web.search.custom_filters.get_object("char");
1872 this.value = new Field(this, field);
1873 _.each(this.value.operators, function(operator) {
1874 $('<option>', {value: operator.value})
1875 .text(String(operator.text))
1876 .appendTo(self.$('.searchview_extended_prop_op'));
1878 var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
1879 this.value.appendTo($value_loc);
1882 get_filter: function () {
1883 if (this.attrs.selected === null || this.attrs.selected === undefined)
1885 var field = this.attrs.selected,
1886 op_select = this.$('.searchview_extended_prop_op')[0],
1887 operator = op_select.options[op_select.selectedIndex];
1891 domain: [this.value.get_domain(field, operator)],
1892 string: this.value.get_label(field, operator),
1900 instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
1901 init: function (parent, field) {
1902 this._super(parent);
1905 get_label: function (field, operator) {
1907 switch (operator.value) {
1908 case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
1909 default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
1911 return this.format_label(format, field, operator);
1913 format_label: function (format, field, operator) {
1914 return _.str.sprintf(format, {
1915 field: field.string,
1916 // According to spec, HTMLOptionElement#label should return
1917 // HTMLOptionElement#text when not defined/empty, but it does
1918 // not in older Webkit (between Safari 5.1.5 and Chrome 17) and
1919 // Gecko (pre Firefox 7) browsers, so we need a manual fallback
1921 operator: operator.label || operator.text,
1925 get_domain: function (field, operator) {
1926 switch (operator.value) {
1927 case '∃': return this.make_domain(field.name, '!=', false);
1928 case '∄': return this.make_domain(field.name, '=', false);
1929 default: return this.make_domain(
1930 field.name, operator.value, this.get_value());
1933 make_domain: function (field, operator, value) {
1934 return [field, operator, value];
1937 * Returns a human-readable version of the value, in case the "logical"
1938 * and the "semantic" values of a field differ (as for selection fields,
1941 * The default implementation simply returns the value itself.
1943 * @return {String} human-readable version of the value
1945 toString: function () {
1946 return this.get_value();
1949 instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
1950 template: 'SearchView.extended_search.proposition.char',
1952 {value: "ilike", text: _lt("contains")},
1953 {value: "not ilike", text: _lt("doesn't contain")},
1954 {value: "=", text: _lt("is equal to")},
1955 {value: "!=", text: _lt("is not equal to")},
1956 {value: "∃", text: _lt("is set")},
1957 {value: "∄", text: _lt("is not set")}
1959 get_value: function() {
1960 return this.$el.val();
1963 instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
1964 template: 'SearchView.extended_search.proposition.empty',
1966 {value: "=", text: _lt("is equal to")},
1967 {value: "!=", text: _lt("is not equal to")},
1968 {value: ">", text: _lt("greater than")},
1969 {value: "<", text: _lt("less than")},
1970 {value: ">=", text: _lt("greater or equal than")},
1971 {value: "<=", text: _lt("less or equal than")},
1972 {value: "∃", text: _lt("is set")},
1973 {value: "∄", text: _lt("is not set")}
1976 * Date widgets live in view_form which is not yet loaded when this is
1979 widget: function () { return instance.web.DateTimeWidget; },
1980 get_value: function() {
1981 return this.datewidget.get_value();
1983 toString: function () {
1984 return instance.web.format_value(this.get_value(), { type:"datetime" });
1987 var ready = this._super();
1988 this.datewidget = new (this.widget())(this);
1989 this.datewidget.appendTo(this.$el);
1993 instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
1994 widget: function () { return instance.web.DateWidget; },
1995 toString: function () {
1996 return instance.web.format_value(this.get_value(), { type:"date" });
1999 instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
2000 template: 'SearchView.extended_search.proposition.integer',
2002 {value: "=", text: _lt("is equal to")},
2003 {value: "!=", text: _lt("is not equal to")},
2004 {value: ">", text: _lt("greater than")},
2005 {value: "<", text: _lt("less than")},
2006 {value: ">=", text: _lt("greater or equal than")},
2007 {value: "<=", text: _lt("less or equal than")},
2008 {value: "∃", text: _lt("is set")},
2009 {value: "∄", text: _lt("is not set")}
2011 toString: function () {
2012 return this.$el.val();
2014 get_value: function() {
2016 var val =this.$el.val();
2017 return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
2023 instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
2024 operators: [{value: "=", text: _lt("is")}]
2026 instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
2027 template: 'SearchView.extended_search.proposition.float',
2029 {value: "=", text: _lt("is equal to")},
2030 {value: "!=", text: _lt("is not equal to")},
2031 {value: ">", text: _lt("greater than")},
2032 {value: "<", text: _lt("less than")},
2033 {value: ">=", text: _lt("greater or equal than")},
2034 {value: "<=", text: _lt("less or equal than")},
2035 {value: "∃", text: _lt("is set")},
2036 {value: "∄", text: _lt("is not set")}
2038 toString: function () {
2039 return this.$el.val();
2041 get_value: function() {
2043 var val =this.$el.val();
2044 return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
2050 instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
2051 template: 'SearchView.extended_search.proposition.selection',
2053 {value: "=", text: _lt("is")},
2054 {value: "!=", text: _lt("is not")},
2055 {value: "∃", text: _lt("is set")},
2056 {value: "∄", text: _lt("is not set")}
2058 toString: function () {
2059 var select = this.$el[0];
2060 var option = select.options[select.selectedIndex];
2061 return option.label || option.text;
2063 get_value: function() {
2064 return this.$el.val();
2067 instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
2068 template: 'SearchView.extended_search.proposition.empty',
2070 {value: "=", text: _lt("is true")},
2071 {value: "!=", text: _lt("is false")}
2073 get_label: function (field, operator) {
2074 return this.format_label(
2075 _t('%(field)s %(operator)s'), field, operator);
2077 get_value: function() {
2082 instance.web.search.custom_filters = new instance.web.Registry({
2083 'char': 'instance.web.search.ExtendedSearchProposition.Char',
2084 'text': 'instance.web.search.ExtendedSearchProposition.Char',
2085 'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
2086 'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
2087 'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
2089 'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
2090 'date': 'instance.web.search.ExtendedSearchProposition.Date',
2091 'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
2092 'float': 'instance.web.search.ExtendedSearchProposition.Float',
2093 'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
2094 'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
2096 'id': 'instance.web.search.ExtendedSearchProposition.Id'
2099 instance.web.search.AutoComplete = instance.web.Widget.extend({
2100 template: "SearchView.autocomplete",
2102 // Parameters for autocomplete constructor:
2104 // parent: this is used to detect keyboard events
2106 // options.source: function ({term:query}, callback). This function will be called to
2107 // obtain the search results corresponding to the query string. It is assumed that
2108 // options.source will call callback with the results.
2109 // options.delay: delay in millisecond before calling source. Useful if you don't want
2110 // to make too many rpc calls
2111 // options.select: function (ev, {item: {facet:facet}}). Autocomplete widget will call
2112 // that function when a selection is made by the user
2113 // options.get_search_string: function (). This function will be called by autocomplete
2114 // to obtain the current search string.
2115 init: function (parent, options) {
2116 this._super(parent);
2117 this.$input = parent.$el;
2118 this.source = options.source;
2119 this.delay = options.delay;
2120 this.select = options.select,
2121 this.get_search_string = options.get_search_string;
2123 this.current_result = null;
2125 this.searching = true;
2126 this.search_string = null;
2127 this.current_search = null;
2129 start: function () {
2131 this.$input.on('keyup', function (ev) {
2132 if (ev.which === $.ui.keyCode.RIGHT) {
2133 self.searching = true;
2134 ev.preventDefault();
2137 if (!self.searching) {
2138 self.searching = true;
2141 self.search_string = self.get_search_string();
2142 if (self.search_string.length) {
2143 var search_string = self.search_string;
2144 setTimeout(function () { self.initiate_search(search_string);}, self.delay);
2149 this.$input.on('keydown', function (ev) {
2151 case $.ui.keyCode.TAB:
2152 case $.ui.keyCode.ENTER:
2153 if (self.current_result && self.get_search_string().length) {
2154 self.select_item(ev);
2157 case $.ui.keyCode.DOWN:
2159 self.searching = false;
2160 ev.preventDefault();
2162 case $.ui.keyCode.UP:
2164 self.searching = false;
2165 ev.preventDefault();
2167 case $.ui.keyCode.RIGHT:
2168 self.searching = false;
2169 var current = self.current_result
2170 if (current && current.expand && !current.expanded) {
2172 self.searching = true;
2174 ev.preventDefault();
2176 case $.ui.keyCode.ESCAPE:
2178 self.searching = false;
2183 initiate_search: function (query) {
2184 if (query === this.search_string && query !== this.current_search) {
2188 search: function (query) {
2190 this.current_search = query;
2191 this.source({term:query}, function (results) {
2192 if (results.length) {
2193 self.render_search_results(results);
2194 self.focus_element(self.$('li:first-child'));
2200 render_search_results: function (results) {
2202 var $list = this.$('ul');
2204 var render_separator = false;
2205 results.forEach(function (result) {
2206 if (result.is_separator) {
2207 if (render_separator)
2208 $list.append($('<li>').addClass('oe-separator'));
2209 render_separator = false;
2211 var $item = self.make_list_item(result).appendTo($list);
2213 render_separator = true;
2218 make_list_item: function (result) {
2221 .hover(function (ev) {self.focus_element($li);})
2222 .mousedown(function (ev) {
2223 if (ev.button === 0) { // left button
2224 self.select(ev, {item: {facet: result.facet}});
2227 ev.preventDefault();
2230 .data('result', result);
2231 if (result.expand) {
2232 var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
2233 $expand.mousedown(function (ev) {
2234 ev.preventDefault();
2235 ev.stopPropagation();
2236 if (result.expanded)
2241 result.expanded = false;
2243 if (result.indent) $li.addClass('oe-indent');
2244 $li.append($('<span>').html(result.label));
2247 expand: function () {
2249 this.current_result.expand(this.get_search_string()).then(function (results) {
2250 (results || [{label: '(no result)'}]).reverse().forEach(function (result) {
2251 result.indent = true;
2252 var $li = self.make_list_item(result);
2253 self.current_result.$el.after($li);
2255 self.current_result.expanded = true;
2256 self.current_result.$el.find('span.oe-expand').html('▼');
2260 var $next = this.current_result.$el.next();
2261 while ($next.hasClass('oe-indent')) {
2263 $next = this.current_result.$el.next();
2265 this.current_result.expanded = false;
2266 this.current_result.$el.find('span.oe-expand').html('▶');
2268 focus_element: function ($li) {
2269 this.$('li').removeClass('oe-selection-focus');
2270 $li.addClass('oe-selection-focus');
2271 this.current_result = $li.data('result');
2273 select_item: function (ev) {
2274 if (this.current_result.facet) {
2275 this.select(ev, {item: {facet: this.current_result.facet}});
2282 close: function () {
2283 this.current_search = null;
2284 this.search_string = null;
2285 this.searching = true;
2288 move: function (direction) {
2290 if (direction === 'down') {
2291 $next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
2292 if (!$next.length) $next = this.$('li:first-child');
2294 $next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
2295 if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
2297 this.focus_element($next);
2299 is_expandable: function () {
2300 return !!this.$('.oe-selection-focus .oe-expand').length;
2306 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: