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 fa-caret-up');
337 localStorage.visible_search_menu = (localStorage.visible_search_menu !== 'true');
338 this.toggle_buttons();
340 'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
342 case $.ui.keyCode.LEFT:
343 this.focusPreceding(e.target);
346 case $.ui.keyCode.RIGHT:
347 if (!this.autocomplete.is_expandable()) {
348 this.focusFollowing(e.target);
354 'autocompleteopen': function () {
355 this.$el.autocomplete('widget').css('z-index', 9999);
359 * @constructs instance.web.SearchView
360 * @extends instance.web.Widget
366 * @param {Object} [options]
367 * @param {Boolean} [options.hidden=false] hide the search view
368 * @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
370 init: function(parent, dataset, view_id, defaults, options) {
371 this.options = _.defaults(options || {}, {
373 disable_custom_filters: false,
376 this.query = undefined;
377 this.dataset = dataset;
378 this.view_id = view_id;
379 this.search_fields = [];
382 this.visible_filters = (localStorage.visible_search_menu === 'true');
383 this.input_subviews = []; // for user input in searchbar
384 this.defaults = defaults || {};
385 this.headless = this.options.hidden && _.isEmpty(this.defaults);
386 this.$buttons = this.options.$buttons;
388 this.filter_menu = undefined;
389 this.groupby_menu = undefined;
390 this.favorite_menu = undefined;
391 this.action_id = this.options && this.options.action && this.options.action.id;
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 this.alive($.when(this._super(), load_view.then(this.view_loaded.bind(this))));
415 view_loaded: function (r) {
417 this.fields_view_get = r;
418 this.view_id = this.view_id || r.view_id;
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, this.action_id);
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 // it should parse the arch field of the view, instantiate the corresponding
437 // filters/fields, and put them in the correct variables:
438 // * this.search_fields is a list of all the fields,
439 // * this.filters: groups of filters
440 // * this.group_by: group_bys
441 prepare_search_inputs: function () {
443 arch = this.fields_view_get.arch;
445 var filters = [].concat.apply([], _.map(arch.children, function (item) {
446 return item.tag !== 'group' ? eval_item(item) : item.children.map(eval_item);
448 function eval_item (item) {
449 var category = 'filters';
450 if (item.attrs.context) {
452 var context = instance.web.pyeval.eval('context', item.attrs.context);
453 if (context.group_by) {
454 category = 'group_by';
463 var current_group = [],
464 current_category = 'filters',
465 categories = {filters: this.filters, group_by: this.groupbys};
467 _.each(filters.concat({category:'filters', item: 'separator'}), function (filter) {
468 if (filter.item.tag === 'filter' && filter.category === current_category) {
469 return current_group.push(new my.Filter(filter.item, self));
471 if (current_group.length) {
472 var group = new my.FilterGroup(current_group, self);
473 categories[current_category].push(group);
476 if (filter.item.tag === 'field') {
477 var attrs = filter.item.attrs,
478 field = self.fields_view_get.fields[attrs.name],
479 Obj = my.fields.get_any([attrs.widget, field.type]);
481 self.search_fields.push(new (Obj) (filter.item, field, self));
484 if (filter.item.tag === 'filter') {
485 current_group.push(new my.Filter(filter.item, self));
487 current_category = filter.category;
490 set_default_filters: function () {
492 default_custom_filter = this.$buttons && this.favorite_menu.get_default_filter();
493 if (default_custom_filter) {
494 return this.favorite_menu.toggle_filter(default_custom_filter, true);
496 if (!_.isEmpty(this.defaults)) {
497 var inputs = this.search_fields.concat(this.filters, this.groupbys),
498 defaults = _.invoke(inputs, 'facet_for_defaults', this.defaults);
499 return $.when.apply(null, defaults).then(function () {
500 self.query.reset(_(arguments).compact(), {preventSearch: true});
503 this.query.reset([], {preventSearch: true});
507 * Performs the search view collection of widget data.
509 * If the collection went well (all fields are valid), then triggers
510 * :js:func:`instance.web.SearchView.on_search`.
512 * If at least one field failed its validation, triggers
513 * :js:func:`instance.web.SearchView.on_invalid` instead.
516 * @param {Object} [options]
518 do_search: function (_query, options) {
519 if (options && options.preventSearch) {
522 var search = this.build_search_data();
523 this.trigger('search_data', search.domains, search.contexts, search.groupbys);
526 * Extract search data from the view's facets.
528 * Result is an object with 3 (own) properties:
535 * Array of domains, in groupby order rather than view order
539 build_search_data: function () {
540 var domains = [], contexts = [], groupbys = [];
542 this.query.each(function (facet) {
543 var field = facet.get('field');
544 var domain = field.get_domain(facet);
546 domains.push(domain);
548 var context = field.get_context(facet);
550 contexts.push(context);
552 var group_by = field.get_groupby(facet);
554 groupbys.push.apply(groupbys, group_by);
563 toggle_visibility: function (is_visible) {
564 this.$el.toggle(!this.headless && is_visible);
565 this.$buttons && this.$buttons.toggle(!this.headless && is_visible && this.visible_filters);
567 toggle_buttons: function (is_visible) {
568 this.visible_filters = is_visible || !this.visible_filters;
569 this.$buttons && this.$buttons.toggle(this.visible_filters);
572 * Sets up search view's view-wide auto-completion widget
574 setup_global_completion: function () {
576 this.autocomplete = new my.AutoComplete(this, {
577 source: this.proxy('complete_global_search'),
578 select: this.proxy('select_completion'),
580 get_search_string: function () {
581 return self.$('div.oe_searchview_input').text();
584 this.autocomplete.appendTo(this.$el);
587 * Provide auto-completion result for req.term (an array to `resp`)
589 * @param {Object} req request to complete
590 * @param {String} req.term searched term to complete
591 * @param {Function} resp response callback
593 complete_global_search: function (req, resp) {
594 var inputs = this.search_fields.concat(this.filters, this.groupbys);
595 $.when.apply(null, _(inputs).chain()
596 .filter(function (input) { return input.visible(); })
597 .invoke('complete', req.term)
598 .value()).then(function () {
599 resp(_(arguments).chain()
606 * Action to perform in case of selection: create a facet (model)
607 * and add it to the search collection
609 * @param {Object} e selection event, preventDefault to avoid setting value on object
610 * @param {Object} ui selection information
611 * @param {Object} ui.item selected completion item
613 select_completion: function (e, ui) {
615 var input_index = _(this.input_subviews).indexOf(
617 this.$('div.oe_searchview_input:focus')[0]));
618 this.query.add(ui.item.facet, {at: input_index / 2});
620 subviewForRoot: function (subview_root) {
621 return _(this.input_subviews).detect(function (subview) {
622 return subview.$el[0] === subview_root;
625 siblingSubview: function (subview, direction, wrap_around) {
626 var index = _(this.input_subviews).indexOf(subview) + direction;
627 if (wrap_around && index < 0) {
628 index = this.input_subviews.length - 1;
629 } else if (wrap_around && index >= this.input_subviews.length) {
632 return this.input_subviews[index];
634 focusPreceding: function (subview_root) {
635 return this.siblingSubview(
636 this.subviewForRoot(subview_root), -1, true)
639 focusFollowing: function (subview_root) {
640 return this.siblingSubview(
641 this.subviewForRoot(subview_root), +1, true)
645 * @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
646 * @param {openerp.web.search.Facet}
647 * @param {Object} [options]
649 renderFacets: function (collection, model, options) {
652 _.invoke(this.input_subviews, 'destroy');
653 this.input_subviews = [];
655 var i = new my.InputView(this);
656 started.push(i.appendTo(this.$facets_container));
657 this.input_subviews.push(i);
658 this.query.each(function (facet) {
659 var f = new my.FacetView(this, facet);
660 started.push(f.appendTo(self.$facets_container));
661 self.input_subviews.push(f);
663 var i = new my.InputView(this);
664 started.push(i.appendTo(self.$facets_container));
665 self.input_subviews.push(i);
667 _.each(this.input_subviews, function (childView) {
668 childView.on('focused', self, self.proxy('childFocused'));
669 childView.on('blurred', self, self.proxy('childBlurred'));
672 $.when.apply(null, started).then(function () {
673 if (options && options.focus_input === false) return;
675 // options.at: facet inserted at given index, focus next input
676 // otherwise just focus last input
677 if (!options || typeof options.at !== 'number') {
678 input_to_focus = _.last(self.input_subviews);
680 input_to_focus = self.input_subviews[(options.at + 1) * 2];
682 input_to_focus.$el.focus();
685 childFocused: function () {
686 this.$el.addClass('active');
688 childBlurred: function () {
689 this.$el.val('').removeClass('active').trigger('blur');
690 this.autocomplete.close();
693 * Call the renderFacets method with the correct arguments.
694 * This is due to the fact that change events are called with two arguments
695 * (model, options) while add, reset and remove events are called with
696 * (collection, model, options) as arguments
698 renderChangedFacets: function (model, options) {
699 this.renderFacets(undefined, model, options);
704 * Registry of search fields, called by :js:class:`instance.web.SearchView` to
705 * find and instantiate its field widgets.
707 instance.web.search.fields = new instance.web.Registry({
708 'char': 'instance.web.search.CharField',
709 'text': 'instance.web.search.CharField',
710 'html': 'instance.web.search.CharField',
711 'boolean': 'instance.web.search.BooleanField',
712 'integer': 'instance.web.search.IntegerField',
713 'id': 'instance.web.search.IntegerField',
714 'float': 'instance.web.search.FloatField',
715 'selection': 'instance.web.search.SelectionField',
716 'datetime': 'instance.web.search.DateTimeField',
717 'date': 'instance.web.search.DateField',
718 'many2one': 'instance.web.search.ManyToOneField',
719 'many2many': 'instance.web.search.CharField',
720 'one2many': 'instance.web.search.CharField'
723 instance.web.search.Input = instance.web.Widget.extend( /** @lends instance.web.search.Input# */{
725 * @constructs instance.web.search.Input
726 * @extends instance.web.Widget
730 init: function (parent) {
735 * Fetch auto-completion values for the widget.
737 * The completion values should be an array of objects with keys category,
738 * label, value prefixed with an object with keys type=section and label
740 * @param {String} value value to complete
741 * @returns {jQuery.Deferred<null|Array>}
743 complete: function (value) {
747 * Returns a Facet instance for the provided defaults if they apply to
748 * this widget, or null if they don't.
750 * This default implementation will try calling
751 * :js:func:`instance.web.search.Input#facet_for` if the widget's name
752 * matches the input key
754 * @param {Object} defaults
755 * @returns {jQuery.Deferred<null|Object>}
757 facet_for_defaults: function (defaults) {
759 !(this.attrs.name in defaults && defaults[this.attrs.name])) {
762 return this.facet_for(defaults[this.attrs.name]);
764 get_context: function () {
766 "get_context not implemented for widget " + this.attrs.type);
768 get_groupby: function () {
770 "get_groupby not implemented for widget " + this.attrs.type);
772 get_domain: function () {
774 "get_domain not implemented for widget " + this.attrs.type);
776 load_attrs: function (attrs) {
777 attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
781 * Returns whether the input is "visible". The default behavior is to
782 * query the ``modifiers.invisible`` flag on the input's description or
787 visible: function () {
788 return !this.attrs.modifiers.invisible;
791 instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
792 template: 'SearchView.filters',
794 completion_label: _lt("Filter on: %s"),
796 * Inclusive group of filters, creates a continuous "button" with clickable
797 * sections (the normal display for filters is to be a self-contained button)
799 * @constructs instance.web.search.FilterGroup
800 * @extends instance.web.search.Input
802 * @param {Array<instance.web.search.Filter>} filters elements of the group
803 * @param {instance.web.SearchView} parent parent in which the filters are contained
805 init: function (filters, parent) {
806 // If all filters are group_by and we're not initializing a GroupbyGroup,
807 // create a GroupbyGroup instead of the current FilterGroup
808 if (!(this instanceof instance.web.search.GroupbyGroup) &&
809 _(filters).all(function (f) {
810 if (!f.attrs.context) { return false; }
811 var c = instance.web.pyeval.eval('context', f.attrs.context);
812 return !_.isEmpty(c.group_by);})) {
813 return new instance.web.search.GroupbyGroup(filters, parent);
816 this.filters = filters;
817 this.searchview = parent;
818 this.searchview.query.on('add remove change reset', this.proxy('search_change'));
821 this.$el.on('click', 'a', this.proxy('toggle_filter'));
825 * Handles change of the search query: any of the group's filter which is
826 * in the search query should be visually checked in the drawer
828 search_change: function () {
830 var $filters = this.$el.removeClass('selected');
831 var facet = this.searchview.query.find(_.bind(this.match_facet, this));
832 if (!facet) { return; }
833 facet.values.each(function (v) {
834 var i = _(self.filters).indexOf(v.get('value'));
835 if (i === -1) { return; }
836 $filters.filter(function () {
837 return Number($(this).data('index')) === i;
838 }).addClass('selected');
842 * Matches the group to a facet, in order to find if the group is
843 * represented in the current search query
845 match_facet: function (facet) {
846 return facet.get('field') === this;
848 make_facet: function (values) {
850 category: _t("Filter"),
856 make_value: function (filter) {
858 label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
862 facet_for_defaults: function (defaults) {
864 var fs = _(this.filters).chain()
865 .filter(function (f) {
866 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
867 }).map(function (f) {
868 return self.make_value(f);
870 if (_.isEmpty(fs)) { return $.when(null); }
871 return $.when(this.make_facet(fs));
874 * Fetches contexts for all enabled filters in the group
876 * @param {openerp.web.search.Facet} facet
877 * @return {*} combined contexts of the enabled filters in this group
879 get_context: function (facet) {
880 var contexts = facet.values.chain()
881 .map(function (f) { return f.get('value').attrs.context; })
886 if (!contexts.length) { return; }
887 if (contexts.length === 1) { return contexts[0]; }
888 return _.extend(new instance.web.CompoundContext(), {
893 * Fetches group_by sequence for all enabled filters in the group
895 * @param {VS.model.SearchFacet} facet
896 * @return {Array} enabled filters in this group
898 get_groupby: function (facet) {
899 return facet.values.chain()
900 .map(function (f) { return f.get('value').attrs.context; })
906 * Handles domains-fetching for all the filters within it: groups them.
908 * @param {VS.model.SearchFacet} facet
909 * @return {*} combined domains of the enabled filters in this group
911 get_domain: function (facet) {
912 var domains = facet.values.chain()
913 .map(function (f) { return f.get('value').attrs.domain; })
918 if (!domains.length) { return; }
919 if (domains.length === 1) { return domains[0]; }
920 for (var i=domains.length; --i;) {
921 domains.unshift(['|']);
923 return _.extend(new instance.web.CompoundDomain(), {
927 toggle_filter: function (e) {
929 this.toggle(this.filters[Number($(e.target).parent().data('index'))]);
931 toggle: function (filter, options) {
932 this.searchview.query.toggle(this.make_facet([this.make_value(filter)]), options);
934 is_visible: function () {
935 return _.some(this.filters, function (filter) {
936 return !filter.attrs.invisible;
939 complete: function (item) {
941 item = item.toLowerCase();
942 var facet_values = _(this.filters).chain()
943 .filter(function (filter) { return filter.visible(); })
944 .filter(function (filter) {
946 string: filter.attrs.string || '',
947 help: filter.attrs.help || '',
948 name: filter.attrs.name || ''
950 var include = _.str.include;
951 return include(at.string.toLowerCase(), item)
952 || include(at.help.toLowerCase(), item)
953 || include(at.name.toLowerCase(), item);
955 .map(this.make_value)
957 if (_(facet_values).isEmpty()) { return $.when(null); }
958 return $.when(_.map(facet_values, function (facet_value) {
960 label: _.str.sprintf(self.completion_label.toString(),
961 _.escape(facet_value.label)),
962 facet: self.make_facet([facet_value])
967 instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
969 completion_label: _lt("Group by: %s"),
970 init: function (filters, parent) {
971 this._super(filters, parent);
972 this.searchview = parent;
973 // Not flanders: facet unicity is handled through the
974 // (category, field) pair of facet attributes. This is all well and
975 // good for regular filter groups where a group matches a facet, but for
976 // groupby we want a single facet. So cheat: add an attribute on the
977 // view which proxies to the first GroupbyGroup, so it can be used
978 // for every GroupbyGroup and still provides the various methods needed
979 // by the search view. Use weirdo name to avoid risks of conflicts
980 if (!this.searchview._s_groupby) {
981 this.searchview._s_groupby = {
982 help: "See GroupbyGroup#init",
983 get_context: this.proxy('get_context'),
984 get_domain: this.proxy('get_domain'),
985 get_groupby: this.proxy('get_groupby')
989 match_facet: function (facet) {
990 return facet.get('field') === this.searchview._s_groupby;
992 make_facet: function (values) {
994 category: _t("GroupBy"),
997 field: this.searchview._s_groupby
1001 instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
1002 template: 'SearchView.filter',
1004 * Implementation of the OpenERP filters (button with a context and/or
1005 * a domain sent as-is to the search view)
1007 * Filters are only attributes holder, the actual work (compositing
1008 * domains and contexts, converting between facets and filters) is
1009 * performed by the filter group.
1011 * @constructs instance.web.search.Filter
1012 * @extends instance.web.search.Input
1017 init: function (node, parent) {
1018 this._super(parent);
1019 this.load_attrs(node.attrs);
1021 facet_for: function () { return $.when(null); },
1022 get_context: function () { },
1023 get_domain: function () { },
1026 instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
1027 template: 'SearchView.field',
1028 default_operator: '=',
1030 * @constructs instance.web.search.Field
1031 * @extends instance.web.search.Input
1033 * @param view_section
1037 init: function (view_section, field, parent) {
1038 this._super(parent);
1039 this.load_attrs(_.extend({}, field, view_section.attrs));
1041 facet_for: function (value) {
1044 category: this.attrs.string || this.attrs.name,
1045 values: [{label: String(value), value: value}]
1048 value_from: function (facetValue) {
1049 return facetValue.get('value');
1051 get_context: function (facet) {
1053 // A field needs a context to send when active
1054 var context = this.attrs.context;
1055 if (_.isEmpty(context) || !facet.values.length) {
1058 var contexts = facet.values.map(function (facetValue) {
1059 return new instance.web.CompoundContext(context)
1060 .set_eval_context({self: self.value_from(facetValue)});
1063 if (contexts.length === 1) { return contexts[0]; }
1065 return _.extend(new instance.web.CompoundContext(), {
1066 __contexts: contexts
1069 get_groupby: function () { },
1071 * Function creating the returned domain for the field, override this
1072 * methods in children if you only need to customize the field's domain
1073 * without more complex alterations or tests (and without the need to
1074 * change override the handling of filter_domain)
1076 * @param {String} name the field's name
1077 * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1078 * @param {Number|String} facet parsed value for the field
1079 * @returns {Array<Array>} domain to include in the resulting search
1081 make_domain: function (name, operator, facet) {
1082 return [[name, operator, this.value_from(facet)]];
1084 get_domain: function (facet) {
1085 if (!facet.values.length) { return; }
1087 var value_to_domain;
1089 var domain = this.attrs['filter_domain'];
1091 value_to_domain = function (facetValue) {
1092 return new instance.web.CompoundDomain(domain)
1093 .set_eval_context({self: self.value_from(facetValue)});
1096 value_to_domain = function (facetValue) {
1097 return self.make_domain(
1099 self.attrs.operator || self.default_operator,
1103 var domains = facet.values.map(value_to_domain);
1105 if (domains.length === 1) { return domains[0]; }
1106 for (var i = domains.length; --i;) {
1107 domains.unshift(['|']);
1110 return _.extend(new instance.web.CompoundDomain(), {
1116 * Implementation of the ``char`` OpenERP field type:
1118 * * Default operator is ``ilike`` rather than ``=``
1120 * * The Javascript and the HTML values are identical (strings)
1123 * @extends instance.web.search.Field
1125 instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
1126 default_operator: 'ilike',
1127 complete: function (value) {
1128 if (_.isEmpty(value)) { return $.when(null); }
1129 var label = _.str.sprintf(_.str.escapeHTML(
1130 _t("Search %(field)s for: %(value)s")), {
1131 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1132 value: '<strong>' + _.escape(value) + '</strong>'});
1136 category: this.attrs.string,
1138 values: [{label: value, value: value}]
1143 instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
1144 complete: function (value) {
1145 var val = this.parse(value);
1146 if (isNaN(val)) { return $.when(); }
1147 var label = _.str.sprintf(
1148 _t("Search %(field)s for: %(value)s"), {
1149 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1150 value: '<strong>' + _.escape(value) + '</strong>'});
1154 category: this.attrs.string,
1156 values: [{label: value, value: val}]
1163 * @extends instance.web.search.NumberField
1165 instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
1166 error_message: _t("not a valid integer"),
1167 parse: function (value) {
1169 return instance.web.parse_value(value, {'widget': 'integer'});
1177 * @extends instance.web.search.NumberField
1179 instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
1180 error_message: _t("not a valid number"),
1181 parse: function (value) {
1183 return instance.web.parse_value(value, {'widget': 'float'});
1191 * Utility function for m2o & selection fields taking a selection/name_get pair
1192 * (value, name) and converting it to a Facet descriptor
1194 * @param {instance.web.search.Field} field holder field
1195 * @param {Array} pair pair value to convert
1197 function facet_from(field, pair) {
1200 category: field.attrs.string,
1201 values: [{label: pair[1], value: pair[0]}]
1207 * @extends instance.web.search.Field
1209 instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
1210 // This implementation is a basic <select> field, but it may have to be
1211 // altered to be more in line with the GTK client, which uses a combo box
1212 // (~ jquery.autocomplete):
1213 // * If an option was selected in the list, behave as currently
1214 // * If something which is not in the list was entered (via the text input),
1215 // the default domain should become (`ilike` string_value) but **any
1216 // ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1217 // is specified. So at least get_domain needs to be quite a bit
1218 // overridden (if there's no @value and there is no filter_domain and
1219 // there is no @operator, return [[name, 'ilike', str_val]]
1220 template: 'SearchView.field.selection',
1222 this._super.apply(this, arguments);
1223 // prepend empty option if there is no empty option in the selection list
1224 this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1228 complete: function (needle) {
1230 var results = _(this.attrs.selection).chain()
1231 .filter(function (sel) {
1232 var value = sel[0], label = sel[1];
1233 if (!value) { return false; }
1234 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1236 .map(function (sel) {
1238 label: _.escape(sel[1]),
1239 facet: facet_from(self, sel)
1242 if (_.isEmpty(results)) { return $.when(null); }
1243 return $.when.call(null, [{
1244 label: _.escape(this.attrs.string)
1245 }].concat(results));
1247 facet_for: function (value) {
1248 var match = _(this.attrs.selection).detect(function (sel) {
1249 return sel[0] === value;
1251 if (!match) { return $.when(null); }
1252 return $.when(facet_from(this, match));
1255 instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
1257 * @constructs instance.web.search.BooleanField
1258 * @extends instance.web.search.BooleanField
1261 this._super.apply(this, arguments);
1262 this.attrs.selection = [
1270 * @extends instance.web.search.DateField
1272 instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
1273 value_from: function (facetValue) {
1274 return instance.web.date_to_str(facetValue.get('value'));
1276 complete: function (needle) {
1277 var m = moment(needle);
1278 if (!m.isValid()) { return $.when(null); }
1280 var date_string = instance.web.format_value(d, this.attrs);
1281 var label = _.str.sprintf(_.str.escapeHTML(
1282 _t("Search %(field)s at: %(value)s")), {
1283 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1284 value: '<strong>' + date_string + '</strong>'});
1288 category: this.attrs.string,
1290 values: [{label: date_string, value: d}]
1296 * Implementation of the ``datetime`` openerp field type:
1298 * * Uses the same widget as the ``date`` field type (a simple date)
1300 * * Builds a slighly more complex, it's a datetime range (includes time)
1301 * spanning the whole day selected by the date widget
1304 * @extends instance.web.DateField
1306 instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
1307 value_from: function (facetValue) {
1308 return instance.web.datetime_to_str(facetValue.get('value'));
1311 instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
1312 default_operator: {},
1313 init: function (view_section, field, parent) {
1314 this._super(view_section, field, parent);
1315 this.model = new instance.web.Model(this.attrs.relation);
1316 this.searchview = parent;
1319 complete: function (value) {
1320 if (_.isEmpty(value)) { return $.when(null); }
1321 var label = _.str.sprintf(_.str.escapeHTML(
1322 _t("Search %(field)s for: %(value)s")), {
1323 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1324 value: '<strong>' + _.escape(value) + '</strong>'});
1328 category: this.attrs.string,
1330 values: [{label: value, value: value, operator: 'ilike'}]
1332 expand: this.expand.bind(this),
1336 expand: function (needle) {
1338 // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1339 var context = instance.web.pyeval.eval(
1340 'contexts', [this.searchview.dataset.get_context()]);
1341 return this.model.call('name_search', [], {
1343 args: (typeof this.attrs.domain === 'string') ? [] : this.attrs.domain,
1346 }).then(function (results) {
1347 if (_.isEmpty(results)) { return null; }
1348 return _(results).map(function (result) {
1350 label: _.escape(result[1]),
1351 facet: facet_from(self, result)
1356 facet_for: function (value) {
1358 if (value instanceof Array) {
1359 if (value.length === 2 && _.isString(value[1])) {
1360 return $.when(facet_from(this, value));
1362 assert(value.length <= 1,
1363 _t("M2O search fields do not currently handle multiple default values"));
1364 // there are many cases of {search_default_$m2ofield: [id]}, need
1365 // to handle this as if it were a single value.
1368 return this.model.call('name_get', [value]).then(function (names) {
1369 if (_(names).isEmpty()) { return null; }
1370 return facet_from(self, names[0]);
1373 value_from: function (facetValue) {
1374 return facetValue.get('label');
1376 make_domain: function (name, operator, facetValue) {
1377 operator = facetValue.get('operator') || operator;
1380 case this.default_operator:
1381 return [[name, '=', facetValue.get('value')]];
1383 return [[name, 'ilike', facetValue.get('value')]];
1385 return [[name, 'child_of', facetValue.get('value')]];
1387 return this._super(name, operator, facetValue);
1389 get_context: function (facet) {
1390 var values = facet.values;
1391 if (_.isEmpty(this.attrs.context) && values.length === 1) {
1393 c['default_' + this.attrs.name] = values.at(0).get('value');
1396 return this._super(facet);
1400 instance.web.search.FilterMenu = instance.web.Widget.extend({
1401 template: 'SearchView.FilterMenu',
1403 'click .oe-add-filter': function () {
1404 this.toggle_custom_filter_menu();
1406 'click li': function (event) {event.stopImmediatePropagation();},
1407 'hidden.bs.dropdown': function () {
1408 this.toggle_custom_filter_menu(false);
1410 'click .oe-add-condition': 'append_proposition',
1411 'click .oe-apply-filter': 'commit_search',
1413 init: function (parent, filters, fields_def) {
1415 this._super(parent);
1416 this.filters = filters || [];
1417 this.searchview = parent;
1418 this.propositions = [];
1419 this.fields_def = fields_def.then(function (data) {
1421 id: { string: 'ID', type: 'id', searchable: true }
1423 _.each(data, function(field_def, field_name) {
1424 if (field_def.selectable !== false && field_name !== 'id') {
1425 fields[field_name] = field_def;
1431 start: function () {
1433 this.$menu = this.$('.filters-menu');
1434 this.$add_filter = this.$('.oe-add-filter');
1435 this.$apply_filter = this.$('.oe-apply-filter');
1436 this.$add_filter_menu = this.$('.oe-add-filter-menu');
1437 _.each(this.filters, function (group) {
1438 if (group.is_visible()) {
1439 group.insertBefore(self.$add_filter);
1440 $('<li class="divider">').insertBefore(self.$add_filter);
1443 this.append_proposition().then(function (prop) {
1447 update_max_height: function () {
1448 var max_height = $(window).height() - this.$menu[0].getBoundingClientRect().top - 10;
1449 this.$menu.css('max-height', max_height);
1451 toggle_custom_filter_menu: function (is_open) {
1453 .toggleClass('closed-menu', !is_open)
1454 .toggleClass('open-menu', is_open);
1455 this.$add_filter_menu.toggle(is_open);
1456 if (this.$add_filter.hasClass('closed-menu') && (!this.propositions.length)) {
1457 this.append_proposition();
1459 this.$('.oe-filter-condition').toggle(is_open);
1460 this.update_max_height();
1462 append_proposition: function () {
1464 return this.fields_def.then(function (fields) {
1465 var prop = new instance.web.search.ExtendedSearchProposition(self, fields);
1466 self.propositions.push(prop);
1467 prop.insertBefore(self.$add_filter_menu);
1468 self.$apply_filter.prop('disabled', false);
1469 self.update_max_height();
1473 remove_proposition: function (prop) {
1474 this.propositions = _.without(this.propositions, prop);
1475 if (!this.propositions.length) {
1476 this.$apply_filter.prop('disabled', true);
1480 commit_search: function () {
1481 var filters = _.invoke(this.propositions, 'get_filter'),
1482 filters_widgets = _.map(filters, function (filter) {
1483 return new my.Filter(filter, this);
1485 filter_group = new my.FilterGroup(filters_widgets, this.searchview),
1486 facets = filters_widgets.map(function (filter) {
1487 return filter_group.make_facet([filter_group.make_value(filter)]);
1489 filter_group.insertBefore(this.$add_filter);
1490 $('<li class="divider">').insertBefore(this.$add_filter);
1491 this.searchview.query.add(facets, {silent: true});
1492 this.searchview.query.trigger('reset');
1494 _.invoke(this.propositions, 'destroy');
1495 this.propositions = [];
1496 this.append_proposition();
1497 this.toggle_custom_filter_menu(false);
1501 instance.web.search.GroupByMenu = instance.web.Widget.extend({
1502 template: 'SearchView.GroupByMenu',
1504 'click li': function (event) {
1505 event.stopImmediatePropagation();
1507 'hidden.bs.dropdown': function () {
1508 this.toggle_add_menu(false);
1510 'click .add-custom-group a': function () {
1511 this.toggle_add_menu();
1514 init: function (parent, groups, fields_def) {
1515 this._super(parent);
1516 this.groups = groups || [];
1517 this.groupable_fields = {};
1518 this.searchview = parent;
1519 this.fields_def = fields_def.then(this.proxy('get_groupable_fields'));
1521 start: function () {
1523 this.$menu = this.$('.group-by-menu');
1524 var divider = this.$menu.find('.divider');
1525 _.invoke(this.groups, 'insertBefore', divider);
1526 if (this.groups.length) {
1529 this.$add_group = this.$menu.find('.add-custom-group');
1530 this.fields_def.then(function () {
1531 self.$menu.append(QWeb.render('GroupByMenuSelector', self));
1532 self.$add_group_menu = self.$('.oe-add-group');
1533 self.$group_selector = self.$('.oe-group-selector');
1534 self.$('.oe-select-group').click(function (event) {
1535 self.toggle_add_menu(false);
1536 var field = self.$group_selector.find(':selected').data('name');
1537 self.add_groupby_to_menu(field);
1541 get_groupable_fields: function (fields) {
1543 groupable_types = ['many2one', 'char', 'boolean', 'selection', 'date', 'datetime'];
1545 _.each(fields, function (field, name) {
1546 if (field.store && _.contains(groupable_types, field.type)) {
1547 self.groupable_fields[name] = field;
1551 toggle_add_menu: function (is_open) {
1553 .toggleClass('closed-menu', !is_open)
1554 .toggleClass('open-menu', is_open);
1555 this.$add_group_menu.toggle(is_open);
1556 if (this.$add_group.hasClass('open-menu')) {
1557 this.$group_selector.focus();
1560 add_groupby_to_menu: function (field_name) {
1561 var filter = new my.Filter({attrs:{
1562 context:"{'group_by':'" + field_name + "''}",
1563 name: this.groupable_fields[field_name].string,
1564 }}, this.searchview);
1565 var group = new my.FilterGroup([filter], this.searchview),
1566 divider = this.$('.divider').show();
1567 group.insertBefore(divider);
1568 group.toggle(filter);
1572 instance.web.search.FavoriteMenu = instance.web.Widget.extend({
1573 template: 'SearchView.FavoriteMenu',
1575 'click li': function (event) {
1576 event.stopImmediatePropagation();
1578 'click .oe-save-search a': function () {
1579 this.toggle_save_menu();
1581 'click .oe-save-name button': 'save_favorite',
1582 'hidden.bs.dropdown': function () {
1586 init: function (parent, query, target_model, action_id) {
1587 this._super.apply(this,arguments);
1588 this.searchview = parent;
1590 this.target_model = target_model;
1591 this.model = new instance.web.Model('ir.filters');
1594 this.action_id = action_id;
1596 start: function () {
1598 this.$save_search = this.$('.oe-save-search');
1599 this.$save_name = this.$('.oe-save-name');
1600 this.$inputs = this.$save_name.find('input');
1601 this.$divider = this.$('.divider');
1602 this.$inputs.eq(0).val(this.searchview.getParent().title);
1603 var $shared_filter = this.$inputs.eq(1),
1604 $default_filter = this.$inputs.eq(2);
1605 $shared_filter.click(function () {$default_filter.prop('checked', false)});
1606 $default_filter.click(function () {$shared_filter.prop('checked', false)});
1609 .on('remove', function (facet) {
1610 if (facet.get('is_custom_filter')) {
1611 self.clear_selection();
1614 .on('reset', this.proxy('clear_selection'));
1615 if (!this.action_id) return $.when();
1616 return this.model.call('get_filters', [this.target_model, this.action_id])
1617 .done(this.proxy('prepare_dropdown_menu'));
1619 prepare_dropdown_menu: function (filters) {
1620 filters.map(this.append_filter.bind(this));
1622 toggle_save_menu: function (is_open) {
1624 .toggleClass('closed-menu', !is_open)
1625 .toggleClass('open-menu', is_open);
1626 this.$save_name.toggle(is_open);
1627 if (this.$save_search.hasClass('open-menu')) {
1628 this.$save_name.find('input').first().focus();
1631 close_menus: function () {
1632 this.toggle_save_menu(false);
1634 save_favorite: function () {
1636 filter_name = this.$inputs[0].value,
1637 default_filter = this.$inputs[1].checked,
1638 shared_filter = this.$inputs[2].checked;
1639 if (!filter_name.length){
1640 this.do_warn(_t("Error"), _t("Filter name is required."));
1641 this.$inputs.first().focus();
1644 var search = this.searchview.build_search_data(),
1645 results = instance.web.pyeval.sync_eval_domains_and_contexts({
1646 domains: search.domains,
1647 contexts: search.contexts,
1648 group_by_seq: search.groupbys || [],
1650 if (!_.isEmpty(results.group_by)) {
1651 results.context.group_by = results.group_by;
1653 // Don't save user_context keys in the custom filter, otherwise end
1654 // up with e.g. wrong uid or lang stored *and used in subsequent
1656 var ctx = results.context;
1657 _(_.keys(instance.session.user_context)).each(function (key) {
1662 user_id: shared_filter ? false : instance.session.uid,
1663 model_id: this.searchview.dataset.model,
1664 context: results.context,
1665 domain: results.domain,
1666 is_default: default_filter,
1667 action_id: this.action_id,
1669 return this.model.call('create_or_replace', [filter]).done(function (id) {
1671 self.toggle_save_menu(false);
1672 self.$save_name.find('input').val('').prop('checked', false);
1673 self.append_filter(filter);
1674 self.toggle_filter(filter, true);
1677 get_default_filter: function () {
1678 var personal_filter = _.find(this.filters, function (filter) {
1679 return filter.user_id && filter.is_default;
1681 if (personal_filter) {
1682 return personal_filter;
1684 return _.find(this.filters, function (filter) {
1685 return !filter.user_id && filter.is_default;
1689 * Generates a mapping key (in the filters and $filter mappings) for the
1690 * filter descriptor object provided (as returned by ``get_filters``).
1692 * The mapping key is guaranteed to be unique for a given (user_id, name)
1695 * @param {Object} filter
1696 * @param {String} filter.name
1697 * @param {Number|Pair<Number, String>} [filter.user_id]
1698 * @return {String} mapping key corresponding to the filter
1700 key_for: function (filter) {
1701 var user_id = filter.user_id,
1702 action_id = filter.action_id,
1703 uid = (user_id instanceof Array) ? user_id[0] : user_id,
1704 act_id = (action_id instanceof Array) ? action_id[0] : action_id;
1705 return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
1708 * Generates a :js:class:`~instance.web.search.Facet` descriptor from a
1711 * @param {Object} filter
1712 * @param {String} filter.name
1713 * @param {Object} [filter.context]
1714 * @param {Array} [filter.domain]
1717 facet_for: function (filter) {
1719 category: _t("Custom Filter"),
1722 get_context: function () { return filter.context; },
1723 get_groupby: function () { return [filter.context]; },
1724 get_domain: function () { return filter.domain; }
1727 is_custom_filter: true,
1728 values: [{label: filter.name, value: null}]
1731 clear_selection: function () {
1732 this.$('li.selected').removeClass('selected');
1734 append_filter: function (filter) {
1736 key = this.key_for(filter),
1739 this.$divider.show();
1740 if (key in this.$filters) {
1741 $filter = this.$filters[key];
1743 this.filters[key] = filter;
1744 $filter = $('<li></li>')
1745 .insertBefore(this.$divider)
1746 .toggleClass('oe_searchview_custom_default', filter.is_default)
1747 .append($('<a>').text(filter.name));
1749 this.$filters[key] = $filter;
1750 this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
1751 : 'oe_searchview_custom_public')
1753 .addClass('fa fa-trash-o remove-filter')
1754 .click(function (event) {
1755 event.stopImmediatePropagation();
1756 self.remove_filter(filter, $filter, key);
1760 this.$filters[key].unbind('click').click(function () {
1761 self.toggle_filter(filter);
1764 toggle_filter: function (filter, preventSearch) {
1765 var current = this.query.find(function (facet) {
1766 return facet.get('_id') === filter.id;
1769 this.query.remove(current);
1770 this.$filters[this.key_for(filter)].removeClass('selected');
1773 this.query.reset([this.facet_for(filter)], {
1774 preventSearch: preventSearch || false});
1775 this.$filters[this.key_for(filter)].addClass('selected');
1777 remove_filter: function (filter, $filter, key) {
1779 var global_warning = _t("This filter is global and will be removed for everybody if you continue."),
1780 warning = _t("Are you sure that you want to remove this filter?");
1781 if (!confirm(filter.user_id ? warning : global_warning)) {
1784 this.model.call('unlink', [filter.id]).done(function () {
1786 delete self.$filters[key];
1787 delete self.filters[key];
1788 if (_.isEmpty(self.filters)) {
1789 self.$divider.hide();
1795 instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
1796 template: 'SearchView.extended_search.proposition',
1798 'change .searchview_extended_prop_field': 'changed',
1799 'change .searchview_extended_prop_op': 'operator_changed',
1800 'click .searchview_extended_delete_prop': function (e) {
1801 e.stopPropagation();
1802 this.getParent().remove_proposition(this);
1806 * @constructs instance.web.search.ExtendedSearchProposition
1807 * @extends instance.web.Widget
1812 init: function (parent, fields) {
1813 this._super(parent);
1814 this.fields = _(fields).chain()
1815 .map(function(val, key) { return _.extend({}, val, {'name': key}); })
1816 .filter(function (field) { return !field.deprecated && field.searchable; })
1817 .sortBy(function(field) {return field.string;})
1819 this.attrs = {_: _, fields: this.fields, selected: null};
1822 start: function () {
1823 return this._super().done(this.proxy('changed'));
1825 changed: function() {
1826 var nval = this.$(".searchview_extended_prop_field").val();
1827 if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
1828 this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
1831 operator_changed: function (e) {
1832 var $value = this.$('.searchview_extended_prop_value');
1833 switch ($(e.target).val()) {
1843 * Selects the provided field object
1845 * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
1847 select_field: function(field) {
1849 if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
1850 this.value.destroy();
1852 this.$('.searchview_extended_prop_op').html('');
1854 this.attrs.selected = field;
1855 if(field === null || field === undefined) {
1859 var type = field.type;
1860 var Field = instance.web.search.custom_filters.get_object(type);
1862 Field = instance.web.search.custom_filters.get_object("char");
1864 this.value = new Field(this, field);
1865 _.each(this.value.operators, function(operator) {
1866 $('<option>', {value: operator.value})
1867 .text(String(operator.text))
1868 .appendTo(self.$('.searchview_extended_prop_op'));
1870 var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
1871 this.value.appendTo($value_loc);
1874 get_filter: function () {
1875 if (this.attrs.selected === null || this.attrs.selected === undefined)
1877 var field = this.attrs.selected,
1878 op_select = this.$('.searchview_extended_prop_op')[0],
1879 operator = op_select.options[op_select.selectedIndex];
1883 domain: [this.value.get_domain(field, operator)],
1884 string: this.value.get_label(field, operator),
1892 instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
1893 init: function (parent, field) {
1894 this._super(parent);
1897 get_label: function (field, operator) {
1899 switch (operator.value) {
1900 case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
1901 default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
1903 return this.format_label(format, field, operator);
1905 format_label: function (format, field, operator) {
1906 return _.str.sprintf(format, {
1907 field: field.string,
1908 // According to spec, HTMLOptionElement#label should return
1909 // HTMLOptionElement#text when not defined/empty, but it does
1910 // not in older Webkit (between Safari 5.1.5 and Chrome 17) and
1911 // Gecko (pre Firefox 7) browsers, so we need a manual fallback
1913 operator: operator.label || operator.text,
1917 get_domain: function (field, operator) {
1918 switch (operator.value) {
1919 case '∃': return this.make_domain(field.name, '!=', false);
1920 case '∄': return this.make_domain(field.name, '=', false);
1921 default: return this.make_domain(
1922 field.name, operator.value, this.get_value());
1925 make_domain: function (field, operator, value) {
1926 return [field, operator, value];
1929 * Returns a human-readable version of the value, in case the "logical"
1930 * and the "semantic" values of a field differ (as for selection fields,
1933 * The default implementation simply returns the value itself.
1935 * @return {String} human-readable version of the value
1937 toString: function () {
1938 return this.get_value();
1941 instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
1942 template: 'SearchView.extended_search.proposition.char',
1944 {value: "ilike", text: _lt("contains")},
1945 {value: "not ilike", text: _lt("doesn't contain")},
1946 {value: "=", text: _lt("is equal to")},
1947 {value: "!=", text: _lt("is not equal to")},
1948 {value: "∃", text: _lt("is set")},
1949 {value: "∄", text: _lt("is not set")}
1951 get_value: function() {
1952 return this.$el.val();
1955 instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
1956 template: 'SearchView.extended_search.proposition.empty',
1958 {value: "=", text: _lt("is equal to")},
1959 {value: "!=", text: _lt("is not equal to")},
1960 {value: ">", text: _lt("greater than")},
1961 {value: "<", text: _lt("less than")},
1962 {value: ">=", text: _lt("greater or equal than")},
1963 {value: "<=", text: _lt("less or equal than")},
1964 {value: "∃", text: _lt("is set")},
1965 {value: "∄", text: _lt("is not set")}
1968 * Date widgets live in view_form which is not yet loaded when this is
1971 widget: function () { return instance.web.DateTimeWidget; },
1972 get_value: function() {
1973 return this.datewidget.get_value();
1975 toString: function () {
1976 return instance.web.format_value(this.get_value(), { type:"datetime" });
1979 var ready = this._super();
1980 this.datewidget = new (this.widget())(this);
1981 this.datewidget.appendTo(this.$el);
1985 instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
1986 widget: function () { return instance.web.DateWidget; },
1987 toString: function () {
1988 return instance.web.format_value(this.get_value(), { type:"date" });
1991 instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
1992 template: 'SearchView.extended_search.proposition.integer',
1994 {value: "=", text: _lt("is equal to")},
1995 {value: "!=", text: _lt("is not equal to")},
1996 {value: ">", text: _lt("greater than")},
1997 {value: "<", text: _lt("less than")},
1998 {value: ">=", text: _lt("greater or equal than")},
1999 {value: "<=", text: _lt("less or equal than")},
2000 {value: "∃", text: _lt("is set")},
2001 {value: "∄", text: _lt("is not set")}
2003 toString: function () {
2004 return this.$el.val();
2006 get_value: function() {
2008 var val =this.$el.val();
2009 return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
2015 instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
2016 operators: [{value: "=", text: _lt("is")}]
2018 instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
2019 template: 'SearchView.extended_search.proposition.float',
2021 {value: "=", text: _lt("is equal to")},
2022 {value: "!=", text: _lt("is not equal to")},
2023 {value: ">", text: _lt("greater than")},
2024 {value: "<", text: _lt("less than")},
2025 {value: ">=", text: _lt("greater or equal than")},
2026 {value: "<=", text: _lt("less or equal than")},
2027 {value: "∃", text: _lt("is set")},
2028 {value: "∄", text: _lt("is not set")}
2030 toString: function () {
2031 return this.$el.val();
2033 get_value: function() {
2035 var val =this.$el.val();
2036 return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
2042 instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
2043 template: 'SearchView.extended_search.proposition.selection',
2045 {value: "=", text: _lt("is")},
2046 {value: "!=", text: _lt("is not")},
2047 {value: "∃", text: _lt("is set")},
2048 {value: "∄", text: _lt("is not set")}
2050 toString: function () {
2051 var select = this.$el[0];
2052 var option = select.options[select.selectedIndex];
2053 return option.label || option.text;
2055 get_value: function() {
2056 return this.$el.val();
2059 instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
2060 template: 'SearchView.extended_search.proposition.empty',
2062 {value: "=", text: _lt("is true")},
2063 {value: "!=", text: _lt("is false")}
2065 get_label: function (field, operator) {
2066 return this.format_label(
2067 _t('%(field)s %(operator)s'), field, operator);
2069 get_value: function() {
2074 instance.web.search.custom_filters = new instance.web.Registry({
2075 'char': 'instance.web.search.ExtendedSearchProposition.Char',
2076 'text': 'instance.web.search.ExtendedSearchProposition.Char',
2077 'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
2078 'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
2079 'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
2081 'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
2082 'date': 'instance.web.search.ExtendedSearchProposition.Date',
2083 'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
2084 'float': 'instance.web.search.ExtendedSearchProposition.Float',
2085 'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
2086 'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
2088 'id': 'instance.web.search.ExtendedSearchProposition.Id'
2091 instance.web.search.AutoComplete = instance.web.Widget.extend({
2092 template: "SearchView.autocomplete",
2094 // Parameters for autocomplete constructor:
2096 // parent: this is used to detect keyboard events
2098 // options.source: function ({term:query}, callback). This function will be called to
2099 // obtain the search results corresponding to the query string. It is assumed that
2100 // options.source will call callback with the results.
2101 // options.delay: delay in millisecond before calling source. Useful if you don't want
2102 // to make too many rpc calls
2103 // options.select: function (ev, {item: {facet:facet}}). Autocomplete widget will call
2104 // that function when a selection is made by the user
2105 // options.get_search_string: function (). This function will be called by autocomplete
2106 // to obtain the current search string.
2107 init: function (parent, options) {
2108 this._super(parent);
2109 this.$input = parent.$el;
2110 this.source = options.source;
2111 this.delay = options.delay;
2112 this.select = options.select,
2113 this.get_search_string = options.get_search_string;
2115 this.current_result = null;
2117 this.searching = true;
2118 this.search_string = null;
2119 this.current_search = null;
2121 start: function () {
2123 this.$input.on('keyup', function (ev) {
2124 if (ev.which === $.ui.keyCode.RIGHT) {
2125 self.searching = true;
2126 ev.preventDefault();
2129 if (!self.searching) {
2130 self.searching = true;
2133 self.search_string = self.get_search_string();
2134 if (self.search_string.length) {
2135 var search_string = self.search_string;
2136 setTimeout(function () { self.initiate_search(search_string);}, self.delay);
2141 this.$input.on('keydown', function (ev) {
2143 case $.ui.keyCode.TAB:
2144 case $.ui.keyCode.ENTER:
2145 if (self.current_result && self.get_search_string().length) {
2146 self.select_item(ev);
2149 case $.ui.keyCode.DOWN:
2151 self.searching = false;
2152 ev.preventDefault();
2154 case $.ui.keyCode.UP:
2156 self.searching = false;
2157 ev.preventDefault();
2159 case $.ui.keyCode.RIGHT:
2160 self.searching = false;
2161 var current = self.current_result
2162 if (current && current.expand && !current.expanded) {
2164 self.searching = true;
2166 ev.preventDefault();
2168 case $.ui.keyCode.ESCAPE:
2170 self.searching = false;
2175 initiate_search: function (query) {
2176 if (query === this.search_string && query !== this.current_search) {
2180 search: function (query) {
2182 this.current_search = query;
2183 this.source({term:query}, function (results) {
2184 if (results.length) {
2185 self.render_search_results(results);
2186 self.focus_element(self.$('li:first-child'));
2192 render_search_results: function (results) {
2194 var $list = this.$('ul');
2196 var render_separator = false;
2197 results.forEach(function (result) {
2198 if (result.is_separator) {
2199 if (render_separator)
2200 $list.append($('<li>').addClass('oe-separator'));
2201 render_separator = false;
2203 var $item = self.make_list_item(result).appendTo($list);
2205 render_separator = true;
2210 make_list_item: function (result) {
2213 .hover(function (ev) {self.focus_element($li);})
2214 .mousedown(function (ev) {
2215 if (ev.button === 0) { // left button
2216 self.select(ev, {item: {facet: result.facet}});
2219 ev.preventDefault();
2222 .data('result', result);
2223 if (result.expand) {
2224 var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
2225 $expand.mousedown(function (ev) {
2226 ev.preventDefault();
2227 ev.stopPropagation();
2228 if (result.expanded)
2233 result.expanded = false;
2235 if (result.indent) $li.addClass('oe-indent');
2236 $li.append($('<span>').html(result.label));
2239 expand: function () {
2241 this.current_result.expand(this.get_search_string()).then(function (results) {
2242 (results || [{label: '(no result)'}]).reverse().forEach(function (result) {
2243 result.indent = true;
2244 var $li = self.make_list_item(result);
2245 self.current_result.$el.after($li);
2247 self.current_result.expanded = true;
2248 self.current_result.$el.find('span.oe-expand').html('▼');
2252 var $next = this.current_result.$el.next();
2253 while ($next.hasClass('oe-indent')) {
2255 $next = this.current_result.$el.next();
2257 this.current_result.expanded = false;
2258 this.current_result.$el.find('span.oe-expand').html('▶');
2260 focus_element: function ($li) {
2261 this.$('li').removeClass('oe-selection-focus');
2262 $li.addClass('oe-selection-focus');
2263 this.current_result = $li.data('result');
2265 select_item: function (ev) {
2266 if (this.current_result.facet) {
2267 this.select(ev, {item: {facet: this.current_result.facet}});
2274 close: function () {
2275 this.current_search = null;
2276 this.search_string = null;
2277 this.searching = true;
2280 move: function (direction) {
2282 if (direction === 'down') {
2283 $next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
2284 if (!$next.length) $next = this.$('li:first-child');
2286 $next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
2287 if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
2289 this.focus_element($next);
2291 is_expandable: function () {
2292 return !!this.$('.oe-selection-focus .oe-expand').length;
2298 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: