1 openerp.web.list = function (openerp) {
2 var _t = openerp.web._t;
3 var QWeb = openerp.web.qweb;
4 openerp.web.views.add('list', 'openerp.web.ListView');
5 openerp.web.ListView = openerp.web.View.extend( /** @lends openerp.web.ListView# */ {
7 // records can be selected one by one
9 // list rows can be deleted
11 // whether the column headers should be displayed
13 // display addition button, with that label
14 'addable': _t("Create"),
15 // whether the list view can be sorted, note that once a view has been
16 // sorted it can not be reordered anymore
18 // whether the view rows can be reordered (via vertical drag & drop)
22 * Core class for list-type displays.
24 * As a view, needs a number of view-related parameters to be correctly
25 * instantiated, provides options and overridable methods for behavioral
28 * See constructor parameters and method documentations for information on
29 * the default behaviors and possible options for the list view.
31 * @constructs openerp.web.ListView
32 * @extends openerp.web.View
34 * @param parent parent object
35 * @param {openerp.web.DataSet} dataset the dataset the view should work with
36 * @param {String} view_id the listview's identifier, if any
37 * @param {Object} options A set of options used to configure the view
38 * @param {Boolean} [options.selectable=true] determines whether view rows are selectable (e.g. via a checkbox)
39 * @param {Boolean} [options.header=true] should the list's header be displayed
40 * @param {Boolean} [options.deletable=true] are the list rows deletable
41 * @param {void|String} [options.addable="New"] should the new-record button be displayed, and what should its label be. Use ``null`` to hide the button.
42 * @param {Boolean} [options.sortable=true] is it possible to sort the table by clicking on column headers
43 * @param {Boolean} [options.reorderable=true] is it possible to reorder list rows
45 init: function(parent, dataset, view_id, options) {
48 this.set_default_options(_.extend({}, this.defaults, options || {}));
49 this.dataset = dataset;
50 this.model = dataset.model;
51 this.view_id = view_id;
52 this.previous_colspan = null;
57 this.records = new Collection();
59 this.set_groups(new openerp.web.ListView.Groups(this));
61 if (this.dataset instanceof openerp.web.DataSetStatic) {
62 this.groups.datagroup = new openerp.web.StaticDataGroup(this.dataset);
64 this.groups.datagroup = new openerp.web.DataGroup(
67 dataset.get_context(),
69 this.groups.datagroup.sort = this.dataset._sort;
73 this.records.bind('change', function (event, record, key) {
74 if (!_(self.aggregate_columns).chain()
75 .pluck('name').contains(key).value()) {
78 self.compute_aggregates();
83 * Retrieves the view's number of records per page (|| section)
85 * options > defaults > parent.action.limit > indefinite
87 * @returns {Number|null}
90 if (this._limit === undefined) {
91 this._limit = (this.options.limit
92 || this.defaults.limit
93 || (this.widget_parent.action || {}).limit
99 * Set a custom Group construct as the root of the List View.
101 * @param {openerp.web.ListView.Groups} groups
103 set_groups: function (groups) {
106 $(this.groups).unbind("selected deleted action row_link");
110 this.groups = groups;
111 $(this.groups).bind({
112 'selected': function (e, ids, records) {
113 self.do_select(ids, records);
115 'deleted': function (e, ids) {
118 'action': function (e, action_name, id, callback) {
119 self.do_button_action(action_name, id, callback);
121 'row_link': function (e, id, dataset) {
122 self.do_activate_record(dataset.index, id, dataset);
127 * View startup method, the default behavior is to set the ``oe-listview``
128 * class on its root element and to perform an RPC load call.
130 * @returns {$.Deferred} loading promise
134 this.$element.addClass('oe-listview');
135 return this.reload_view(null, null, true);
138 * Returns the color for the provided record in the current view (from the
139 * ``@colors`` attribute)
141 * @param {Record} record record for the current row
142 * @returns {String} CSS color declaration
144 color_for: function (record) {
145 if (!this.colors) { return ''; }
146 var context = _.extend({}, record.attributes, {
147 uid: this.session.uid,
148 current_date: new Date().toString('yyyy-MM-dd')
149 // TODO: time, datetime, relativedelta
151 for(var i=0, len=this.colors.length; i<len; ++i) {
152 var pair = this.colors[i],
154 expression = pair[1];
155 if (py.evaluate(expression, context)) {
156 return 'color: ' + color + ';';
158 // TODO: handle evaluation errors
163 * Called after loading the list view's description, sets up such things
164 * as the view table's columns, renders the table itself and hooks up the
165 * various table-level and row-level DOM events (action buttons, deletion
166 * buttons, selection of records, [New] button, selection of a given
169 * Sets up the following:
171 * * Processes arch and fields to generate a complete field descriptor for each field
172 * * Create the table itself and allocate visible columns
173 * * Hook in the top-level (header) [New|Add] and [Delete] button
174 * * Sets up showing/hiding the top-level [Delete] button based on records being selected or not
175 * * Sets up event handlers for action buttons and per-row deletion button
176 * * Hooks global callback for clicking on a row
177 * * Sets up its sidebar, if any
179 * @param {Object} data wrapped fields_view_get result
180 * @param {Object} data.fields_view fields_view_get result (processed)
181 * @param {Object} data.fields_view.fields mapping of fields for the current model
182 * @param {Object} data.fields_view.arch current list view descriptor
183 * @param {Boolean} grouped Is the list view grouped
185 on_loaded: function(data, grouped) {
187 this.fields_view = data;
188 this.name = "" + this.fields_view.arch.attrs.string;
190 if (this.fields_view.arch.attrs.colors) {
191 this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
193 .map(function(color_pair) {
194 var pair = color_pair.split(':'),
197 return [color, py.parse(py.tokenize(expr)), expr];
201 this.setup_columns(this.fields_view.fields, grouped);
203 this.$element.html(QWeb.render("ListView", this));
205 this.$element.find('.all-record-selector').click(function(){
206 self.$element.find('.oe-record-selector input').prop('checked',
207 self.$element.find('.all-record-selector').prop('checked') || false);
208 var selection = self.groups.get_selection();
209 $(self.groups).trigger(
210 'selected', [selection.ids, selection.records]);
213 this.$element.find('.oe-list-add')
214 .click(this.do_add_record)
215 .attr('disabled', grouped && this.options.editable);
216 this.$element.find('.oe-list-delete')
217 .attr('disabled', true)
218 .click(this.do_delete_selected);
219 this.$element.find('thead').delegate('th.oe-sortable[data-id]', 'click', function (e) {
223 self.dataset.sort($this.data('id'));
224 if ($this.find('span').length) {
225 $this.find('span').toggleClass(
226 'ui-icon-triangle-1-s ui-icon-triangle-1-n');
228 $this.append('<span class="ui-icon ui-icon-triangle-1-s">')
229 .siblings('.oe-sortable').find('span').remove();
232 self.reload_content();
235 this.$element.find('.oe-list-pager')
236 .delegate('button', 'click', function () {
238 switch ($this.data('pager-action')) {
240 self.page = 0; break;
242 self.page = Math.floor(
243 self.dataset.ids.length / self.limit());
246 self.page += 1; break;
248 self.page -= 1; break;
250 self.reload_content();
251 }).find('.oe-pager-state')
252 .click(function (e) {
256 var $select = $('<select>')
257 .appendTo($this.empty())
258 .click(function (e) {e.stopPropagation();})
259 .append('<option value="80">80</option>' +
260 '<option value="100">100</option>' +
261 '<option value="200">200</option>' +
262 '<option value="500">500</option>' +
263 '<option value="NaN">' + _t("Unlimited") + '</option>')
264 .change(function () {
265 var val = parseInt($select.val(), 10);
266 self._limit = (isNaN(val) ? null : val);
268 self.reload_content();
270 .val(self._limit || 'NaN');
272 if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
273 this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
274 this.sidebar.start();
275 this.sidebar.add_toolbar(this.fields_view.toolbar);
276 this.set_common_sidebar_sections(this.sidebar);
280 * Configures the ListView pager based on the provided dataset's information
282 * Horrifying side-effect: sets the dataset's data on this.dataset?
284 * @param {openerp.web.DataSet} dataset
286 configure_pager: function (dataset) {
287 this.dataset.ids = dataset.ids;
289 var limit = this.limit(),
290 total = dataset.ids.length,
291 first = (this.page * limit),
293 if (!limit || (total - first) < limit) {
296 last = first + limit;
298 this.$element.find('span.oe-pager-state').empty().text(_.sprintf(
299 "[%d to %d] of %d", first + 1, last, total));
302 .find('button[data-pager-action=first], button[data-pager-action=previous]')
303 .attr('disabled', this.page === 0)
305 .find('button[data-pager-action=last], button[data-pager-action=next]')
306 .attr('disabled', last === total);
309 * Sets up the listview's columns: merges view and fields data, move
310 * grouped-by columns to the front of the columns list and make them all
313 * @param {Object} fields fields_view_get's fields section
314 * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
316 setup_columns: function (fields, grouped) {
317 var domain_computer = openerp.web.form.compute_domain;
319 var noop = function () { return {}; };
320 var field_to_column = function (field) {
321 var name = field.attrs.name;
322 var column = _.extend({id: name, tag: field.tag},
323 field.attrs, fields[name]);
324 // modifiers computer
325 if (column.modifiers) {
326 var modifiers = JSON.parse(column.modifiers);
327 column.modifiers_for = function (fields) {
328 if (!modifiers.invisible) {
332 'invisible': domain_computer(modifiers.invisible, fields)
335 if (modifiers['tree_invisible']) {
336 column.invisible = '1';
339 column.modifiers_for = noop;
344 this.columns.splice(0, this.columns.length);
345 this.columns.push.apply(
347 _(this.fields_view.arch.children).map(field_to_column));
349 this.columns.unshift({
350 id: '_group', tag: '', string: "Group", meta: true,
351 modifiers_for: function () { return {}; }
353 id: '_count', tag: '', string: '#', meta: true,
354 modifiers_for: function () { return {}; }
358 this.visible_columns = _.filter(this.columns, function (column) {
359 return column.invisible !== '1';
362 this.aggregate_columns = _(this.visible_columns)
363 .map(function (column) {
364 if (column.type !== 'integer' && column.type !== 'float') {
367 var aggregation_func = column['group_operator'] || 'sum';
368 if (!(aggregation_func in column)) {
372 return _.extend({}, column, {
373 'function': aggregation_func,
374 label: column[aggregation_func]
379 * Used to handle a click on a table row, if no other handler caught the
382 * The default implementation asks the list view's view manager to switch
383 * to a different view (by calling
384 * :js:func:`~openerp.web.ViewManager.on_mode_switch`), using the
385 * provided record index (within the current list view's dataset).
387 * If the index is null, ``switch_to_record`` asks for the creation of a
390 * @param {Number|void} index the record index (in the current dataset) to switch to
391 * @param {String} [view="form"] the view type to switch to
393 select_record:function (index, view) {
394 view = view || 'form';
395 this.dataset.index = index;
396 _.delay(_.bind(function () {
397 this.do_switch_view(view);
400 do_show: function () {
401 this.$element.show();
403 this.sidebar.$element.show();
406 do_hide: function () {
407 this.$element.hide();
409 this.sidebar.$element.hide();
413 * Reloads the list view based on the current settings (dataset & al)
415 * @param {Boolean} [grouped] Should the list be displayed grouped
416 * @param {Object} [context] context to send the server while loading the view
418 reload_view: function (grouped, context, initial) {
420 var callback = function (field_view_get) {
421 self.on_loaded(field_view_get, grouped);
423 if (this.embedded_view) {
424 return $.Deferred().then(callback).resolve(this.embedded_view);
426 return this.rpc('/web/listview/load', {
428 view_id: this.view_id,
430 context: this.dataset.get_context(context),
431 toolbar: this.options.sidebar
436 * re-renders the content of the list view
438 * @returns {$.Deferred} promise to content reloading
440 reload_content: function () {
442 this.records.reset();
443 var reloaded = $.Deferred();
444 this.$element.find('.oe-listview-content').append(
445 this.groups.render(function () {
446 if (self.dataset.index == null) {
448 self.records.each(function () { has_one = true; });
450 self.dataset.index = 0;
453 self.compute_aggregates();
456 return reloaded.promise();
459 * Handler for the result of eval_domain_and_context, actually perform the
462 * @param {Object} results results of evaluating domain and process for a search
464 do_search: function (domain, context, group_by) {
465 this.groups.datagroup = new openerp.web.DataGroup(
466 this, this.model, domain, context, group_by);
467 this.groups.datagroup.sort = this.dataset._sort;
469 if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
473 this.reload_view(!!group_by, context).then(
474 $.proxy(this, 'reload_content'));
477 * Handles the signal to delete lines from the records list
479 * @param {Array} ids the ids of the records to delete
481 do_delete: function (ids) {
482 if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
486 return $.when(this.dataset.unlink(ids)).then(function () {
487 _(ids).each(function (id) {
488 self.records.remove(self.records.get(id));
490 self.configure_pager(self.dataset);
491 self.compute_aggregates();
495 * Handles the signal indicating that a new record has been selected
497 * @param {Array} ids selected record ids
498 * @param {Array} records selected record values
500 do_select: function (ids, records) {
501 this.$element.find('.oe-list-delete')
502 .attr('disabled', !ids.length);
505 this.sidebar.do_unfold();
507 this.sidebar.do_fold();
510 if (!records.length) {
511 this.compute_aggregates();
514 this.compute_aggregates(_(records).map(function (record) {
515 return {count: 1, values: record};
519 * Handles action button signals on a record
521 * @param {String} name action name
522 * @param {Object} id id of the record the action should be called on
523 * @param {Function} callback should be called after the action is executed, if non-null
525 do_button_action: function (name, id, callback) {
526 var action = _.detect(this.columns, function (field) {
527 return field.name === name;
529 if (!action) { return; }
531 var c = new openerp.web.CompoundContext();
532 c.set_eval_context(_.extend({
535 active_model: this.dataset.model
536 }, this.records.get(id).toContext()));
537 if (action.context) {
538 c.add(action.context);
541 this.do_execute_action(action, this.dataset, id, callback);
544 * Handles the activation of a record (clicking on it)
546 * @param {Number} index index of the record in the dataset
547 * @param {Object} id identifier of the activated record
548 * @param {openerp.web.DataSet} dataset dataset in which the record is available (may not be the listview's dataset in case of nested groups)
550 do_activate_record: function (index, id, dataset) {
551 this.dataset.ids = dataset.ids;
552 this.select_record(index);
555 * Handles signal for the addition of a new record (can be a creation,
556 * can be the addition from a remote source, ...)
558 * The default implementation is to switch to a new record on the form view
560 do_add_record: function () {
561 this.select_record(null);
564 * Handles deletion of all selected lines
566 do_delete_selected: function () {
567 this.do_delete(this.groups.get_selection().ids);
570 * Computes the aggregates for the current list view, either on the
571 * records provided or on the records of the internal
572 * :js:class:`~openerp.web.ListView.Group`, by calling
573 * :js:func:`~openerp.web.ListView.group.get_records`.
575 * Then displays the aggregates in the table through
576 * :js:method:`~openerp.web.ListView.display_aggregates`.
578 * @param {Array} [records]
580 compute_aggregates: function (records) {
581 var columns = _(this.aggregate_columns).filter(function (column) {
582 return column['function']; });
583 if (_.isEmpty(columns)) { return; }
585 if (_.isEmpty(records)) {
586 records = this.groups.get_records();
588 records = _(records).compact();
590 var count = 0, sums = {};
591 _(columns).each(function (column) {
592 switch (column['function']) {
594 sums[column.id] = -Infinity;
597 sums[column.id] = Infinity;
603 _(records).each(function (record) {
604 count += record.count || 1;
605 _(columns).each(function (column) {
606 var field = column.id,
607 value = record.values[field];
608 switch (column['function']) {
610 sums[field] += value;
613 sums[field] += record.count * value;
616 if (sums[field] > value) {
621 if (sums[field] < value) {
630 _(columns).each(function (column) {
631 var field = column.id;
632 switch (column['function']) {
634 aggregates[field] = {value: sums[field] / count};
637 aggregates[field] = {value: sums[field]};
641 this.display_aggregates(aggregates);
643 display_aggregates: function (aggregation) {
644 var $footer_cells = this.$element.find('.oe-list-footer');
645 _(this.aggregate_columns).each(function (column) {
646 if (!column['function']) {
650 $footer_cells.filter(_.sprintf('[data-field=%s]', column.id))
651 .html(openerp.web.format_cell(aggregation, column, undefined, false));
654 get_selected_ids: function() {
655 var ids = this.groups.get_selection().ids;
659 * Adds padding columns at the start or end of all table rows (including
662 * @param {Number} count number of columns to add
663 * @param {Object} options
664 * @param {"before"|"after"} [position="after"] insertion position for the new columns
665 * @param {Object} [except] content row to not pad
667 pad_columns: function (count, options) {
668 options = options || {};
669 // padding for action/pager header
670 var $first_header = this.$element.find('thead tr:first th');
671 var colspan = $first_header.attr('colspan');
673 if (!this.previous_colspan) {
674 this.previous_colspan = colspan;
676 $first_header.attr('colspan', parseInt(colspan, 10) + count);
678 // Padding for column titles, footer and data rows
679 var $rows = this.$element
680 .find('.oe-listview-header-columns, tr:not(thead tr)')
681 .not(options['except']);
682 var newcols = new Array(count+1).join('<td class="oe-listview-padding"></td>');
683 if (options.position === 'before') {
684 $rows.prepend(newcols);
686 $rows.append(newcols);
690 * Removes all padding columns of the table
692 unpad_columns: function () {
693 this.$element.find('.oe-listview-padding').remove();
694 if (this.previous_colspan) {
696 .find('thead tr:first th')
697 .attr('colspan', this.previous_colspan);
698 this.previous_colspan = null;
702 openerp.web.ListView.List = openerp.web.Class.extend( /** @lends openerp.web.ListView.List# */{
704 * List display for the ListView, handles basic DOM events and transforms
705 * them in the relevant higher-level events, to which the list view (or
706 * other consumers) can subscribe.
708 * Events on this object are registered via jQuery.
713 * Triggered when a row is selected (using check boxes), provides an
714 * array of ids of all the selected records.
716 * Triggered when deletion buttons are hit, provide an array of ids of
717 * all the records being marked for suppression.
719 * Triggered when an action button is clicked, provides two parameters:
721 * * The name of the action to execute (as a string)
722 * * The id of the record to execute the action on
724 * Triggered when a row of the table is clicked, provides the index (in
725 * the rows array) and id of the selected record to the handle function.
727 * @constructs openerp.web.ListView.List
728 * @extends openerp.web.Class
730 * @param {Object} opts display options, identical to those of :js:class:`openerp.web.ListView`
732 init: function (group, opts) {
735 this.view = group.view;
736 this.session = this.view.session;
738 this.options = opts.options;
739 this.columns = opts.columns;
740 this.dataset = opts.dataset;
741 this.records = opts.records;
743 this.record_callbacks = {
744 'remove': function (event, record) {
745 var $row = self.$current.find(
746 '[data-id=' + record.get('id') + ']');
747 var index = $row.data('index');
749 self.refresh_zebra(index);
751 'reset': $.proxy(this, 'on_records_reset'),
752 'change': function (event, record) {
753 var $row = self.$current.find('[data-id=' + record.get('id') + ']');
754 $row.replaceWith(self.render_record(record));
756 'add': function (ev, records, record, index) {
757 var $new_row = $('<tr>').attr({
758 'data-id': record.get('id')
762 $new_row.prependTo(self.$current);
764 var previous_record = records.at(index-1),
765 $previous_sibling = self.$current.find(
766 '[data-id=' + previous_record.get('id') + ']');
767 $new_row.insertAfter($previous_sibling);
770 self.refresh_zebra(index, 1);
773 _(this.record_callbacks).each(function (callback, event) {
774 this.records.bind(event, callback);
777 this.$_element = $('<tbody class="ui-widget-content">')
778 .appendTo(document.body)
779 .delegate('th.oe-record-selector', 'click', function (e) {
781 var selection = self.get_selection();
783 'selected', [selection.ids, selection.records]);
785 .delegate('td.oe-record-delete button', 'click', function (e) {
787 var $row = $(e.target).closest('tr');
788 $(self).trigger('deleted', [[self.row_id($row)]]);
790 .delegate('td.oe-field-cell button', 'click', function (e) {
792 var $target = $(e.currentTarget),
793 field = $target.closest('td').data('field'),
794 $row = $target.closest('tr'),
795 record_id = self.row_id($row);
797 // note: $.data converts data to number if it's composed only
798 // of digits, nice when storing actual numbers, not nice when
799 // storing strings composed only of digits. Force the action
800 // name to be a string
801 $(self).trigger('action', [field.toString(), record_id, function () {
802 return self.reload_record(self.records.get(record_id));
805 .delegate('tr', 'click', function (e) {
807 var row_id = self.row_id(e.currentTarget);
808 if (row_id !== undefined) {
809 if (!self.dataset.select_id(row_id)) {
810 throw "Could not find id in dataset"
816 row_clicked: function () {
819 [this.dataset.ids[this.dataset.index],
822 render_cell: function (record, column) {
824 if(column.type === 'reference') {
825 value = record.get(column.id);
827 // Ensure that value is in a reference "shape", otherwise we're
828 // going to loop on performing name_get after we've resolved (and
829 // set) a human-readable version. m2o does not have this issue
830 // because the non-human-readable is just a number, where the
831 // human-readable version is a pair
832 if (value && (ref_match = /([\w\.]+),(\d+)/.exec(value))) {
833 // reference values are in the shape "$model,$id" (as a
834 // string), we need to split and name_get this pair in order
835 // to get a correctly displayable value in the field
836 var model = ref_match[1],
837 id = parseInt(ref_match[2], 10);
838 new openerp.web.DataSet(this.view, model).name_get([id], function(names) {
839 if (!names.length) { return; }
840 record.set(column.id, names[0][1]);
843 } else if (column.type === 'many2one') {
844 value = record.get(column.id);
845 // m2o values are usually name_get formatted, [Number, String]
846 // pairs, but in some cases only the id is provided. In these
847 // cases, we need to perform a name_get call to fetch the actual
849 if (typeof value === 'number' || value instanceof Number) {
850 // fetch the name, set it on the record (in the right field)
851 // and let the various registered events handle refreshing the
853 new openerp.web.DataSet(this.view, column.relation)
854 .name_get([value], function (names) {
855 if (!names.length) { return; }
856 record.set(column.id, names[0]);
860 return openerp.web.format_cell(record.toForm().data, column);
862 render: function () {
864 this.$current.remove();
866 this.$current = this.$_element.clone(true);
867 this.$current.empty().append(
868 QWeb.render('ListView.rows', _.extend({
869 render_cell: $.proxy(this, 'render_cell')}, this)));
870 this.pad_table_to(5);
872 pad_table_to: function (count) {
873 if (this.records.length >= count ||
874 _(this.columns).any(function(column) { return column.meta; })) {
878 if (this.options.selectable) {
879 cells.push('<th class="oe-record-selector"></td>');
881 _(this.columns).each(function(column) {
882 if (column.invisible === '1') {
885 if (column.tag === 'button') {
886 cells.push('<td class="oe-button" title="' + column.string + '"> </td>');
888 cells.push('<td title="' + column.string + '"> </td>');
891 if (this.options.deletable) {
892 cells.push('<td class="oe-record-delete"><button type="button" style="visibility: hidden"> </button></td>');
894 cells.unshift('<tr>');
897 var row = cells.join('');
899 .children('tr:not([data-id])').remove().end()
900 .append(new Array(count - this.records.length + 1).join(row));
901 this.refresh_zebra(this.records.length);
904 * Gets the ids of all currently selected records, if any
905 * @returns {Object} object with the keys ``ids`` and ``records``, holding respectively the ids of all selected records and the records themselves.
907 get_selection: function () {
908 if (!this.options.selectable) {
911 var records = this.records;
912 var result = {ids: [], records: []};
913 this.$current.find('th.oe-record-selector input:checked')
914 .closest('tr').each(function () {
915 var record = records.get($(this).data('id'));
916 result.ids.push(record.get('id'));
917 result.records.push(record.attributes);
922 * Returns the identifier of the object displayed in the provided table
925 * @param {Object} row the selected table row
926 * @returns {Number|String} the identifier of the row's object
928 row_id: function (row) {
929 return $(row).data('id');
932 * Death signal, cleans up list display
934 on_records_reset: function () {
935 _(this.record_callbacks).each(function (callback, event) {
936 this.records.unbind(event, callback);
938 if (!this.$current) { return; }
939 this.$current.remove();
940 this.$current = null;
941 this.$_element.remove();
943 get_records: function () {
944 return this.records.map(function (record) {
945 return {count: 1, values: record.attributes};
949 * Reloads the provided record by re-reading its content from the server.
951 * @param {Record} record
952 * @returns {$.Deferred} promise to the finalization of the reloading
954 reload_record: function (record) {
955 return this.dataset.read_ids(
957 _.pluck(_(this.columns).filter(function (r) {
958 return r.tag === 'field';
961 _(records[0]).each(function (value, key) {
962 record.set(key, value, {silent: true});
964 record.trigger('change', record);
969 * Renders a list record to HTML
971 * @param {Record} record index of the record to render in ``this.rows``
972 * @returns {String} QWeb rendering of the selected record
974 render_record: function (record) {
975 var index = this.records.indexOf(record);
976 return QWeb.render('ListView.row', {
977 columns: this.columns,
978 options: this.options,
980 row_parity: (index % 2 === 0) ? 'even' : 'odd',
982 render_cell: $.proxy(this, 'render_cell')
986 * Fixes fixes the even/odd classes
988 * @param {Number} [from_index] index from which to resequence
989 * @param {Number} [offset = 0] selection offset for DOM, in case there are rows to ignore in the table
991 refresh_zebra: function (from_index, offset) {
992 offset = offset || 0;
993 from_index = from_index || 0;
994 var dom_offset = offset + from_index;
995 var sel = dom_offset ? ':gt(' + (dom_offset - 1) + ')' : null;
996 this.$current.children(sel).each(function (i, e) {
997 var index = from_index + i;
998 // reset record-index accelerators on rows and even/odd
999 var even = index%2 === 0;
1000 $(e).toggleClass('even', even)
1001 .toggleClass('odd', !even);
1005 openerp.web.ListView.Groups = openerp.web.Class.extend( /** @lends openerp.web.ListView.Groups# */{
1006 passtrough_events: 'action deleted row_link',
1008 * Grouped display for the ListView. Handles basic DOM events and interacts
1009 * with the :js:class:`~openerp.web.DataGroup` bound to it.
1011 * Provides events similar to those of
1012 * :js:class:`~openerp.web.ListView.List`
1014 * @constructs openerp.web.ListView.Groups
1015 * @extends openerp.web.Class
1017 * @param {openerp.web.ListView} view
1018 * @param {Object} [options]
1019 * @param {Collection} [options.records]
1020 * @param {Object} [options.options]
1021 * @param {Array} [options.columns]
1023 init: function (view, options) {
1024 options = options || {};
1026 this.records = options.records || view.records;
1027 this.options = options.options || view.options;
1028 this.columns = options.columns || view.columns;
1029 this.datagroup = null;
1036 this.records.bind('reset', $.proxy(this, 'on_records_reset'));
1038 make_fragment: function () {
1039 return document.createDocumentFragment();
1042 * Returns a DOM node after which a new tbody can be inserted, so that it
1043 * follows the provided row.
1045 * Necessary to insert the result of a new group or list view within an
1046 * existing groups render, without losing track of the groups's own
1049 * @param {HTMLTableRowElement} row the row after which the caller wants to insert a body
1050 * @returns {HTMLTableSectionElement} element after which a tbody can be inserted
1052 point_insertion: function (row) {
1054 var red_letter_tboday = $row.closest('tbody')[0];
1056 var $next_siblings = $row.nextAll();
1057 if ($next_siblings.length) {
1058 var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1060 $root_kanal.append($next_siblings);
1061 this.elements.splice(
1062 _.indexOf(this.elements, red_letter_tboday),
1066 return red_letter_tboday;
1068 make_paginator: function () {
1070 var $prev = $('<button type="button" data-pager-action="previous"><</button>')
1071 .click(function (e) {
1072 e.stopPropagation();
1075 self.$row.closest('tbody').next()
1076 .replaceWith(self.render());
1078 var $next = $('<button type="button" data-pager-action="next">></button>')
1079 .click(function (e) {
1080 e.stopPropagation();
1083 self.$row.closest('tbody').next()
1084 .replaceWith(self.render());
1086 this.$row.children().last()
1088 .append('<span class="oe-pager-state"></span>')
1091 open: function (point_insertion) {
1092 this.render().insertAfter(point_insertion);
1093 this.make_paginator();
1095 close: function () {
1096 this.$row.children().last().empty();
1097 this.records.reset();
1100 * Prefixes ``$node`` with floated spaces in order to indent it relative
1101 * to its own left margin/baseline
1103 * @param {jQuery} $node jQuery object to indent
1104 * @param {Number} level current nesting level, >= 1
1105 * @returns {jQuery} the indentation node created
1107 indent: function ($node, level) {
1109 .css({'float': 'left', 'white-space': 'pre'})
1110 .text(new Array(level).join(' '))
1113 render_groups: function (datagroups) {
1115 var placeholder = this.make_fragment();
1116 _(datagroups).each(function (group) {
1117 if (self.children[group.value]) {
1118 self.records.proxy(group.value).reset();
1119 delete self.children[group.value];
1121 var child = self.children[group.value] = new openerp.web.ListView.Groups(self.view, {
1122 records: self.records.proxy(group.value),
1123 options: self.options,
1124 columns: self.columns
1126 self.bind_child_events(child);
1127 child.datagroup = group;
1129 var $row = child.$row = $('<tr>');
1130 if (group.openable) {
1131 $row.click(function (e) {
1132 if (!$row.data('open')) {
1133 $row.data('open', true)
1134 .find('span.ui-icon')
1135 .removeClass('ui-icon-triangle-1-e')
1136 .addClass('ui-icon-triangle-1-s');
1137 child.open(self.point_insertion(e.currentTarget));
1139 $row.removeData('open')
1140 .find('span.ui-icon')
1141 .removeClass('ui-icon-triangle-1-s')
1142 .addClass('ui-icon-triangle-1-e');
1147 placeholder.appendChild($row[0]);
1149 var $group_column = $('<th class="oe-group-name">').appendTo($row);
1150 // Don't fill this if group_by_no_leaf but no group_by
1151 if (group.grouped_on) {
1153 row_data[group.grouped_on] = group;
1154 var group_column = _(self.columns).detect(function (column) {
1155 return column.id === group.grouped_on; });
1157 $group_column.html(openerp.web.format_cell(
1158 row_data, group_column, _t("Undefined")));
1160 $group_column.html(row_data[group_column.id].value);
1162 if (group.openable) {
1163 // Make openable if not terminal group & group_by_no_leaf
1165 .prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1168 self.indent($group_column, group.level);
1170 $('<td>').text(group.length).appendTo($row);
1172 if (self.options.selectable) {
1173 $row.append('<td>');
1175 _(self.columns).chain()
1176 .filter(function (column) {return !column.invisible;})
1177 .each(function (column) {
1179 // do not do anything
1180 } else if (column.id in group.aggregates) {
1181 var value = group.aggregates[column.id];
1183 if (column.type === 'integer') {
1185 } else if (column.type === 'float') {
1189 .text(_.sprintf(format, value))
1192 $row.append('<td>');
1195 if (self.options.deletable) {
1196 $row.append('<td class="oe-group-pagination">');
1201 bind_child_events: function (child) {
1202 var $this = $(this),
1204 $(child).bind('selected', function (e) {
1205 // can have selections spanning multiple links
1206 var selection = self.get_selection();
1207 $this.trigger(e, [selection.ids, selection.records]);
1208 }).bind(this.passtrough_events, function (e) {
1209 // additional positional parameters are provided to trigger as an
1210 // Array, following the event type or event object, but are
1211 // provided to the .bind event handler as *args.
1212 // Convert our *args back into an Array in order to trigger them
1213 // on the group itself, so it can ultimately be forwarded wherever
1214 // it's supposed to go.
1215 var args = Array.prototype.slice.call(arguments, 1);
1216 $this.trigger.call($this, e, args);
1219 render_dataset: function (dataset) {
1221 list = new openerp.web.ListView.List(this, {
1222 options: this.options,
1223 columns: this.columns,
1225 records: this.records
1227 this.bind_child_events(list);
1229 var view = this.view,
1230 limit = view.limit(),
1231 d = new $.Deferred(),
1232 page = this.datagroup.openable ? this.page : view.page;
1234 var fields = _.pluck(_.select(this.columns, function(x) {return x.tag == "field"}), 'name');
1235 var options = { offset: page * limit, limit: limit };
1236 //TODO xmo: investigate why we need to put the setTimeout
1237 setTimeout(function() {dataset.read_slice(fields, options , function (records) {
1238 // FIXME: ignominious hacks, parents (aka form view) should not send two ListView#reload_content concurrently
1239 if (self.records.length) {
1240 self.records.reset(null, {silent: true});
1242 if (!self.datagroup.openable) {
1243 view.configure_pager(dataset);
1245 var pages = Math.ceil(dataset.ids.length / limit);
1247 .find('.oe-pager-state')
1248 .text(_.sprintf('%d/%d', page + 1, pages))
1250 .find('button[data-pager-action=previous]')
1251 .attr('disabled', page === 0)
1253 .find('button[data-pager-action=next]')
1254 .attr('disabled', page === pages - 1);
1257 self.records.add(records, {silent: true});
1263 setup_resequence_rows: function (list, dataset) {
1264 // drag and drop enabled if list is not sorted and there is a
1265 // "sequence" column in the view.
1266 if ((dataset.sort && dataset.sort())
1267 || !_(this.columns).any(function (column) {
1268 return column.name === 'sequence'; })) {
1271 // ondrop, move relevant record & fix sequences
1272 list.$current.sortable({
1274 items: '> tr[data-id]',
1275 stop: function (event, ui) {
1276 var to_move = list.records.get(ui.item.data('id')),
1277 target_id = ui.item.prev().data('id');
1279 list.records.remove(to_move);
1280 var to = target_id ? list.records.indexOf(list.records.get(target_id)) + 1 : 0;
1281 list.records.add(to_move, { at: to });
1283 // resequencing time!
1284 var record, index = to,
1285 // if drag to 1st row (to = 0), start sequencing from 0
1286 // (exclusive lower bound)
1287 seq = to ? list.records.at(to - 1).get('sequence') : 0;
1288 while (++seq, record = list.records.at(index++)) {
1289 // write are independent from one another, so we can just
1290 // launch them all at the same time and we don't really
1291 // give a fig about when they're done
1292 dataset.write(record.get('id'), {sequence: seq});
1293 record.set('sequence', seq);
1296 list.refresh_zebra();
1300 render: function (post_render) {
1302 var $element = $('<tbody>');
1303 this.elements = [$element[0]];
1305 this.datagroup.list(
1306 _(this.view.visible_columns).chain()
1307 .filter(function (column) { return column.tag === 'field' })
1308 .pluck('name').value(),
1310 $element[0].appendChild(
1311 self.render_groups(groups));
1312 if (post_render) { post_render(); }
1313 }, function (dataset) {
1314 self.render_dataset(dataset).then(function (list) {
1315 self.children[null] = list;
1317 [list.$current.replaceAll($element)[0]];
1318 self.setup_resequence_rows(list, dataset);
1319 if (post_render) { post_render(); }
1325 * Returns the ids of all selected records for this group, and the records
1328 get_selection: function () {
1329 var ids = [], records = [];
1332 .each(function (child) {
1333 var selection = child.get_selection();
1334 ids.push.apply(ids, selection.ids);
1335 records.push.apply(records, selection.records);
1338 return {ids: ids, records: records};
1340 on_records_reset: function () {
1342 $(this.elements).remove();
1344 get_records: function () {
1345 if (_(this.children).isEmpty()) {
1346 if (!this.datagroup.length) {
1350 count: this.datagroup.length,
1351 values: this.datagroup.aggregates
1354 return _(this.children).chain()
1355 .map(function (child) {
1356 return child.get_records();
1357 }).flatten().value();
1364 var Events = /** @lends Events# */{
1366 * @param {String} event event to listen to on the current object, null for all events
1367 * @param {Function} handler event handler to bind to the relevant event
1370 bind: function (event, handler) {
1371 var calls = this['_callbacks'] || (this._callbacks = {});
1373 if (event in calls) {
1374 calls[event].push(handler);
1376 calls[event] = [handler];
1381 * @param {String} event event to unbind on the current object
1382 * @param {function} [handler] specific event handler to remove (otherwise unbind all handlers for the event)
1385 unbind: function (event, handler) {
1386 var calls = this._callbacks || {};
1387 if (!(event in calls)) { return this; }
1389 delete calls[event];
1391 var handlers = calls[event];
1393 _(handlers).indexOf(handler),
1399 * @param {String} event
1402 trigger: function (event) {
1404 if (!(calls = this._callbacks)) { return this; }
1405 var callbacks = (calls[event] || []).concat(calls[null] || []);
1406 for(var i=0, length=callbacks.length; i<length; ++i) {
1407 callbacks[i].apply(this, arguments);
1412 var Record = openerp.web.Class.extend(/** @lends Record# */{
1414 * @constructs Record
1415 * @extends openerp.web.Class
1418 * @param {Object} [data]
1420 init: function (data) {
1421 this.attributes = data || {};
1424 * @param {String} key
1427 get: function (key) {
1428 return this.attributes[key];
1433 * @param {Object} [options]
1434 * @param {Boolean} [options.silent=false]
1437 set: function (key, value, options) {
1438 options = options || {};
1439 var old_value = this.attributes[key];
1440 if (old_value === value) {
1443 this.attributes[key] = value;
1444 if (!options.silent) {
1445 this.trigger('change:' + key, this, value, old_value);
1446 this.trigger('change', this, key, value, old_value);
1451 * Converts the current record to the format expected by form views:
1453 * .. code-block:: javascript
1462 * @returns {Object} record displayable in a form view
1464 toForm: function () {
1465 var form_data = {}, attrs = this.attributes;
1466 for(var k in attrs) {
1467 form_data[k] = {value: attrs[k]};
1470 return {data: form_data};
1473 * Converts the current record to a format expected by context evaluations
1474 * (identical to record.attributes, except m2o fields are their integer
1475 * value rather than a pair)
1477 toContext: function () {
1478 var output = {}, attrs = this.attributes;
1479 for(var k in attrs) {
1481 if (typeof val !== 'object') {
1483 } else if (val instanceof Array) {
1486 throw new Error("Can't convert value " + val + " to context");
1492 Record.include(Events);
1493 var Collection = openerp.web.Class.extend(/** @lends Collection# */{
1495 * Smarter collections, with events, very strongly inspired by Backbone's.
1497 * Using a "dumb" array of records makes synchronization between the
1500 * @constructs Collection
1501 * @extends openerp.web.Class
1504 * @param {Array} [records] records to initialize the collection with
1505 * @param {Object} [options]
1507 init: function (records, options) {
1508 options = options || {};
1509 _.bindAll(this, '_onRecordEvent');
1514 this._key = options.key;
1515 this._parent = options.parent;
1522 * @param {Object|Array} record
1523 * @param {Object} [options]
1524 * @param {Number} [options.at]
1525 * @param {Boolean} [options.silent=false]
1528 add: function (record, options) {
1529 options = options || {};
1530 var records = record instanceof Array ? record : [record];
1532 for(var i=0, length=records.length; i<length; ++i) {
1533 var instance = (records[i] instanceof Record) ? records[i] : new Record(records[i]);
1534 instance.bind(null, this._onRecordEvent);
1535 this._byId[instance.get('id')] = instance;
1536 if (options.at == undefined) {
1537 this.records.push(instance);
1538 if (!options.silent) {
1539 this.trigger('add', this, instance, this.records.length-1);
1542 var insertion_index = options.at + i;
1543 this.records.splice(insertion_index, 0, instance);
1544 if (!options.silent) {
1545 this.trigger('add', this, instance, insertion_index);
1554 * Get a record by its index in the collection, can also take a group if
1555 * the collection is not degenerate
1557 * @param {Number} index
1558 * @param {String} [group]
1559 * @returns {Record|undefined}
1561 at: function (index, group) {
1563 var groups = group.split('.');
1564 return this._proxies[groups[0]].at(index, groups.join('.'));
1566 return this.records[index];
1569 * Get a record by its database id
1571 * @param {Number} id
1572 * @returns {Record|undefined}
1574 get: function (id) {
1575 if (!_(this._proxies).isEmpty()) {
1577 _(this._proxies).detect(function (proxy) {
1578 return record = proxy.get(id);
1582 return this._byId[id];
1585 * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1586 * the subtree's group
1588 * @param {String} section group path section
1589 * @returns {Collection}
1591 proxy: function (section) {
1592 return this._proxies[section] = new Collection(null, {
1595 }).bind(null, this._onRecordEvent);
1598 * @param {Array} [records]
1601 reset: function (records, options) {
1602 options = options || {};
1603 _(this._proxies).each(function (proxy) {
1613 if (!options.silent) {
1614 this.trigger('reset', this);
1619 * Removes the provided record from the collection
1621 * @param {Record} record
1624 remove: function (record) {
1626 var index = _(this.records).indexOf(record);
1628 _(this._proxies).each(function (proxy) {
1629 proxy.remove(record);
1634 this.records.splice(index, 1);
1635 delete this._byId[record.get('id')];
1637 this.trigger('remove', record, this);
1641 _onRecordEvent: function (event, record, options) {
1642 // don't propagate reset events
1643 if (event === 'reset') { return; }
1644 this.trigger.apply(this, arguments);
1647 // underscore-type methods
1648 each: function (callback) {
1649 for(var section in this._proxies) {
1650 if (this._proxies.hasOwnProperty(section)) {
1651 this._proxies[section].each(callback);
1654 for(var i=0; i<this.length; ++i) {
1655 callback(this.records[i]);
1658 map: function (callback) {
1660 this.each(function (record) {
1661 results.push(callback(record));
1665 pluck: function (fieldname) {
1666 return this.map(function (record) {
1667 return record.get(fieldname);
1670 indexOf: function (record) {
1671 return _(this.records).indexOf(record);
1674 Collection.include(Events);
1675 openerp.web.list = {
1678 Collection: Collection
1681 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: