openerp.web.search = function(instance) { var QWeb = instance.web.qweb, _t = instance.web._t, _lt = instance.web._lt; _.mixin({ sum: function (obj) { return _.reduce(obj, function (a, b) { return a + b; }, 0); } }); /** @namespace */ var my = instance.web.search = {}; var B = Backbone; my.FacetValue = B.Model.extend({ }); my.FacetValues = B.Collection.extend({ model: my.FacetValue }); my.Facet = B.Model.extend({ initialize: function (attrs) { var values = attrs.values; delete attrs.values; B.Model.prototype.initialize.apply(this, arguments); this.values = new my.FacetValues(values || []); this.values.on('add remove change reset', function () { this.trigger('change', this); }, this); }, get: function (key) { if (key !== 'values') { return B.Model.prototype.get.call(this, key); } return this.values.toJSON(); }, set: function (key, value) { if (key !== 'values') { return B.Model.prototype.set.call(this, key, value); } this.values.reset(value); }, toJSON: function () { var out = {}; var attrs = this.attributes; for(var att in attrs) { if (!attrs.hasOwnProperty(att) || att === 'field') { continue; } out[att] = attrs[att]; } out.values = this.values.toJSON(); return out; } }); my.SearchQuery = B.Collection.extend({ model: my.Facet, initialize: function () { B.Collection.prototype.initialize.apply( this, arguments); this.on('change', function (facet) { if(!facet.values.isEmpty()) { return; } this.remove(facet, {silent: true}); }, this); }, add: function (values, options) { options || (options = {}); if (!(values instanceof Array)) { values = [values]; } _(values).each(function (value) { var model = this._prepareModel(value, options); var previous = this.detect(function (facet) { return facet.get('category') === model.get('category') && facet.get('field') === model.get('field'); }); if (previous) { previous.values.add(model.get('values')); return; } B.Collection.prototype.add.call(this, model, options); }, this); return this; }, toggle: function (value, options) { options || (options = {}); var facet = this.detect(function (facet) { return facet.get('category') === value.category && facet.get('field') === value.field; }); if (!facet) { return this.add(value, options); } var changed = false; _(value.values).each(function (val) { var already_value = facet.values.detect(function (v) { return v.get('value') === val.value && v.get('label') === val.label; }); // toggle value if (already_value) { facet.values.remove(already_value, {silent: true}); } else { facet.values.add(val, {silent: true}); } changed = true; }); // "Commit" changes to values array as a single call, so observers of // change event don't get misled by intermediate incomplete toggling // states facet.trigger('change', facet); return this; } }); function assert(condition, message) { if(!condition) { throw new Error(message); } } my.InputView = instance.web.Widget.extend({ template: 'SearchView.InputView', start: function () { var p = this._super.apply(this, arguments); this.$el.on('focus', this.proxy('onFocus')); this.$el.on('blur', this.proxy('onBlur')); this.$el.on('keydown', this.proxy('onKeydown')); return p; }, onFocus: function () { this.trigger('focused', this); }, onBlur: function () { this.$el.text(''); this.trigger('blurred', this); }, getSelection: function () { // get Text node var root = this.$el[0].childNodes[0]; if (!root || !root.textContent) { // if input does not have a child node, or the child node is an // empty string, then the selection can only be (0, 0) return {start: 0, end: 0}; } if (window.getSelection) { var domRange = window.getSelection().getRangeAt(0); assert(domRange.startContainer === root, "selection should be in the input view"); assert(domRange.endContainer === root, "selection should be in the input view"); return { start: domRange.startOffset, end: domRange.endOffset } } else if (document.selection) { var ieRange = document.selection.createRange(); var rangeParent = ieRange.parentElement(); assert(rangeParent === root, "selection should be in the input view"); var offsetRange = document.body.createTextRange(); offsetRange = offsetRange.moveToElementText(rangeParent); offsetRange.setEndPoint("EndToStart", ieRange); var start = offsetRange.text.length; return { start: start, end: start + ieRange.text.length } } throw new Error("Could not get caret position"); }, onKeydown: function (e) { var sel; switch (e.which) { // Do not insert newline, but let it bubble so searchview can use it case $.ui.keyCode.ENTER: e.preventDefault(); break; // FIXME: may forget content if non-empty but caret at index 0, ok? case $.ui.keyCode.BACKSPACE: sel = this.getSelection(); if (sel.start === 0 && sel.start === sel.end) { e.preventDefault(); var preceding = this.getParent().siblingSubview(this, -1); if (preceding && (preceding instanceof my.FacetView)) { preceding.model.destroy(); } } break; // let left/right events propagate to view if caret is at input border // and not a selection case $.ui.keyCode.LEFT: sel = this.getSelection(); if (sel.start !== 0 || sel.start !== sel.end) { e.stopPropagation(); } break; case $.ui.keyCode.RIGHT: sel = this.getSelection(); var len = this.$el.text().length; if (sel.start !== len || sel.start !== sel.end) { e.stopPropagation(); } break; } } }); my.FacetView = instance.web.Widget.extend({ template: 'SearchView.FacetView', init: function (parent, model) { this._super(parent); this.model = model; this.model.on('change', this.model_changed, this); }, destroy: function () { this.model.off('change', this.model_changed, this); this._super(); }, start: function () { var self = this; this.$el.on('focus', function () { self.trigger('focused', self); }); this.$el.on('blur', function () { self.trigger('blurred', self); }); this.$el.on('click', function (e) { if ($(e.target).is('.oe_facet_remove')) { self.model.destroy(); return false; } self.$el.focus(); e.stopPropagation(); }); this.$el.on('keydown', function (e) { var keys = $.ui.keyCode; switch (e.which) { case keys.BACKSPACE: case keys.DELETE: self.model.destroy(); return false; } }); var $e = self.$el.find('> span:last-child'); var q = $.when(this._super()); return q.then(function () { var values = self.model.values.map(function (value) { return new my.FacetValueView(self, value).appendTo($e); }); return $.when.apply(null, values); }); }, model_changed: function () { this.$el.text(this.$el.text() + '*'); } }); my.FacetValueView = instance.web.Widget.extend({ template: 'SearchView.FacetView.Value', init: function (parent, model) { this._super(parent); this.model = model; this.model.on('change', this.model_changed, this); }, destroy: function () { this.model.off('change', this.model_changed, this); this._super(); }, model_changed: function () { this.$el.text(this.$el.text() + '*'); } }); instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.SearchView# */{ template: "SearchView", /** * @constructs instance.web.SearchView * @extends instance.web.Widget * * @param parent * @param dataset * @param view_id * @param defaults * @param hidden */ init: function(parent, dataset, view_id, defaults, hidden) { this._super(parent); this.dataset = dataset; this.model = dataset.model; this.view_id = view_id; this.defaults = defaults || {}; this.has_defaults = !_.isEmpty(this.defaults); this.inputs = []; this.controls = {}; this.hidden = !!hidden; this.headless = this.hidden && !this.has_defaults; this.input_subviews = []; this.ready = $.Deferred(); }, start: function() { var self = this; var p = this._super(); this.setup_global_completion(); this.query = new my.SearchQuery() .on('add change reset remove', this.proxy('do_search')) .on('add change reset remove', this.proxy('renderFacets')); if (this.hidden) { this.$el.hide(); } if (this.headless) { this.ready.resolve(); } else { var load_view = this.rpc("/web/searchview/load", { model: this.model, view_id: this.view_id, context: this.dataset.get_context() }); $.when(load_view) .then(function(r) { self.search_view_loaded(r) }).fail(function () { self.ready.reject.apply(null, arguments); }); } // Launch a search on clicking the oe_searchview_search button this.$el.on('click', 'button.oe_searchview_search', function (e) { e.stopImmediatePropagation(); self.do_search(); }); this.$el.on('keydown', '.oe_searchview_input, .oe_searchview_facet', function (e) { switch(e.which) { case $.ui.keyCode.LEFT: self.focusPreceding(this); e.preventDefault(); break; case $.ui.keyCode.RIGHT: self.focusFollowing(this); e.preventDefault(); break; } }); this.$el.on('click', '.oe_searchview_clear', function (e) { e.stopImmediatePropagation(); self.query.reset(); }); this.$el.on('click', '.oe_searchview_unfold_drawer', function (e) { e.stopImmediatePropagation(); self.$el.toggleClass('oe_searchview_open_drawer'); }); instance.web.bus.on('click', this, function(ev) { if ($(ev.target).parents('.oe_searchview').length === 0) { self.$el.removeClass('oe_searchview_open_drawer'); } }); // Focus last input if the view itself is clicked (empty section of // facets element) this.$el.on('click', function (e) { if (e.target === self.$el.find('.oe_searchview_facets')[0]) { self.$el.find('.oe_searchview_input:last').focus(); } }); return $.when(p, this.ready); }, show: function () { this.$el.show(); }, hide: function () { this.$el.hide(); }, subviewForRoot: function (subview_root) { return _(this.input_subviews).detect(function (subview) { return subview.$el[0] === subview_root; }); }, siblingSubview: function (subview, direction, wrap_around) { var index = _(this.input_subviews).indexOf(subview) + direction; if (wrap_around && index < 0) { index = this.input_subviews.length - 1; } else if (wrap_around && index >= this.input_subviews.length) { index = 0; } return this.input_subviews[index]; }, focusPreceding: function (subview_root) { return this.siblingSubview( this.subviewForRoot(subview_root), -1, true) .$el.focus(); }, focusFollowing: function (subview_root) { return this.siblingSubview( this.subviewForRoot(subview_root), +1, true) .$el.focus(); }, /** * Sets up thingie where all the mess is put? */ select_for_drawer: function () { return _(this.inputs).filter(function (input) { return input.in_drawer(); }); }, /** * Sets up search view's view-wide auto-completion widget */ setup_global_completion: function () { var self = this; var autocomplete = this.$el.autocomplete({ source: this.proxy('complete_global_search'), select: this.proxy('select_completion'), focus: function (e) { e.preventDefault(); }, html: true, autoFocus: true, minLength: 1, delay: 0 }).data('autocomplete'); // MonkeyPatch autocomplete instance _.extend(autocomplete, { _renderItem: function (ul, item) { // item of completion list var $item = $( "
" ) .data( "item.autocomplete", item ) .appendTo( ul ); if (item.facet !== undefined) { // regular completion item return $item.append( (item.label) ? $('').html(item.label) : $('').text(item.value)); } return $item.text(item.label) .css({ borderTop: '1px solid #cccccc', margin: 0, padding: 0, zoom: 1, 'float': 'left', clear: 'left', width: '100%' }); }, _value: function() { return self.$el.find('div.oe_searchview_input').text(); }, }); }, /** * Provide auto-completion result for req.term (an array to `resp`) * * @param {Object} req request to complete * @param {String} req.term searched term to complete * @param {Function} resp response callback */ complete_global_search: function (req, resp) { $.when.apply(null, _(this.inputs).chain() .invoke('complete', req.term) .value()).done(function () { resp(_(_(arguments).compact()).flatten(true)); }); }, /** * Action to perform in case of selection: create a facet (model) * and add it to the search collection * * @param {Object} e selection event, preventDefault to avoid setting value on object * @param {Object} ui selection information * @param {Object} ui.item selected completion item */ select_completion: function (e, ui) { e.preventDefault(); var input_index = _(this.input_subviews).indexOf( this.subviewForRoot( this.$el.find('div.oe_searchview_input:focus')[0])); this.query.add(ui.item.facet, {at: input_index / 2}); }, childFocused: function () { this.$el.addClass('oe_focused'); }, childBlurred: function () { var val = this.$el.val(); this.$el.val(''); var complete = this.$el.data('autocomplete'); if ((val && complete.term === undefined) || complete.previous !== undefined) { throw new Error("new jquery.ui version altering implementation" + " details relied on"); } delete complete.term; this.$el.removeClass('oe_focused') .trigger('blur'); }, /** * * @param {openerp.web.search.SearchQuery | openerp.web.search.Facet} _1 * @param {openerp.web.search.Facet} [_2] * @param {Object} [options] */ renderFacets: function (_1, _2, options) { // _1: model if event=change, otherwise collection // _2: undefined if event=change, otherwise model var self = this; var started = []; var $e = this.$el.find('div.oe_searchview_facets'); _.invoke(this.input_subviews, 'destroy'); this.input_subviews = []; var i = new my.InputView(this); started.push(i.appendTo($e)); this.input_subviews.push(i); this.query.each(function (facet) { var f = new my.FacetView(this, facet); started.push(f.appendTo($e)); self.input_subviews.push(f); var i = new my.InputView(this); started.push(i.appendTo($e)); self.input_subviews.push(i); }, this); _.each(this.input_subviews, function (childView) { childView.on('focused', self, self.proxy('childFocused')); childView.on('blurred', self, self.proxy('childBlurred')); }); $.when.apply(null, started).done(function () { var input_to_focus; // options.at: facet inserted at given index, focus next input // otherwise just focus last input if (!options || typeof options.at !== 'number') { input_to_focus = _.last(self.input_subviews); } else { input_to_focus = self.input_subviews[(options.at + 1) * 2]; } input_to_focus.$el.focus(); }); }, /** * Builds a list of widget rows (each row is an array of widgets) * * @param {Array} items a list of nodes to convert to widgets * @param {Object} fields a mapping of field names to (ORM) field attributes * @param {String} [group_name] name of the group to put the new controls in */ make_widgets: function (items, fields, group_name) { group_name = group_name || null; if (!(group_name in this.controls)) { this.controls[group_name] = []; } var self = this, group = this.controls[group_name]; var filters = []; _.each(items, function (item) { if (filters.length && item.tag !== 'filter') { group.push(new instance.web.search.FilterGroup(filters, this)); filters = []; } switch (item.tag) { case 'separator': case 'newline': break; case 'filter': filters.push(new instance.web.search.Filter(item, this)); break; case 'group': self.make_widgets(item.children, fields, item.attrs.string); break; case 'field': group.push(this.make_field(item, fields[item['attrs'].name])); // filters self.make_widgets(item.children, fields, group_name); break; } }, this); if (filters.length) { group.push(new instance.web.search.FilterGroup(filters, this)); } }, /** * Creates a field for the provided field descriptor item (which comes * from fields_view_get) * * @param {Object} item fields_view_get node for the field * @param {Object} field fields_get result for the field * @returns instance.web.search.Field */ make_field: function (item, field) { var obj = instance.web.search.fields.get_any( [item.attrs.widget, field.type]); if(obj) { return new (obj) (item, field, this); } else { console.group('Unknown field type ' + field.type); console.error('View node', item); console.info('View field', field); console.info('In view', this); console.groupEnd(); return null; } }, add_common_inputs: function() { // add Filters to this.inputs, need view.controls filled (new instance.web.search.Filters(this)); // add custom filters to this.inputs (new instance.web.search.CustomFilters(this)); // add Advanced to this.inputs (new instance.web.search.Advanced(this)); }, search_view_loaded: function(data) { var self = this; this.fields_view = data.fields_view; if (data.fields_view.type !== 'search' || data.fields_view.arch.tag !== 'search') { throw new Error(_.str.sprintf( "Got non-search view after asking for a search view: type %s, arch root %s", data.fields_view.type, data.fields_view.arch.tag)); } this.make_widgets( data.fields_view['arch'].children, data.fields_view.fields); this.add_common_inputs(); // build drawer var drawer_started = $.when.apply( null, _(this.select_for_drawer()).invoke( 'appendTo', this.$el.find('.oe_searchview_drawer'))); // load defaults var defaults_fetched = $.when.apply(null, _(this.inputs).invoke( 'facet_for_defaults', this.defaults)).done(function () { self.query.reset(_(arguments).compact(), {preventSearch: true}); }); return $.when(drawer_started, defaults_fetched) .done(function () { self.trigger("search_view_loaded", data); self.ready.resolve(); }); }, /** * Extract search data from the view's facets. * * Result is an object with 4 (own) properties: * * errors * An array of any error generated during data validation and * extraction, contains the validation error objects * domains * Array of domains * contexts * Array of contexts * groupbys * Array of domains, in groupby order rather than view order * * @return {Object} */ build_search_data: function () { var domains = [], contexts = [], groupbys = [], errors = []; this.query.each(function (facet) { var field = facet.get('field'); try { var domain = field.get_domain(facet); if (domain) { domains.push(domain); } var context = field.get_context(facet); if (context) { contexts.push(context); } var group_by = field.get_groupby(facet); if (group_by) { groupbys.push.apply(groupbys, group_by); } } catch (e) { if (e instanceof instance.web.search.Invalid) { errors.push(e); } else { throw e; } } }); return { domains: domains, contexts: contexts, groupbys: groupbys, errors: errors }; }, /** * Performs the search view collection of widget data. * * If the collection went well (all fields are valid), then triggers * :js:func:`instance.web.SearchView.on_search`. * * If at least one field failed its validation, triggers * :js:func:`instance.web.SearchView.on_invalid` instead. */ do_search: function (_query, options) { if (options && options.preventSearch) { return; } var search = this.build_search_data(); if (!_.isEmpty(search.errors)) { this.on_invalid(search.errors); return; } this.trigger('search_data', search.domains, search.contexts, search.groupbys); }, /** * Triggered after the SearchView has collected all relevant domains and * contexts. * * It is provided with an Array of domains and an Array of contexts, which * may or may not be evaluated (each item can be either a valid domain or * context, or a string to evaluate in order in the sequence) * * It is also passed an array of contexts used for group_by (they are in * the correct order for group_by evaluation, which contexts may not be) * * @event * @param {Array} domains an array of literal domains or domain references * @param {Array} contexts an array of literal contexts or context refs * @param {Array} groupbys ordered contexts which may or may not have group_by keys */ /** * Triggered after a validation error in the SearchView fields. * * Error objects have three keys: * * ``field`` is the name of the invalid field * * ``value`` is the invalid value * * ``message`` is the (in)validation message provided by the field * * @event * @param {Array} errors a never-empty array of error objects */ on_invalid: function (errors) { this.do_notify(_t("Invalid Search"), _t("triggered from search view")); this.trigger('invalid_search', errors); } }); /** * Registry of search fields, called by :js:class:`instance.web.SearchView` to * find and instantiate its field widgets. */ instance.web.search.fields = new instance.web.Registry({ 'char': 'instance.web.search.CharField', 'text': 'instance.web.search.CharField', 'html': 'instance.web.search.CharField', 'boolean': 'instance.web.search.BooleanField', 'integer': 'instance.web.search.IntegerField', 'id': 'instance.web.search.IntegerField', 'float': 'instance.web.search.FloatField', 'selection': 'instance.web.search.SelectionField', 'datetime': 'instance.web.search.DateTimeField', 'date': 'instance.web.search.DateField', 'many2one': 'instance.web.search.ManyToOneField', 'many2many': 'instance.web.search.CharField', 'one2many': 'instance.web.search.CharField' }); instance.web.search.Invalid = instance.web.Class.extend( /** @lends instance.web.search.Invalid# */{ /** * Exception thrown by search widgets when they hold invalid values, * which they can not return when asked. * * @constructs instance.web.search.Invalid * @extends instance.web.Class * * @param field the name of the field holding an invalid value * @param value the invalid value * @param message validation failure message */ init: function (field, value, message) { this.field = field; this.value = value; this.message = message; }, toString: function () { return _.str.sprintf( _t("Incorrect value for field %(fieldname)s: [%(value)s] is %(message)s"), {fieldname: this.field, value: this.value, message: this.message} ); } }); instance.web.search.Widget = instance.web.Widget.extend( /** @lends instance.web.search.Widget# */{ template: null, /** * Root class of all search widgets * * @constructs instance.web.search.Widget * @extends instance.web.Widget * * @param view the ancestor view of this widget */ init: function (view) { this._super(view); this.view = view; } }); instance.web.search.add_expand_listener = function($root) { $root.find('a.searchview_group_string').click(function (e) { $root.toggleClass('folded expanded'); e.stopPropagation(); e.preventDefault(); }); }; instance.web.search.Group = instance.web.search.Widget.extend({ template: 'SearchView.group', init: function (view_section, view, fields) { this._super(view); this.attrs = view_section.attrs; this.lines = view.make_widgets( view_section.children, fields); } }); instance.web.search.Input = instance.web.search.Widget.extend( /** @lends instance.web.search.Input# */{ _in_drawer: false, /** * @constructs instance.web.search.Input * @extends instance.web.search.Widget * * @param view */ init: function (view) { this._super(view); this.view.inputs.push(this); this.style = undefined; }, /** * Fetch auto-completion values for the widget. * * The completion values should be an array of objects with keys category, * label, value prefixed with an object with keys type=section and label * * @param {String} value value to complete * @returns {jQuery.Deferred