4 var instance = openerp;
5 openerp.web.search = {};
7 var QWeb = instance.web.qweb,
9 _lt = instance.web._lt;
11 sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); }
15 var my = instance.web.search = {};
18 my.FacetValue = B.Model.extend({
21 my.FacetValues = B.Collection.extend({
24 my.Facet = B.Model.extend({
25 initialize: function (attrs) {
26 var values = attrs.values;
29 B.Model.prototype.initialize.apply(this, arguments);
31 this.values = new my.FacetValues(values || []);
32 this.values.on('add remove change reset', function (_, options) {
33 this.trigger('change', this, options);
37 if (key !== 'values') {
38 return B.Model.prototype.get.call(this, key);
40 return this.values.toJSON();
42 set: function (key, value) {
43 if (key !== 'values') {
44 return B.Model.prototype.set.call(this, key, value);
46 this.values.reset(value);
50 var attrs = this.attributes;
51 for(var att in attrs) {
52 if (!attrs.hasOwnProperty(att) || att === 'field') {
55 out[att] = attrs[att];
57 out.values = this.values.toJSON();
61 my.SearchQuery = B.Collection.extend({
63 initialize: function () {
64 B.Collection.prototype.initialize.apply(
66 this.on('change', function (facet) {
67 if(!facet.values.isEmpty()) { return; }
69 this.remove(facet, {silent: true});
72 add: function (values, options) {
73 options = options || {};
77 } else if (!(values instanceof Array)) {
81 _(values).each(function (value) {
82 var model = this._prepareModel(value, options);
83 var previous = this.detect(function (facet) {
84 return facet.get('category') === model.get('category')
85 && facet.get('field') === model.get('field');
88 previous.values.add(model.get('values'), _.omit(options, 'at', 'merge'));
91 B.Collection.prototype.add.call(this, model, options);
93 // warning: in backbone 1.0+ add is supposed to return the added models,
94 // but here toggle may delegate to add and return its value directly.
95 // return value of neither seems actually used but should be tested
96 // before change, probably
99 toggle: function (value, options) {
100 options = options || {};
102 var facet = this.detect(function (facet) {
103 return facet.get('category') === value.category
104 && facet.get('field') === value.field;
107 return this.add(value, options);
111 _(value.values).each(function (val) {
112 var already_value = facet.values.detect(function (v) {
113 return v.get('value') === val.value
114 && v.get('label') === val.label;
118 facet.values.remove(already_value, {silent: true});
120 facet.values.add(val, {silent: true});
124 // "Commit" changes to values array as a single call, so observers of
125 // change event don't get misled by intermediate incomplete toggling
127 facet.trigger('change', facet);
132 function assert(condition, message) {
134 throw new Error(message);
137 my.InputView = instance.web.Widget.extend({
138 template: 'SearchView.InputView',
140 focus: function () { this.trigger('focused', this); },
141 blur: function () { this.$el.text(''); this.trigger('blurred', this); },
142 keydown: 'onKeydown',
145 getSelection: function () {
148 var root = this.el.childNodes[0];
149 if (!root || !root.textContent) {
150 // if input does not have a child node, or the child node is an
151 // empty string, then the selection can only be (0, 0)
152 return {start: 0, end: 0};
154 var range = window.getSelection().getRangeAt(0);
155 // In Firefox, depending on the way text is selected (drag, double- or
156 // triple-click) the range may start or end on the parent of the
157 // selected text node‽ Check for this condition and fixup the range
158 // note: apparently with C-a this can go even higher?
159 if (range.startContainer === this.el && range.startOffset === 0) {
160 range.setStart(root, 0);
162 if (range.endContainer === this.el && range.endOffset === 1) {
163 range.setEnd(root, root.length);
165 assert(range.startContainer === root,
166 "selection should be in the input view");
167 assert(range.endContainer === root,
168 "selection should be in the input view");
170 start: range.startOffset,
174 onKeydown: function (e) {
178 // Do not insert newline, but let it bubble so searchview can use it
179 case $.ui.keyCode.ENTER:
183 // FIXME: may forget content if non-empty but caret at index 0, ok?
184 case $.ui.keyCode.BACKSPACE:
185 sel = this.getSelection();
186 if (sel.start === 0 && sel.start === sel.end) {
188 var preceding = this.getParent().siblingSubview(this, -1);
189 if (preceding && (preceding instanceof my.FacetView)) {
190 preceding.model.destroy();
195 // let left/right events propagate to view if caret is at input border
196 // and not a selection
197 case $.ui.keyCode.LEFT:
198 sel = this.getSelection();
199 if (sel.start !== 0 || sel.start !== sel.end) {
203 case $.ui.keyCode.RIGHT:
204 sel = this.getSelection();
205 var len = this.$el.text().length;
206 if (sel.start !== len || sel.start !== sel.end) {
212 setCursorAtEnd: function () {
214 var sel = window.getSelection();
215 sel.removeAllRanges();
216 var range = document.createRange();
217 // in theory, range.selectNodeContents should work here. In practice,
218 // MSIE9 has issues from time to time, instead of selecting the inner
219 // text node it would select the reference node instead (e.g. in demo
220 // data, company news, copy across the "Company News" link + the title,
221 // from about half the link to half the text, paste in search box then
222 // hit the left arrow key, getSelection would blow up).
224 // Explicitly selecting only the inner text node (only child node
225 // since we've normalized the parent) avoids the issue
226 range.selectNode(this.el.childNodes[0]);
227 range.collapse(false);
230 onPaste: function () {
232 // In MSIE and Webkit, it is possible to get various representations of
233 // the clipboard data at this point e.g.
234 // window.clipboardData.getData('Text') and
235 // event.clipboardData.getData('text/plain') to ensure we have a plain
236 // text representation of the object (and probably ensure the object is
237 // pastable as well, so nobody puts an image in the search view)
238 // (nb: since it's not possible to alter the content of the clipboard
239 // — at least in Webkit — to ensure only textual content is available,
240 // using this would require 1. getting the text data; 2. manually
241 // inserting the text data into the content; and 3. cancelling the
244 // But Firefox doesn't support the clipboard API (as of FF18)
245 // although it correctly triggers the paste event (Opera does not even
246 // do that) => implement lowest-denominator system where onPaste
247 // triggers a followup "cleanup" pass after the data has been pasted
248 setTimeout(function () {
249 // Read text content (ignore pasted HTML)
250 var data = this.$el.text();
253 // paste raw text back in
254 this.$el.empty().text(data);
256 // Set the cursor at the end of the text, so the cursor is not lost
257 // in some kind of error-spawning limbo.
258 this.setCursorAtEnd();
262 my.FacetView = instance.web.Widget.extend({
263 template: 'SearchView.FacetView',
265 'focus': function () { this.trigger('focused', this); },
266 'blur': function () { this.trigger('blurred', this); },
267 'click': function (e) {
268 if ($(e.target).is('.oe_facet_remove')) {
269 this.model.destroy();
275 'keydown': function (e) {
276 var keys = $.ui.keyCode;
280 this.model.destroy();
285 init: function (parent, model) {
288 this.model.on('change', this.model_changed, this);
290 destroy: function () {
291 this.model.off('change', this.model_changed, this);
296 var $e = this.$('> span:last-child');
297 return $.when(this._super()).then(function () {
298 return $.when.apply(null, self.model.values.map(function (value) {
299 return new my.FacetValueView(self, value).appendTo($e);
303 model_changed: function () {
304 this.$el.text(this.$el.text() + '*');
307 my.FacetValueView = instance.web.Widget.extend({
308 template: 'SearchView.FacetView.Value',
309 init: function (parent, model) {
312 this.model.on('change', this.model_changed, this);
314 destroy: function () {
315 this.model.off('change', this.model_changed, this);
318 model_changed: function () {
319 this.$el.text(this.$el.text() + '*');
323 instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{
324 template: "SearchView",
326 // focus last input if view itself is clicked
327 'click': function (e) {
328 if (e.target === this.$('.oe_searchview_facets')[0]) {
329 this.$('.oe_searchview_input:last').focus();
333 'click button.oe_searchview_search': function (e) {
334 e.stopImmediatePropagation();
337 'click .oe_searchview_clear': function (e) {
338 e.stopImmediatePropagation();
341 'click .oe_searchview_unfold_drawer': function (e) {
342 e.stopImmediatePropagation();
344 this.drawer.toggle();
346 'keydown .oe_searchview_input, .oe_searchview_facet': function (e) {
348 case $.ui.keyCode.LEFT:
349 this.focusPreceding(e.target);
352 case $.ui.keyCode.RIGHT:
353 if (!this.autocomplete.is_expandable()) {
354 this.focusFollowing(e.target);
360 'autocompleteopen': function () {
361 this.$el.autocomplete('widget').css('z-index', 9999);
365 * @constructs instance.web.SearchView
366 * @extends instance.web.Widget
372 * @param {Object} [options]
373 * @param {Boolean} [options.hidden=false] hide the search view
374 * @param {Boolean} [options.disable_custom_filters=false] do not load custom filters from ir.filters
376 init: function(parent, dataset, view_id, defaults, options) {
377 this.options = _.defaults(options || {}, {
379 disable_custom_filters: false,
382 this.dataset = dataset;
383 this.model = dataset.model;
384 this.view_id = view_id;
386 this.defaults = defaults || {};
387 this.has_defaults = !_.isEmpty(this.defaults);
389 this.headless = this.options.hidden && !this.has_defaults;
391 this.input_subviews = [];
392 this.view_manager = null;
393 this.$view_manager_header = null;
395 this.ready = $.Deferred();
396 this.drawer_ready = $.Deferred();
397 this.fields_view_get = $.Deferred();
398 this.drawer = new instance.web.SearchViewDrawer(parent, this);
403 var p = this._super();
405 this.$view_manager_header = this.$el.parents(".oe_view_manager_header").first();
407 this.setup_global_completion();
408 this.query = new my.SearchQuery()
409 .on('add change reset remove', this.proxy('do_search'))
410 .on('change', this.proxy('renderChangedFacets'))
411 .on('add reset remove', this.proxy('renderFacets'));
413 if (this.options.hidden) {
417 this.ready.resolve();
419 var load_view = instance.web.fields_view_get({
420 model: this.dataset._model,
421 view_id: this.view_id,
423 context: this.dataset.get_context(),
426 this.alive($.when(load_view)).then(function (r) {
427 self.fields_view_get.resolve(r);
428 return self.search_view_loaded(r);
429 }).fail(function () {
430 self.ready.reject.apply(null, arguments);
434 var view_manager = this.getParent();
435 while (!(view_manager instanceof instance.web.ViewManager) &&
436 view_manager && view_manager.getParent) {
437 view_manager = view_manager.getParent();
441 this.view_manager = view_manager;
442 view_manager.on('switch_mode', this, function (e) {
443 self.drawer.toggle(e === 'graph');
446 return $.when(p, this.ready);
449 set_drawer: function (drawer) {
450 this.drawer = drawer;
460 subviewForRoot: function (subview_root) {
461 return _(this.input_subviews).detect(function (subview) {
462 return subview.$el[0] === subview_root;
465 siblingSubview: function (subview, direction, wrap_around) {
466 var index = _(this.input_subviews).indexOf(subview) + direction;
467 if (wrap_around && index < 0) {
468 index = this.input_subviews.length - 1;
469 } else if (wrap_around && index >= this.input_subviews.length) {
472 return this.input_subviews[index];
474 focusPreceding: function (subview_root) {
475 return this.siblingSubview(
476 this.subviewForRoot(subview_root), -1, true)
479 focusFollowing: function (subview_root) {
480 return this.siblingSubview(
481 this.subviewForRoot(subview_root), +1, true)
486 * Sets up search view's view-wide auto-completion widget
488 setup_global_completion: function () {
490 this.autocomplete = new instance.web.search.AutoComplete(this, {
491 source: this.proxy('complete_global_search'),
492 select: this.proxy('select_completion'),
494 get_search_string: function () {
495 return self.$('div.oe_searchview_input').text();
497 width: this.$el.width(),
499 this.autocomplete.appendTo(this.$el);
502 * Provide auto-completion result for req.term (an array to `resp`)
504 * @param {Object} req request to complete
505 * @param {String} req.term searched term to complete
506 * @param {Function} resp response callback
508 complete_global_search: function (req, resp) {
509 $.when.apply(null, _(this.drawer.inputs).chain()
510 .filter(function (input) { return input.visible(); })
511 .invoke('complete', req.term)
512 .value()).then(function () {
513 resp(_(arguments).chain()
521 * Action to perform in case of selection: create a facet (model)
522 * and add it to the search collection
524 * @param {Object} e selection event, preventDefault to avoid setting value on object
525 * @param {Object} ui selection information
526 * @param {Object} ui.item selected completion item
528 select_completion: function (e, ui) {
531 var input_index = _(this.input_subviews).indexOf(
533 this.$('div.oe_searchview_input:focus')[0]));
534 this.query.add(ui.item.facet, {at: input_index / 2});
536 childFocused: function () {
537 this.$el.addClass('oe_focused');
539 childBlurred: function () {
540 var val = this.$el.val();
542 this.$el.removeClass('oe_focused')
544 this.autocomplete.close();
547 * Call the renderFacets method with the correct arguments.
548 * This is due to the fact that change events are called with two arguments
549 * (model, options) while add, reset and remove events are called with
550 * (collection, model, options) as arguments
552 renderChangedFacets: function (model, options) {
553 this.renderFacets(undefined, model, options);
556 * @param {openerp.web.search.SearchQuery | undefined} Undefined if event is change
557 * @param {openerp.web.search.Facet}
558 * @param {Object} [options]
560 renderFacets: function (collection, model, options) {
563 var $e = this.$('div.oe_searchview_facets');
564 _.invoke(this.input_subviews, 'destroy');
565 this.input_subviews = [];
567 var i = new my.InputView(this);
568 started.push(i.appendTo($e));
569 this.input_subviews.push(i);
570 this.query.each(function (facet) {
571 var f = new my.FacetView(this, facet);
572 started.push(f.appendTo($e));
573 self.input_subviews.push(f);
575 var i = new my.InputView(this);
576 started.push(i.appendTo($e));
577 self.input_subviews.push(i);
579 _.each(this.input_subviews, function (childView) {
580 childView.on('focused', self, self.proxy('childFocused'));
581 childView.on('blurred', self, self.proxy('childBlurred'));
584 $.when.apply(null, started).then(function () {
585 if (options && options.focus_input === false) return;
587 // options.at: facet inserted at given index, focus next input
588 // otherwise just focus last input
589 if (!options || typeof options.at !== 'number') {
590 input_to_focus = _.last(self.input_subviews);
592 input_to_focus = self.input_subviews[(options.at + 1) * 2];
594 input_to_focus.$el.focus();
598 search_view_loaded: function(data) {
600 this.fields_view = data;
601 if (data.type !== 'search' ||
602 data.arch.tag !== 'search') {
603 throw new Error(_.str.sprintf(
604 "Got non-search view after asking for a search view: type %s, arch root %s",
605 data.type, data.arch.tag));
608 return this.drawer_ready
609 .then(this.proxy('setup_default_query'))
611 self.trigger("search_view_loaded", data);
612 self.ready.resolve();
615 setup_default_query: function () {
616 // Hacky implementation of CustomFilters#facet_for_defaults ensure
617 // CustomFilters will be ready (and CustomFilters#filters will be
618 // correctly filled) by the time this method executes.
619 var custom_filters = this.drawer.custom_filters.filters;
620 if (!this.options.disable_custom_filters && !_(custom_filters).isEmpty()) {
621 // Check for any is_default custom filter
622 var personal_filter = _(custom_filters).find(function (filter) {
623 return filter.user_id && filter.is_default;
625 if (personal_filter) {
626 this.drawer.custom_filters.toggle_filter(personal_filter, true);
630 var global_filter = _(custom_filters).find(function (filter) {
631 return !filter.user_id && filter.is_default;
634 this.drawer.custom_filters.toggle_filter(global_filter, true);
638 // No custom filter, or no is_default custom filter, apply view defaults
639 this.query.reset(_(arguments).compact(), {preventSearch: true});
642 * Extract search data from the view's facets.
644 * Result is an object with 4 (own) properties:
647 * An array of any error generated during data validation and
648 * extraction, contains the validation error objects
654 * Array of domains, in groupby order rather than view order
658 build_search_data: function () {
659 var domains = [], contexts = [], groupbys = [], errors = [];
661 this.query.each(function (facet) {
662 var field = facet.get('field');
664 var domain = field.get_domain(facet);
666 domains.push(domain);
668 var context = field.get_context(facet);
670 contexts.push(context);
672 var group_by = field.get_groupby(facet);
674 groupbys.push.apply(groupbys, group_by);
677 if (e instanceof instance.web.search.Invalid) {
692 * Performs the search view collection of widget data.
694 * If the collection went well (all fields are valid), then triggers
695 * :js:func:`instance.web.SearchView.on_search`.
697 * If at least one field failed its validation, triggers
698 * :js:func:`instance.web.SearchView.on_invalid` instead.
701 * @param {Object} [options]
703 do_search: function (_query, options) {
704 if (options && options.preventSearch) {
707 var search = this.build_search_data();
708 if (!_.isEmpty(search.errors)) {
709 this.on_invalid(search.errors);
712 this.trigger('search_data', search.domains, search.contexts, search.groupbys);
715 * Triggered after the SearchView has collected all relevant domains and
718 * It is provided with an Array of domains and an Array of contexts, which
719 * may or may not be evaluated (each item can be either a valid domain or
720 * context, or a string to evaluate in order in the sequence)
722 * It is also passed an array of contexts used for group_by (they are in
723 * the correct order for group_by evaluation, which contexts may not be)
726 * @param {Array} domains an array of literal domains or domain references
727 * @param {Array} contexts an array of literal contexts or context refs
728 * @param {Array} groupbys ordered contexts which may or may not have group_by keys
731 * Triggered after a validation error in the SearchView fields.
733 * Error objects have three keys:
734 * * ``field`` is the name of the invalid field
735 * * ``value`` is the invalid value
736 * * ``message`` is the (in)validation message provided by the field
739 * @param {Array} errors a never-empty array of error objects
741 on_invalid: function (errors) {
742 this.do_notify(_t("Invalid Search"), _t("triggered from search view"));
743 this.trigger('invalid_search', errors);
746 // The method appendTo is overwrited to be able to insert the drawer anywhere
747 appendTo: function ($searchview_parent, $searchview_drawer_node) {
748 var $searchview_drawer_node = $searchview_drawer_node || $searchview_parent;
751 this._super($searchview_parent),
752 this.drawer.appendTo($searchview_drawer_node)
756 destroy: function () {
757 this.drawer.destroy();
758 this.getParent().destroy.call(this);
762 instance.web.SearchViewDrawer = instance.web.Widget.extend({
763 template: "SearchViewDrawer",
765 init: function(parent, searchview) {
767 this.searchview = searchview;
768 this.searchview.set_drawer(this);
769 this.ready = searchview.drawer_ready;
774 toggle: function (visibility) {
775 this.$el.toggle(visibility);
776 var $view_manager_body = this.$el.closest('.oe_view_manager_body');
777 if ($view_manager_body.length) {
778 $view_manager_body.scrollTop(0);
784 if (this.searchview.headless) return $.when(this._super(), this.searchview.ready);
785 var filters_ready = this.searchview.fields_view_get
786 .then(this.proxy('prepare_filters'));
787 return $.when(this._super(), filters_ready).then(function () {
788 var defaults = arguments[1][0];
789 self.ready.resolve.apply(null, defaults);
792 prepare_filters: function (data) {
794 data['arch'].children,
797 this.add_common_inputs();
800 var in_drawer = this.select_for_drawer();
802 var $first_col = this.$(".col-md-7"),
803 $snd_col = this.$(".col-md-5");
805 var add_custom_filters = in_drawer[0].appendTo($first_col),
806 add_filters = in_drawer[1].appendTo($first_col),
807 add_rest = $.when.apply(null, _(in_drawer.slice(2)).invoke('appendTo', $snd_col)),
808 defaults_fetched = $.when.apply(null, _(this.inputs).invoke(
809 'facet_for_defaults', this.searchview.defaults));
811 return $.when(defaults_fetched, add_custom_filters, add_filters, add_rest);
814 * Sets up thingie where all the mess is put?
816 select_for_drawer: function () {
817 return _(this.inputs).filter(function (input) {
818 return input.in_drawer();
823 * Builds a list of widget rows (each row is an array of widgets)
825 * @param {Array} items a list of nodes to convert to widgets
826 * @param {Object} fields a mapping of field names to (ORM) field attributes
827 * @param {Object} [group] group to put the new controls in
829 make_widgets: function (items, fields, group) {
831 group = new instance.web.search.Group(
832 this, 'q', {attrs: {string: _t("Filters")}});
836 _.each(items, function (item) {
837 if (filters.length && item.tag !== 'filter') {
838 group.push(new instance.web.search.FilterGroup(filters, group));
843 case 'separator': case 'newline':
846 filters.push(new instance.web.search.Filter(item, group));
849 self.add_separator();
850 self.make_widgets(item.children, fields,
851 new instance.web.search.Group(group, 'w', item));
852 self.add_separator();
855 var field = this.make_field(
856 item, fields[item['attrs'].name], group);
859 self.make_widgets(item.children, fields, group);
864 if (filters.length) {
865 group.push(new instance.web.search.FilterGroup(filters, this));
869 add_separator: function () {
870 if (!(_.last(this.inputs) instanceof instance.web.search.Separator))
871 new instance.web.search.Separator(this);
874 * Creates a field for the provided field descriptor item (which comes
875 * from fields_view_get)
877 * @param {Object} item fields_view_get node for the field
878 * @param {Object} field fields_get result for the field
879 * @param {Object} [parent]
880 * @returns instance.web.search.Field
882 make_field: function (item, field, parent) {
883 // M2O combined with selection widget is pointless and broken in search views,
884 // but has been used in the past for unsupported hacks -> ignore it
885 if (field.type === "many2one" && item.attrs.widget === "selection"){
886 item.attrs.widget = undefined;
888 var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]);
890 return new (obj) (item, field, parent || this);
892 console.group('Unknown field type ' + field.type);
893 console.error('View node', item);
894 console.info('View field', field);
895 console.info('In view', this);
901 add_common_inputs: function() {
902 // add custom filters to this.inputs
903 this.custom_filters = new instance.web.search.CustomFilters(this);
904 // add Filters to this.inputs, need view.controls filled
905 (new instance.web.search.Filters(this));
906 (new instance.web.search.SaveFilter(this, this.custom_filters));
907 // add Advanced to this.inputs
908 (new instance.web.search.Advanced(this));
914 * Registry of search fields, called by :js:class:`instance.web.SearchView` to
915 * find and instantiate its field widgets.
917 instance.web.search.fields = new instance.web.Registry({
918 'char': 'instance.web.search.CharField',
919 'text': 'instance.web.search.CharField',
920 'html': 'instance.web.search.CharField',
921 'boolean': 'instance.web.search.BooleanField',
922 'integer': 'instance.web.search.IntegerField',
923 'id': 'instance.web.search.IntegerField',
924 'float': 'instance.web.search.FloatField',
925 'selection': 'instance.web.search.SelectionField',
926 'datetime': 'instance.web.search.DateTimeField',
927 'date': 'instance.web.search.DateField',
928 'many2one': 'instance.web.search.ManyToOneField',
929 'many2many': 'instance.web.search.CharField',
930 'one2many': 'instance.web.search.CharField'
932 instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{
934 * Exception thrown by search widgets when they hold invalid values,
935 * which they can not return when asked.
937 * @constructs instance.web.search.Invalid
938 * @extends instance.web.Class
940 * @param field the name of the field holding an invalid value
941 * @param value the invalid value
942 * @param message validation failure message
944 init: function (field, value, message) {
947 this.message = message;
949 toString: function () {
950 return _.str.sprintf(
951 _t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"),
952 {fieldname: this.field, value: this.value, message: this.message}
956 instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{
959 * Root class of all search widgets
961 * @constructs instance.web.search.Widget
962 * @extends instance.web.Widget
964 * @param parent parent of this widget
966 init: function (parent) {
968 var ancestor = parent;
970 this.drawer = ancestor;
971 } while (!(ancestor instanceof instance.web.SearchViewDrawer)
972 && (ancestor = (ancestor.getParent && ancestor.getParent())));
973 this.view = this.drawer.searchview || this.drawer;
977 instance.web.search.add_expand_listener = function($root) {
978 $root.find('a.searchview_group_string').click(function (e) {
979 $root.toggleClass('folded expanded');
984 instance.web.search.Group = instance.web.search.Widget.extend({
985 init: function (parent, icon, node) {
987 var attrs = node.attrs;
988 this.modifiers = attrs.modifiers =
989 attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
992 this.name = attrs.string;
995 this.drawer.controls.push(this);
997 push: function (input) {
998 this.children.push(input);
1000 visible: function () {
1001 return !this.modifiers.invisible;
1005 instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{
1008 * @constructs instance.web.search.Input
1009 * @extends instance.web.search.Widget
1013 init: function (parent) {
1014 this._super(parent);
1015 this.load_attrs({});
1016 this.drawer.inputs.push(this);
1019 * Fetch auto-completion values for the widget.
1021 * The completion values should be an array of objects with keys category,
1022 * label, value prefixed with an object with keys type=section and label
1024 * @param {String} value value to complete
1025 * @returns {jQuery.Deferred<null|Array>}
1027 complete: function (value) {
1028 return $.when(null);
1031 * Returns a Facet instance for the provided defaults if they apply to
1032 * this widget, or null if they don't.
1034 * This default implementation will try calling
1035 * :js:func:`instance.web.search.Input#facet_for` if the widget's name
1036 * matches the input key
1038 * @param {Object} defaults
1039 * @returns {jQuery.Deferred<null|Object>}
1041 facet_for_defaults: function (defaults) {
1043 !(this.attrs.name in defaults && defaults[this.attrs.name])) {
1044 return $.when(null);
1046 return this.facet_for(defaults[this.attrs.name]);
1048 in_drawer: function () {
1049 return !!this._in_drawer;
1051 get_context: function () {
1053 "get_context not implemented for widget " + this.attrs.type);
1055 get_groupby: function () {
1057 "get_groupby not implemented for widget " + this.attrs.type);
1059 get_domain: function () {
1061 "get_domain not implemented for widget " + this.attrs.type);
1063 load_attrs: function (attrs) {
1064 attrs.modifiers = attrs.modifiers ? JSON.parse(attrs.modifiers) : {};
1068 * Returns whether the input is "visible". The default behavior is to
1069 * query the ``modifiers.invisible`` flag on the input's description or
1072 * @returns {Boolean}
1074 visible: function () {
1075 if (this.attrs.modifiers.invisible) {
1079 while ((parent = parent.getParent()) &&
1080 ( (parent instanceof instance.web.search.Group)
1081 || (parent instanceof instance.web.search.Input))) {
1082 if (!parent.visible()) {
1089 instance.web.search.FilterGroup = instance.web.search.Input.extend(/** @lends instance.web.search.FilterGroup# */{
1090 template: 'SearchView.filters',
1092 completion_label: _lt("Filter on: %s"),
1094 * Inclusive group of filters, creates a continuous "button" with clickable
1095 * sections (the normal display for filters is to be a self-contained button)
1097 * @constructs instance.web.search.FilterGroup
1098 * @extends instance.web.search.Input
1100 * @param {Array<instance.web.search.Filter>} filters elements of the group
1101 * @param {instance.web.SearchView} parent parent in which the filters are contained
1103 init: function (filters, parent) {
1104 // If all filters are group_by and we're not initializing a GroupbyGroup,
1105 // create a GroupbyGroup instead of the current FilterGroup
1106 if (!(this instanceof instance.web.search.GroupbyGroup) &&
1107 _(filters).all(function (f) {
1108 if (!f.attrs.context) { return false; }
1109 var c = instance.web.pyeval.eval('context', f.attrs.context);
1110 return !_.isEmpty(c.group_by);})) {
1111 return new instance.web.search.GroupbyGroup(filters, parent);
1113 this._super(parent);
1114 this.filters = filters;
1115 this.view.query.on('add remove change reset', this.proxy('search_change'));
1117 start: function () {
1118 this.$el.on('click', 'li', this.proxy('toggle_filter'));
1119 return $.when(null);
1122 * Handles change of the search query: any of the group's filter which is
1123 * in the search query should be visually checked in the drawer
1125 search_change: function () {
1127 var $filters = this.$('> li').removeClass('badge');
1128 var facet = this.view.query.find(_.bind(this.match_facet, this));
1129 if (!facet) { return; }
1130 facet.values.each(function (v) {
1131 var i = _(self.filters).indexOf(v.get('value'));
1132 if (i === -1) { return; }
1133 $filters.filter(function () {
1134 return Number($(this).data('index')) === i;
1135 }).addClass('badge');
1139 * Matches the group to a facet, in order to find if the group is
1140 * represented in the current search query
1142 match_facet: function (facet) {
1143 return facet.get('field') === this;
1145 make_facet: function (values) {
1147 category: _t("Filter"),
1153 make_value: function (filter) {
1155 label: filter.attrs.string || filter.attrs.help || filter.attrs.name,
1159 facet_for_defaults: function (defaults) {
1161 var fs = _(this.filters).chain()
1162 .filter(function (f) {
1163 return f.attrs && f.attrs.name && !!defaults[f.attrs.name];
1164 }).map(function (f) {
1165 return self.make_value(f);
1167 if (_.isEmpty(fs)) { return $.when(null); }
1168 return $.when(this.make_facet(fs));
1171 * Fetches contexts for all enabled filters in the group
1173 * @param {openerp.web.search.Facet} facet
1174 * @return {*} combined contexts of the enabled filters in this group
1176 get_context: function (facet) {
1177 var contexts = facet.values.chain()
1178 .map(function (f) { return f.get('value').attrs.context; })
1183 if (!contexts.length) { return; }
1184 if (contexts.length === 1) { return contexts[0]; }
1185 return _.extend(new instance.web.CompoundContext(), {
1186 __contexts: contexts
1190 * Fetches group_by sequence for all enabled filters in the group
1192 * @param {VS.model.SearchFacet} facet
1193 * @return {Array} enabled filters in this group
1195 get_groupby: function (facet) {
1196 return facet.values.chain()
1197 .map(function (f) { return f.get('value').attrs.context; })
1203 * Handles domains-fetching for all the filters within it: groups them.
1205 * @param {VS.model.SearchFacet} facet
1206 * @return {*} combined domains of the enabled filters in this group
1208 get_domain: function (facet) {
1209 var domains = facet.values.chain()
1210 .map(function (f) { return f.get('value').attrs.domain; })
1215 if (!domains.length) { return; }
1216 if (domains.length === 1) { return domains[0]; }
1217 for (var i=domains.length; --i;) {
1218 domains.unshift(['|']);
1220 return _.extend(new instance.web.CompoundDomain(), {
1224 toggle_filter: function (e) {
1225 this.toggle(this.filters[Number($(e.target).data('index'))]);
1227 toggle: function (filter) {
1228 this.view.query.toggle(this.make_facet([this.make_value(filter)]));
1230 complete: function (item) {
1232 item = item.toLowerCase();
1233 var facet_values = _(this.filters).chain()
1234 .filter(function (filter) { return filter.visible(); })
1235 .filter(function (filter) {
1237 string: filter.attrs.string || '',
1238 help: filter.attrs.help || '',
1239 name: filter.attrs.name || ''
1241 var include = _.str.include;
1242 return include(at.string.toLowerCase(), item)
1243 || include(at.help.toLowerCase(), item)
1244 || include(at.name.toLowerCase(), item);
1246 .map(this.make_value)
1248 if (_(facet_values).isEmpty()) { return $.when(null); }
1249 return $.when(_.map(facet_values, function (facet_value) {
1251 label: _.str.sprintf(self.completion_label.toString(),
1252 _.escape(facet_value.label)),
1253 facet: self.make_facet([facet_value])
1258 instance.web.search.GroupbyGroup = instance.web.search.FilterGroup.extend({
1260 completion_label: _lt("Group by: %s"),
1261 init: function (filters, parent) {
1262 this._super(filters, parent);
1263 // Not flanders: facet unicity is handled through the
1264 // (category, field) pair of facet attributes. This is all well and
1265 // good for regular filter groups where a group matches a facet, but for
1266 // groupby we want a single facet. So cheat: add an attribute on the
1267 // view which proxies to the first GroupbyGroup, so it can be used
1268 // for every GroupbyGroup and still provides the various methods needed
1269 // by the search view. Use weirdo name to avoid risks of conflicts
1270 if (!this.view._s_groupby) {
1271 this.view._s_groupby = {
1272 help: "See GroupbyGroup#init",
1273 get_context: this.proxy('get_context'),
1274 get_domain: this.proxy('get_domain'),
1275 get_groupby: this.proxy('get_groupby')
1279 match_facet: function (facet) {
1280 return facet.get('field') === this.view._s_groupby;
1282 make_facet: function (values) {
1284 category: _t("GroupBy"),
1287 field: this.view._s_groupby
1291 instance.web.search.Filter = instance.web.search.Input.extend(/** @lends instance.web.search.Filter# */{
1292 template: 'SearchView.filter',
1294 * Implementation of the OpenERP filters (button with a context and/or
1295 * a domain sent as-is to the search view)
1297 * Filters are only attributes holder, the actual work (compositing
1298 * domains and contexts, converting between facets and filters) is
1299 * performed by the filter group.
1301 * @constructs instance.web.search.Filter
1302 * @extends instance.web.search.Input
1307 init: function (node, parent) {
1308 this._super(parent);
1309 this.load_attrs(node.attrs);
1311 facet_for: function () { return $.when(null); },
1312 get_context: function () { },
1313 get_domain: function () { },
1316 instance.web.search.Separator = instance.web.search.Input.extend({
1319 complete: function () {
1320 return {is_separator: true};
1324 instance.web.search.Field = instance.web.search.Input.extend( /** @lends instance.web.search.Field# */ {
1325 template: 'SearchView.field',
1326 default_operator: '=',
1328 * @constructs instance.web.search.Field
1329 * @extends instance.web.search.Input
1331 * @param view_section
1335 init: function (view_section, field, parent) {
1336 this._super(parent);
1337 this.load_attrs(_.extend({}, field, view_section.attrs));
1339 facet_for: function (value) {
1342 category: this.attrs.string || this.attrs.name,
1343 values: [{label: String(value), value: value}]
1346 value_from: function (facetValue) {
1347 return facetValue.get('value');
1349 get_context: function (facet) {
1351 // A field needs a context to send when active
1352 var context = this.attrs.context;
1353 if (_.isEmpty(context) || !facet.values.length) {
1356 var contexts = facet.values.map(function (facetValue) {
1357 return new instance.web.CompoundContext(context)
1358 .set_eval_context({self: self.value_from(facetValue)});
1361 if (contexts.length === 1) { return contexts[0]; }
1363 return _.extend(new instance.web.CompoundContext(), {
1364 __contexts: contexts
1367 get_groupby: function () { },
1369 * Function creating the returned domain for the field, override this
1370 * methods in children if you only need to customize the field's domain
1371 * without more complex alterations or tests (and without the need to
1372 * change override the handling of filter_domain)
1374 * @param {String} name the field's name
1375 * @param {String} operator the field's operator (either attribute-specified or default operator for the field
1376 * @param {Number|String} facet parsed value for the field
1377 * @returns {Array<Array>} domain to include in the resulting search
1379 make_domain: function (name, operator, facet) {
1380 return [[name, operator, this.value_from(facet)]];
1382 get_domain: function (facet) {
1383 if (!facet.values.length) { return; }
1385 var value_to_domain;
1387 var domain = this.attrs['filter_domain'];
1389 value_to_domain = function (facetValue) {
1390 return new instance.web.CompoundDomain(domain)
1391 .set_eval_context({self: self.value_from(facetValue)});
1394 value_to_domain = function (facetValue) {
1395 return self.make_domain(
1397 self.attrs.operator || self.default_operator,
1401 var domains = facet.values.map(value_to_domain);
1403 if (domains.length === 1) { return domains[0]; }
1404 for (var i = domains.length; --i;) {
1405 domains.unshift(['|']);
1408 return _.extend(new instance.web.CompoundDomain(), {
1414 * Implementation of the ``char`` OpenERP field type:
1416 * * Default operator is ``ilike`` rather than ``=``
1418 * * The Javascript and the HTML values are identical (strings)
1421 * @extends instance.web.search.Field
1423 instance.web.search.CharField = instance.web.search.Field.extend( /** @lends instance.web.search.CharField# */ {
1424 default_operator: 'ilike',
1425 complete: function (value) {
1426 if (_.isEmpty(value)) { return $.when(null); }
1427 var label = _.str.sprintf(_.str.escapeHTML(
1428 _t("Search %(field)s for: %(value)s")), {
1429 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1430 value: '<strong>' + _.escape(value) + '</strong>'});
1434 category: this.attrs.string,
1436 values: [{label: value, value: value}]
1441 instance.web.search.NumberField = instance.web.search.Field.extend(/** @lends instance.web.search.NumberField# */{
1442 complete: function (value) {
1443 var val = this.parse(value);
1444 if (isNaN(val)) { return $.when(); }
1445 var label = _.str.sprintf(
1446 _t("Search %(field)s for: %(value)s"), {
1447 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1448 value: '<strong>' + _.escape(value) + '</strong>'});
1452 category: this.attrs.string,
1454 values: [{label: value, value: val}]
1461 * @extends instance.web.search.NumberField
1463 instance.web.search.IntegerField = instance.web.search.NumberField.extend(/** @lends instance.web.search.IntegerField# */{
1464 error_message: _t("not a valid integer"),
1465 parse: function (value) {
1467 return instance.web.parse_value(value, {'widget': 'integer'});
1475 * @extends instance.web.search.NumberField
1477 instance.web.search.FloatField = instance.web.search.NumberField.extend(/** @lends instance.web.search.FloatField# */{
1478 error_message: _t("not a valid number"),
1479 parse: function (value) {
1481 return instance.web.parse_value(value, {'widget': 'float'});
1489 * Utility function for m2o & selection fields taking a selection/name_get pair
1490 * (value, name) and converting it to a Facet descriptor
1492 * @param {instance.web.search.Field} field holder field
1493 * @param {Array} pair pair value to convert
1495 function facet_from(field, pair) {
1498 category: field['attrs'].string,
1499 values: [{label: pair[1], value: pair[0]}]
1505 * @extends instance.web.search.Field
1507 instance.web.search.SelectionField = instance.web.search.Field.extend(/** @lends instance.web.search.SelectionField# */{
1508 // This implementation is a basic <select> field, but it may have to be
1509 // altered to be more in line with the GTK client, which uses a combo box
1510 // (~ jquery.autocomplete):
1511 // * If an option was selected in the list, behave as currently
1512 // * If something which is not in the list was entered (via the text input),
1513 // the default domain should become (`ilike` string_value) but **any
1514 // ``context`` or ``filter_domain`` becomes falsy, idem if ``@operator``
1515 // is specified. So at least get_domain needs to be quite a bit
1516 // overridden (if there's no @value and there is no filter_domain and
1517 // there is no @operator, return [[name, 'ilike', str_val]]
1518 template: 'SearchView.field.selection',
1520 this._super.apply(this, arguments);
1521 // prepend empty option if there is no empty option in the selection list
1522 this.prepend_empty = !_(this.attrs.selection).detect(function (item) {
1526 complete: function (needle) {
1528 var results = _(this.attrs.selection).chain()
1529 .filter(function (sel) {
1530 var value = sel[0], label = sel[1];
1531 if (!value) { return false; }
1532 return label.toLowerCase().indexOf(needle.toLowerCase()) !== -1;
1534 .map(function (sel) {
1536 label: _.escape(sel[1]),
1537 facet: facet_from(self, sel)
1540 if (_.isEmpty(results)) { return $.when(null); }
1541 return $.when.call(null, [{
1542 label: _.escape(this.attrs.string)
1543 }].concat(results));
1545 facet_for: function (value) {
1546 var match = _(this.attrs.selection).detect(function (sel) {
1547 return sel[0] === value;
1549 if (!match) { return $.when(null); }
1550 return $.when(facet_from(this, match));
1553 instance.web.search.BooleanField = instance.web.search.SelectionField.extend(/** @lends instance.web.search.BooleanField# */{
1555 * @constructs instance.web.search.BooleanField
1556 * @extends instance.web.search.BooleanField
1559 this._super.apply(this, arguments);
1560 this.attrs.selection = [
1568 * @extends instance.web.search.DateField
1570 instance.web.search.DateField = instance.web.search.Field.extend(/** @lends instance.web.search.DateField# */{
1571 value_from: function (facetValue) {
1572 return instance.web.date_to_str(facetValue.get('value'));
1574 complete: function (needle) {
1576 var d = instance.web.str_to_date(instance.web.parse_value(needle, {'widget': 'date'}));
1580 if (!d) { return $.when(null); }
1581 var date_string = instance.web.format_value(d, this.attrs);
1582 var label = _.str.sprintf(_.str.escapeHTML(
1583 _t("Search %(field)s at: %(value)s")), {
1584 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1585 value: '<strong>' + date_string + '</strong>'});
1589 category: this.attrs.string,
1591 values: [{label: date_string, value: d}]
1597 * Implementation of the ``datetime`` openerp field type:
1599 * * Uses the same widget as the ``date`` field type (a simple date)
1601 * * Builds a slighly more complex, it's a datetime range (includes time)
1602 * spanning the whole day selected by the date widget
1605 * @extends instance.web.DateField
1607 instance.web.search.DateTimeField = instance.web.search.DateField.extend(/** @lends instance.web.search.DateTimeField# */{
1608 value_from: function (facetValue) {
1609 return instance.web.datetime_to_str(facetValue.get('value'));
1612 instance.web.search.ManyToOneField = instance.web.search.CharField.extend({
1613 default_operator: {},
1614 init: function (view_section, field, parent) {
1615 this._super(view_section, field, parent);
1616 this.model = new instance.web.Model(this.attrs.relation);
1619 complete: function (value) {
1620 if (_.isEmpty(value)) { return $.when(null); }
1621 var label = _.str.sprintf(_.str.escapeHTML(
1622 _t("Search %(field)s for: %(value)s")), {
1623 field: '<em>' + _.escape(this.attrs.string) + '</em>',
1624 value: '<strong>' + _.escape(value) + '</strong>'});
1628 category: this.attrs.string,
1630 values: [{label: value, value: value, operator: 'ilike'}]
1632 expand: this.expand.bind(this),
1636 expand: function (needle) {
1638 // FIXME: "concurrent" searches (multiple requests, mis-ordered responses)
1639 var context = instance.web.pyeval.eval(
1640 'contexts', [this.view.dataset.get_context()]);
1641 return this.model.call('name_search', [], {
1643 args: (typeof this.attrs.domain === 'string') ? [] : this.attrs.domain,
1646 }).then(function (results) {
1647 if (_.isEmpty(results)) { return null; }
1648 return _(results).map(function (result) {
1650 label: _.escape(result[1]),
1651 facet: facet_from(self, result)
1656 facet_for: function (value) {
1658 if (value instanceof Array) {
1659 if (value.length === 2 && _.isString(value[1])) {
1660 return $.when(facet_from(this, value));
1662 assert(value.length <= 1,
1663 _t("M2O search fields do not currently handle multiple default values"));
1664 // there are many cases of {search_default_$m2ofield: [id]}, need
1665 // to handle this as if it were a single value.
1668 return this.model.call('name_get', [value]).then(function (names) {
1669 if (_(names).isEmpty()) { return null; }
1670 return facet_from(self, names[0]);
1673 value_from: function (facetValue) {
1674 return facetValue.get('label');
1676 make_domain: function (name, operator, facetValue) {
1677 operator = facetValue.get('operator') || operator;
1680 case this.default_operator:
1681 return [[name, '=', facetValue.get('value')]];
1683 return [[name, 'ilike', facetValue.get('value')]];
1685 return [[name, 'child_of', facetValue.get('value')]];
1687 return this._super(name, operator, facetValue);
1689 get_context: function (facet) {
1690 var values = facet.values;
1691 if (_.isEmpty(this.attrs.context) && values.length === 1) {
1693 c['default_' + this.attrs.name] = values.at(0).get('value');
1696 return this._super(facet);
1700 instance.web.search.CustomFilters = instance.web.search.Input.extend({
1701 template: 'SearchView.Custom',
1704 this.is_ready = $.Deferred();
1705 this._super.apply(this,arguments);
1707 start: function () {
1709 this.model = new instance.web.Model('ir.filters');
1713 .on('remove', function (facet) {
1714 if (!facet.get('is_custom_filter')) {
1717 self.clear_selection();
1719 .on('reset', this.proxy('clear_selection'));
1720 return this.model.call('get_filters', [this.view.model, this.get_action_id()])
1721 .then(this.proxy('set_filters'))
1722 .done(function () { self.is_ready.resolve(); })
1723 .fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); });
1725 get_action_id: function(){
1726 var action = instance.client.action_manager.inner_action;
1727 if (action) return action.id;
1730 * Special implementation delaying defaults until CustomFilters is loaded
1732 facet_for_defaults: function () {
1733 return this.is_ready;
1736 * Generates a mapping key (in the filters and $filter mappings) for the
1737 * filter descriptor object provided (as returned by ``get_filters``).
1739 * The mapping key is guaranteed to be unique for a given (user_id, name)
1742 * @param {Object} filter
1743 * @param {String} filter.name
1744 * @param {Number|Pair<Number, String>} [filter.user_id]
1745 * @return {String} mapping key corresponding to the filter
1747 key_for: function (filter) {
1748 var user_id = filter.user_id,
1749 action_id = filter.action_id;
1750 var uid = (user_id instanceof Array) ? user_id[0] : user_id;
1751 var act_id = (action_id instanceof Array) ? action_id[0] : action_id;
1752 return _.str.sprintf('(%s)(%s)%s', uid, act_id, filter.name);
1755 * Generates a :js:class:`~instance.web.search.Facet` descriptor from a
1758 * @param {Object} filter
1759 * @param {String} filter.name
1760 * @param {Object} [filter.context]
1761 * @param {Array} [filter.domain]
1764 facet_for: function (filter) {
1766 category: _t("Custom Filter"),
1769 get_context: function () { return filter.context; },
1770 get_groupby: function () { return [filter.context]; },
1771 get_domain: function () { return filter.domain; }
1774 is_custom_filter: true,
1775 values: [{label: filter.name, value: null}]
1778 clear_selection: function () {
1779 this.$('span.badge').removeClass('badge');
1781 append_filter: function (filter) {
1783 var key = this.key_for(filter);
1784 var warning = _t("This filter is global and will be removed for everybody if you continue.");
1787 if (key in this.$filters) {
1788 $filter = this.$filters[key];
1791 this.filters[key] = filter;
1792 $filter = $('<li></li>')
1793 .appendTo(this.$('.oe_searchview_custom_list'))
1794 .toggleClass('oe_searchview_custom_default', filter.is_default)
1795 .append(this.$filters[key] = $('<span>').text(filter.name));
1797 this.$filters[key].addClass(filter.user_id ? 'oe_searchview_custom_private'
1798 : 'oe_searchview_custom_public')
1800 $('<a class="oe_searchview_custom_delete">x</a>')
1801 .click(function (e) {
1802 e.stopPropagation();
1803 if (!(filter.user_id || confirm(warning))) {
1806 self.model.call('unlink', [id]).done(function () {
1808 delete self.$filters[key];
1809 delete self.filters[key];
1810 if (_.isEmpty(self.filters)) {
1818 this.$filters[key].unbind('click').click(function () {
1819 self.toggle_filter(filter);
1823 toggle_filter: function (filter, preventSearch) {
1824 var current = this.view.query.find(function (facet) {
1825 return facet.get('_id') === filter.id;
1828 this.view.query.remove(current);
1829 this.$filters[this.key_for(filter)].removeClass('badge');
1832 this.view.query.reset([this.facet_for(filter)], {
1833 preventSearch: preventSearch || false});
1834 this.$filters[this.key_for(filter)].addClass('badge');
1836 set_filters: function (filters) {
1837 _(filters).map(_.bind(this.append_filter, this));
1838 if (!filters.length) {
1850 instance.web.search.SaveFilter = instance.web.search.Input.extend({
1851 template: 'SearchView.SaveFilter',
1853 init: function (parent, custom_filters) {
1854 this._super(parent);
1855 this.custom_filters = custom_filters;
1857 start: function () {
1859 this.model = new instance.web.Model('ir.filters');
1860 this.$el.on('submit', 'form', this.proxy('save_current'));
1861 this.$el.on('click', 'input[type=checkbox]', function() {
1862 $(this).siblings('input[type=checkbox]').prop('checked', false);
1864 this.$el.on('click', 'h4', function () {
1865 self.$el.toggleClass('oe_opened');
1868 save_current: function () {
1870 var $name = this.$('input:first');
1871 var private_filter = !this.$('#oe_searchview_custom_public').prop('checked');
1872 var set_as_default = this.$('#oe_searchview_custom_default').prop('checked');
1873 if (_.isEmpty($name.val())){
1874 this.do_warn(_t("Error"), _t("Filter name is required."));
1877 var search = this.view.build_search_data();
1878 instance.web.pyeval.eval_domains_and_contexts({
1879 domains: search.domains,
1880 contexts: search.contexts,
1881 group_by_seq: search.groupbys || []
1882 }).done(function (results) {
1883 if (!_.isEmpty(results.group_by)) {
1884 results.context.group_by = results.group_by;
1886 // Don't save user_context keys in the custom filter, otherwise end
1887 // up with e.g. wrong uid or lang stored *and used in subsequent
1889 var ctx = results.context;
1890 _(_.keys(instance.session.user_context)).each(function (key) {
1895 user_id: private_filter ? instance.session.uid : false,
1896 model_id: self.view.model,
1897 context: results.context,
1898 domain: results.domain,
1899 is_default: set_as_default,
1900 action_id: self.custom_filters.get_action_id()
1902 // FIXME: current context?
1903 return self.model.call('create_or_replace', [filter]).done(function (id) {
1905 if (self.custom_filters) {
1906 self.custom_filters.append_filter(filter);
1909 .removeClass('oe_opened')
1910 .find('form')[0].reset();
1917 instance.web.search.Filters = instance.web.search.Input.extend({
1918 template: 'SearchView.Filters',
1920 start: function () {
1922 var is_group = function (i) { return i instanceof instance.web.search.FilterGroup; };
1923 var visible_filters = _(this.drawer.controls).chain().reject(function (group) {
1924 return _(_(group.children).filter(is_group)).isEmpty()
1925 || group.modifiers.invisible;
1928 var groups = visible_filters.map(function (group) {
1929 var filters = _(group.children).filter(is_group);
1931 name: _.str.sprintf("<span class='oe_i'>%s</span> %s",
1932 group.icon, group.name),
1934 length: _(filters).chain().map(function (i) {
1935 return i.filters.length; }).sum().value()
1939 var $dl = $('<dl class="dl-horizontal">').appendTo(this.$el);
1941 var rendered_lines = _.map(groups, function (group) {
1942 $('<dt>').html(group.name).appendTo($dl);
1943 var $dd = $('<dd>').appendTo($dl);
1944 return $.when.apply(null, _(group.filters).invoke('appendTo', $dd));
1947 return $.when.apply(this, rendered_lines);
1951 instance.web.search.Advanced = instance.web.search.Input.extend({
1952 template: 'SearchView.advanced',
1954 start: function () {
1957 .on('keypress keydown keyup', function (e) { e.stopPropagation(); })
1958 .on('click', 'h4', function () {
1959 self.$el.toggleClass('oe_opened');
1960 }).on('click', 'button.oe_add_condition', function () {
1961 self.append_proposition();
1962 }).on('submit', 'form', function (e) {
1964 self.commit_search();
1968 new instance.web.Model(this.view.model).call('fields_get', {
1969 context: this.view.dataset.context
1970 }).done(function(data) {
1972 id: { string: 'ID', type: 'id', searchable: true }
1974 _.each(data, function(field_def, field_name) {
1975 if (field_def.selectable !== false && field_name != 'id') {
1976 self.fields[field_name] = field_def;
1979 })).done(function () {
1980 self.append_proposition();
1983 append_proposition: function () {
1985 return (new instance.web.search.ExtendedSearchProposition(this, this.fields))
1986 .appendTo(this.$('ul')).done(function () {
1987 self.$('button.oe_apply').prop('disabled', false);
1990 remove_proposition: function (prop) {
1991 // removing last proposition, disable apply button
1992 if (this.getChildren().length <= 1) {
1993 this.$('button.oe_apply').prop('disabled', true);
1997 commit_search: function () {
1998 // Get domain sections from all propositions
1999 var children = this.getChildren();
2000 var propositions = _.invoke(children, 'get_proposition');
2001 var domain = _(propositions).pluck('value');
2002 for (var i = domain.length; --i;) {
2003 domain.unshift('|');
2006 this.view.query.add({
2007 category: _t("Advanced"),
2008 values: propositions,
2010 get_context: function () { },
2011 get_domain: function () { return domain;},
2012 get_groupby: function () { }
2016 // remove all propositions
2017 _.invoke(children, 'destroy');
2018 // add new empty proposition
2019 this.append_proposition();
2020 // TODO: API on searchview
2021 this.view.$el.removeClass('oe_searchview_open_drawer');
2025 instance.web.search.ExtendedSearchProposition = instance.web.Widget.extend(/** @lends instance.web.search.ExtendedSearchProposition# */{
2026 template: 'SearchView.extended_search.proposition',
2028 'change .searchview_extended_prop_field': 'changed',
2029 'change .searchview_extended_prop_op': 'operator_changed',
2030 'click .searchview_extended_delete_prop': function (e) {
2031 e.stopPropagation();
2032 this.getParent().remove_proposition(this);
2036 * @constructs instance.web.search.ExtendedSearchProposition
2037 * @extends instance.web.Widget
2042 init: function (parent, fields) {
2043 this._super(parent);
2044 this.fields = _(fields).chain()
2045 .map(function(val, key) { return _.extend({}, val, {'name': key}); })
2046 .filter(function (field) { return !field.deprecated && field.searchable; })
2047 .sortBy(function(field) {return field.string;})
2049 this.attrs = {_: _, fields: this.fields, selected: null};
2052 start: function () {
2053 return this._super().done(this.proxy('changed'));
2055 changed: function() {
2056 var nval = this.$(".searchview_extended_prop_field").val();
2057 if(this.attrs.selected === null || this.attrs.selected === undefined || nval != this.attrs.selected.name) {
2058 this.select_field(_.detect(this.fields, function(x) {return x.name == nval;}));
2061 operator_changed: function (e) {
2062 var $value = this.$('.searchview_extended_prop_value');
2063 switch ($(e.target).val()) {
2073 * Selects the provided field object
2075 * @param field a field descriptor object (as returned by fields_get, augmented by the field name)
2077 select_field: function(field) {
2079 if(this.attrs.selected !== null && this.attrs.selected !== undefined) {
2080 this.value.destroy();
2082 this.$('.searchview_extended_prop_op').html('');
2084 this.attrs.selected = field;
2085 if(field === null || field === undefined) {
2089 var type = field.type;
2090 var Field = instance.web.search.custom_filters.get_object(type);
2092 Field = instance.web.search.custom_filters.get_object("char");
2094 this.value = new Field(this, field);
2095 _.each(this.value.operators, function(operator) {
2096 $('<option>', {value: operator.value})
2097 .text(String(operator.text))
2098 .appendTo(self.$('.searchview_extended_prop_op'));
2100 var $value_loc = this.$('.searchview_extended_prop_value').show().empty();
2101 this.value.appendTo($value_loc);
2104 get_proposition: function() {
2105 if (this.attrs.selected === null || this.attrs.selected === undefined)
2107 var field = this.attrs.selected;
2108 var op_select = this.$('.searchview_extended_prop_op')[0];
2109 var operator = op_select.options[op_select.selectedIndex];
2112 label: this.value.get_label(field, operator),
2113 value: this.value.get_domain(field, operator),
2118 instance.web.search.ExtendedSearchProposition.Field = instance.web.Widget.extend({
2119 init: function (parent, field) {
2120 this._super(parent);
2123 get_label: function (field, operator) {
2125 switch (operator.value) {
2126 case '∃': case '∄': format = _t('%(field)s %(operator)s'); break;
2127 default: format = _t('%(field)s %(operator)s "%(value)s"'); break;
2129 return this.format_label(format, field, operator);
2131 format_label: function (format, field, operator) {
2132 return _.str.sprintf(format, {
2133 field: field.string,
2134 // According to spec, HTMLOptionElement#label should return
2135 // HTMLOptionElement#text when not defined/empty, but it does
2136 // not in older Webkit (between Safari 5.1.5 and Chrome 17) and
2137 // Gecko (pre Firefox 7) browsers, so we need a manual fallback
2139 operator: operator.label || operator.text,
2143 get_domain: function (field, operator) {
2144 switch (operator.value) {
2145 case '∃': return this.make_domain(field.name, '!=', false);
2146 case '∄': return this.make_domain(field.name, '=', false);
2147 default: return this.make_domain(
2148 field.name, operator.value, this.get_value());
2151 make_domain: function (field, operator, value) {
2152 return [field, operator, value];
2155 * Returns a human-readable version of the value, in case the "logical"
2156 * and the "semantic" values of a field differ (as for selection fields,
2159 * The default implementation simply returns the value itself.
2161 * @return {String} human-readable version of the value
2163 toString: function () {
2164 return this.get_value();
2167 instance.web.search.ExtendedSearchProposition.Char = instance.web.search.ExtendedSearchProposition.Field.extend({
2168 template: 'SearchView.extended_search.proposition.char',
2170 {value: "ilike", text: _lt("contains")},
2171 {value: "not ilike", text: _lt("doesn't contain")},
2172 {value: "=", text: _lt("is equal to")},
2173 {value: "!=", text: _lt("is not equal to")},
2174 {value: "∃", text: _lt("is set")},
2175 {value: "∄", text: _lt("is not set")}
2177 get_value: function() {
2178 return this.$el.val();
2181 instance.web.search.ExtendedSearchProposition.DateTime = instance.web.search.ExtendedSearchProposition.Field.extend({
2182 template: 'SearchView.extended_search.proposition.empty',
2184 {value: "=", text: _lt("is equal to")},
2185 {value: "!=", text: _lt("is not equal to")},
2186 {value: ">", text: _lt("greater than")},
2187 {value: "<", text: _lt("less than")},
2188 {value: ">=", text: _lt("greater or equal than")},
2189 {value: "<=", text: _lt("less or equal than")},
2190 {value: "∃", text: _lt("is set")},
2191 {value: "∄", text: _lt("is not set")}
2194 * Date widgets live in view_form which is not yet loaded when this is
2197 widget: function () { return instance.web.DateTimeWidget; },
2198 get_value: function() {
2199 return this.datewidget.get_value();
2201 toString: function () {
2202 return instance.web.format_value(this.get_value(), { type:"datetime" });
2205 var ready = this._super();
2206 this.datewidget = new (this.widget())(this);
2207 this.datewidget.appendTo(this.$el);
2211 instance.web.search.ExtendedSearchProposition.Date = instance.web.search.ExtendedSearchProposition.DateTime.extend({
2212 widget: function () { return instance.web.DateWidget; },
2213 toString: function () {
2214 return instance.web.format_value(this.get_value(), { type:"date" });
2217 instance.web.search.ExtendedSearchProposition.Integer = instance.web.search.ExtendedSearchProposition.Field.extend({
2218 template: 'SearchView.extended_search.proposition.integer',
2220 {value: "=", text: _lt("is equal to")},
2221 {value: "!=", text: _lt("is not equal to")},
2222 {value: ">", text: _lt("greater than")},
2223 {value: "<", text: _lt("less than")},
2224 {value: ">=", text: _lt("greater or equal than")},
2225 {value: "<=", text: _lt("less or equal than")},
2226 {value: "∃", text: _lt("is set")},
2227 {value: "∄", text: _lt("is not set")}
2229 toString: function () {
2230 return this.$el.val();
2232 get_value: function() {
2234 var val =this.$el.val();
2235 return instance.web.parse_value(val === "" ? 0 : val, {'widget': 'integer'});
2241 instance.web.search.ExtendedSearchProposition.Id = instance.web.search.ExtendedSearchProposition.Integer.extend({
2242 operators: [{value: "=", text: _lt("is")}]
2244 instance.web.search.ExtendedSearchProposition.Float = instance.web.search.ExtendedSearchProposition.Field.extend({
2245 template: 'SearchView.extended_search.proposition.float',
2247 {value: "=", text: _lt("is equal to")},
2248 {value: "!=", text: _lt("is not equal to")},
2249 {value: ">", text: _lt("greater than")},
2250 {value: "<", text: _lt("less than")},
2251 {value: ">=", text: _lt("greater or equal than")},
2252 {value: "<=", text: _lt("less or equal than")},
2253 {value: "∃", text: _lt("is set")},
2254 {value: "∄", text: _lt("is not set")}
2256 toString: function () {
2257 return this.$el.val();
2259 get_value: function() {
2261 var val =this.$el.val();
2262 return instance.web.parse_value(val === "" ? 0.0 : val, {'widget': 'float'});
2268 instance.web.search.ExtendedSearchProposition.Selection = instance.web.search.ExtendedSearchProposition.Field.extend({
2269 template: 'SearchView.extended_search.proposition.selection',
2271 {value: "=", text: _lt("is")},
2272 {value: "!=", text: _lt("is not")},
2273 {value: "∃", text: _lt("is set")},
2274 {value: "∄", text: _lt("is not set")}
2276 toString: function () {
2277 var select = this.$el[0];
2278 var option = select.options[select.selectedIndex];
2279 return option.label || option.text;
2281 get_value: function() {
2282 return this.$el.val();
2285 instance.web.search.ExtendedSearchProposition.Boolean = instance.web.search.ExtendedSearchProposition.Field.extend({
2286 template: 'SearchView.extended_search.proposition.empty',
2288 {value: "=", text: _lt("is true")},
2289 {value: "!=", text: _lt("is false")}
2291 get_label: function (field, operator) {
2292 return this.format_label(
2293 _t('%(field)s %(operator)s'), field, operator);
2295 get_value: function() {
2300 instance.web.search.custom_filters = new instance.web.Registry({
2301 'char': 'instance.web.search.ExtendedSearchProposition.Char',
2302 'text': 'instance.web.search.ExtendedSearchProposition.Char',
2303 'one2many': 'instance.web.search.ExtendedSearchProposition.Char',
2304 'many2one': 'instance.web.search.ExtendedSearchProposition.Char',
2305 'many2many': 'instance.web.search.ExtendedSearchProposition.Char',
2307 'datetime': 'instance.web.search.ExtendedSearchProposition.DateTime',
2308 'date': 'instance.web.search.ExtendedSearchProposition.Date',
2309 'integer': 'instance.web.search.ExtendedSearchProposition.Integer',
2310 'float': 'instance.web.search.ExtendedSearchProposition.Float',
2311 'boolean': 'instance.web.search.ExtendedSearchProposition.Boolean',
2312 'selection': 'instance.web.search.ExtendedSearchProposition.Selection',
2314 'id': 'instance.web.search.ExtendedSearchProposition.Id'
2317 instance.web.search.AutoComplete = instance.web.Widget.extend({
2318 template: "SearchView.autocomplete",
2320 // Parameters for autocomplete constructor:
2322 // parent: this is used to detect keyboard events
2324 // options.source: function ({term:query}, callback). This function will be called to
2325 // obtain the search results corresponding to the query string. It is assumed that
2326 // options.source will call callback with the results.
2327 // options.delay: delay in millisecond before calling source. Useful if you don't want
2328 // to make too many rpc calls
2329 // options.select: function (ev, {item: {facet:facet}}). Autocomplete widget will call
2330 // that function when a selection is made by the user
2331 // options.get_search_string: function (). This function will be called by autocomplete
2332 // to obtain the current search string.
2333 init: function (parent, options) {
2334 this._super(parent);
2335 this.$input = parent.$el;
2336 this.source = options.source;
2337 this.delay = options.delay;
2338 this.select = options.select,
2339 this.get_search_string = options.get_search_string;
2340 this.width = options.width || 400;
2342 this.current_result = null;
2344 this.searching = true;
2345 this.search_string = null;
2346 this.current_search = null;
2348 start: function () {
2350 this.$el.width(this.width);
2351 this.$input.on('keyup', function (ev) {
2352 if (ev.which === $.ui.keyCode.RIGHT) {
2353 self.searching = true;
2354 ev.preventDefault();
2357 if (!self.searching) {
2358 self.searching = true;
2361 self.search_string = self.get_search_string();
2362 if (self.search_string.length) {
2363 var search_string = self.search_string;
2364 setTimeout(function () { self.initiate_search(search_string);}, self.delay);
2369 this.$input.on('keydown', function (ev) {
2371 case $.ui.keyCode.TAB:
2372 case $.ui.keyCode.ENTER:
2373 if (self.current_result && self.get_search_string().length) {
2374 self.select_item(ev);
2377 case $.ui.keyCode.DOWN:
2379 self.searching = false;
2380 ev.preventDefault();
2382 case $.ui.keyCode.UP:
2384 self.searching = false;
2385 ev.preventDefault();
2387 case $.ui.keyCode.RIGHT:
2388 self.searching = false;
2389 var current = self.current_result
2390 if (current && current.expand && !current.expanded) {
2392 self.searching = true;
2394 ev.preventDefault();
2396 case $.ui.keyCode.ESCAPE:
2398 self.searching = false;
2403 initiate_search: function (query) {
2404 if (query === this.search_string && query !== this.current_search) {
2408 search: function (query) {
2410 this.current_search = query;
2411 this.source({term:query}, function (results) {
2412 if (results.length) {
2413 self.render_search_results(results);
2414 self.focus_element(self.$('li:first-child'));
2420 render_search_results: function (results) {
2422 var $list = this.$('ul');
2424 var render_separator = false;
2425 results.forEach(function (result) {
2426 if (result.is_separator) {
2427 if (render_separator)
2428 $list.append($('<li>').addClass('oe-separator'));
2429 render_separator = false;
2431 var $item = self.make_list_item(result).appendTo($list);
2433 render_separator = true;
2438 make_list_item: function (result) {
2441 .hover(function (ev) {self.focus_element($li);})
2442 .mousedown(function (ev) {
2443 if (ev.button === 0) { // left button
2444 self.select(ev, {item: {facet: result.facet}});
2447 ev.preventDefault();
2450 .data('result', result);
2451 if (result.expand) {
2452 var $expand = $('<span class="oe-expand">').text('▶').appendTo($li);
2453 $expand.mousedown(function (ev) {
2454 ev.preventDefault();
2455 ev.stopPropagation();
2456 if (result.expanded)
2461 result.expanded = false;
2463 if (result.indent) $li.addClass('oe-indent');
2464 $li.append($('<span>').html(result.label));
2467 expand: function () {
2469 this.current_result.expand(this.get_search_string()).then(function (results) {
2470 (results || [{label: '(no result)'}]).reverse().forEach(function (result) {
2471 result.indent = true;
2472 var $li = self.make_list_item(result);
2473 self.current_result.$el.after($li);
2475 self.current_result.expanded = true;
2476 self.current_result.$el.find('span.oe-expand').html('▼');
2480 var $next = this.current_result.$el.next();
2481 while ($next.hasClass('oe-indent')) {
2483 $next = this.current_result.$el.next();
2485 this.current_result.expanded = false;
2486 this.current_result.$el.find('span.oe-expand').html('▶');
2488 focus_element: function ($li) {
2489 this.$('li').removeClass('oe-selection-focus');
2490 $li.addClass('oe-selection-focus');
2491 this.current_result = $li.data('result');
2493 select_item: function (ev) {
2494 if (this.current_result.facet) {
2495 this.select(ev, {item: {facet: this.current_result.facet}});
2502 close: function () {
2503 this.current_search = null;
2504 this.search_string = null;
2505 this.searching = true;
2508 move: function (direction) {
2510 if (direction === 'down') {
2511 $next = this.$('li.oe-selection-focus').nextAll(':not(.oe-separator)').first();
2512 if (!$next.length) $next = this.$('li:first-child');
2514 $next = this.$('li.oe-selection-focus').prevAll(':not(.oe-separator)').first();
2515 if (!$next.length) $next = this.$('li:not(.oe-separator)').last();
2517 this.focus_element($next);
2519 is_expandable: function () {
2520 return !!this.$('.oe-selection-focus .oe-expand').length;
2526 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: