[FIX] cell borders in padding rows of list views
[odoo/odoo.git] / addons / web / static / src / js / view_list.js
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# */ {
6     defaults: {
7         // records can be selected one by one
8         'selectable': true,
9         // list rows can be deleted
10         'deletable': true,
11         // whether the column headers should be displayed
12         'header': true,
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
17         'sortable': true,
18         // whether the view rows can be reordered (via vertical drag & drop)
19         'reorderable': true
20     },
21     /**
22      * Core class for list-type displays.
23      *
24      * As a view, needs a number of view-related parameters to be correctly
25      * instantiated, provides options and overridable methods for behavioral
26      * customization.
27      *
28      * See constructor parameters and method documentations for information on
29      * the default behaviors and possible options for the list view.
30      *
31      * @constructs openerp.web.ListView
32      * @extends openerp.web.View
33      *
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
44      */
45     init: function(parent, dataset, view_id, options) {
46         var self = this;
47         this._super(parent);
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;
53         this.colors = null;
54
55         this.columns = [];
56
57         this.records = new Collection();
58
59         this.set_groups(new openerp.web.ListView.Groups(this));
60
61         if (this.dataset instanceof openerp.web.DataSetStatic) {
62             this.groups.datagroup = new openerp.web.StaticDataGroup(this.dataset);
63         } else {
64             this.groups.datagroup = new openerp.web.DataGroup(
65                 this, this.model,
66                 dataset.get_domain(),
67                 dataset.get_context(),
68                 {});
69             this.groups.datagroup.sort = this.dataset._sort;
70         }
71
72         this.page = 0;
73         this.records.bind('change', function (event, record, key) {
74             if (!_(self.aggregate_columns).chain()
75                     .pluck('name').contains(key).value()) {
76                 return;
77             }
78             self.compute_aggregates();
79         });
80
81     },
82     /**
83      * Retrieves the view's number of records per page (|| section)
84      *
85      * options > defaults > parent.action.limit > indefinite
86      *
87      * @returns {Number|null}
88      */
89     limit: function () {
90         if (this._limit === undefined) {
91             this._limit = (this.options.limit
92                         || this.defaults.limit
93                         || (this.widget_parent.action || {}).limit
94                         || null);
95         }
96         return this._limit;
97     },
98     /**
99      * Set a custom Group construct as the root of the List View.
100      *
101      * @param {openerp.web.ListView.Groups} groups
102      */
103     set_groups: function (groups) {
104         var self = this;
105         if (this.groups) {
106             $(this.groups).unbind("selected deleted action row_link");
107             delete this.groups;
108         }
109
110         this.groups = groups;
111         $(this.groups).bind({
112             'selected': function (e, ids, records) {
113                 self.do_select(ids, records);
114             },
115             'deleted': function (e, ids) {
116                 self.do_delete(ids);
117             },
118             'action': function (e, action_name, id, callback) {
119                 self.do_button_action(action_name, id, callback);
120             },
121             'row_link': function (e, id, dataset) {
122                 self.do_activate_record(dataset.index, id, dataset);
123             }
124         });
125     },
126     /**
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.
129      *
130      * @returns {$.Deferred} loading promise
131      */
132     start: function() {
133         this._super();
134         this.$element.addClass('oe-listview');
135         return this.reload_view(null, null, true);
136     },
137     /**
138      * Returns the color for the provided record in the current view (from the
139      * ``@colors`` attribute)
140      *
141      * @param {Record} record record for the current row
142      * @returns {String} CSS color declaration
143      */
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
150         });
151         for(var i=0, len=this.colors.length; i<len; ++i) {
152             var pair = this.colors[i],
153                 color = pair[0],
154                 expression = pair[1];
155             if (py.evaluate(expression, context)) {
156                 return 'color: ' + color + ';';
157             }
158             // TODO: handle evaluation errors
159         }
160         return '';
161     },
162     /**
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
167      * record, ...)
168      *
169      * Sets up the following:
170      *
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
178      *
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
184      */
185     on_loaded: function(data, grouped) {
186         var self = this;
187         this.fields_view = data;
188         this.name = "" + this.fields_view.arch.attrs.string;
189
190         if (this.fields_view.arch.attrs.colors) {
191             this.colors = _(this.fields_view.arch.attrs.colors.split(';')).chain()
192                 .compact()
193                 .map(function(color_pair) {
194                     var pair = color_pair.split(':'),
195                         color = pair[0],
196                         expr = pair[1];
197                     return [color, py.parse(py.tokenize(expr)), expr];
198                 }).value();
199         }
200
201         this.setup_columns(this.fields_view.fields, grouped);
202
203         this.$element.html(QWeb.render("ListView", this));
204         // Head hook
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]);
211         });
212
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) {
220             e.stopPropagation();
221
222             var $this = $(this);
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');
227             } else {
228                 $this.append('<span class="ui-icon ui-icon-triangle-1-s">')
229                      .siblings('.oe-sortable').find('span').remove();
230             }
231
232             self.reload_content();
233         });
234
235         this.$element.find('.oe-list-pager')
236             .delegate('button', 'click', function () {
237                 var $this = $(this);
238                 switch ($this.data('pager-action')) {
239                     case 'first':
240                         self.page = 0; break;
241                     case 'last':
242                         self.page = Math.floor(
243                             self.dataset.ids.length / self.limit());
244                         break;
245                     case 'next':
246                         self.page += 1; break;
247                     case 'previous':
248                         self.page -= 1; break;
249                 }
250                 self.reload_content();
251             }).find('.oe-pager-state')
252                 .click(function (e) {
253                     e.stopPropagation();
254                     var $this = $(this);
255
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);
267                             self.page = 0;
268                             self.reload_content();
269                         })
270                         .val(self._limit || 'NaN');
271                 });
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);
277         }
278     },
279     /**
280      * Configures the ListView pager based on the provided dataset's information
281      *
282      * Horrifying side-effect: sets the dataset's data on this.dataset?
283      *
284      * @param {openerp.web.DataSet} dataset
285      */
286     configure_pager: function (dataset) {
287         this.dataset.ids = dataset.ids;
288
289         var limit = this.limit(),
290             total = dataset.ids.length,
291             first = (this.page * limit),
292             last;
293         if (!limit || (total - first) < limit) {
294             last = total;
295         } else {
296             last = first + limit;
297         }
298         this.$element.find('span.oe-pager-state').empty().text(_.sprintf(
299             "[%d to %d] of %d", first + 1, last, total));
300
301         this.$element
302             .find('button[data-pager-action=first], button[data-pager-action=previous]')
303                 .attr('disabled', this.page === 0)
304             .end()
305             .find('button[data-pager-action=last], button[data-pager-action=next]')
306                 .attr('disabled', last === total);
307     },
308     /**
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
311      * visible.
312      *
313      * @param {Object} fields fields_view_get's fields section
314      * @param {Boolean} [grouped] Should the grouping columns (group and count) be displayed
315      */
316     setup_columns: function (fields, grouped) {
317         var domain_computer = openerp.web.form.compute_domain;
318
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) {
329                         return {};
330                     }
331                     return {
332                         'invisible': domain_computer(modifiers.invisible, fields)
333                     };
334                 };
335                 if (modifiers['tree_invisible']) {
336                     column.invisible = '1';
337                 }
338             } else {
339                 column.modifiers_for = noop;
340             }
341             return column;
342         };
343
344         this.columns.splice(0, this.columns.length);
345         this.columns.push.apply(
346                 this.columns,
347                 _(this.fields_view.arch.children).map(field_to_column));
348         if (grouped) {
349             this.columns.unshift({
350                 id: '_group', tag: '', string: "Group", meta: true,
351                 modifiers_for: function () { return {}; }
352             }, {
353                 id: '_count', tag: '', string: '#', meta: true,
354                 modifiers_for: function () { return {}; }
355             });
356         }
357
358         this.visible_columns = _.filter(this.columns, function (column) {
359             return column.invisible !== '1';
360         });
361
362         this.aggregate_columns = _(this.visible_columns)
363             .map(function (column) {
364                 if (column.type !== 'integer' && column.type !== 'float') {
365                     return {};
366                 }
367                 var aggregation_func = column['group_operator'] || 'sum';
368                 if (!(aggregation_func in column)) {
369                     return {};
370                 }
371
372                 return _.extend({}, column, {
373                     'function': aggregation_func,
374                     label: column[aggregation_func]
375                 });
376             });
377     },
378     /**
379      * Used to handle a click on a table row, if no other handler caught the
380      * event.
381      *
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).
386      *
387      * If the index is null, ``switch_to_record`` asks for the creation of a
388      * new record.
389      *
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
392      */
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);
398         }, this));
399     },
400     do_show: function () {
401         this.$element.show();
402         if (this.sidebar) {
403             this.sidebar.$element.show();
404         }
405     },
406     do_hide: function () {
407         this.$element.hide();
408         if (this.sidebar) {
409             this.sidebar.$element.hide();
410         }
411     },
412     /**
413      * Reloads the list view based on the current settings (dataset & al)
414      *
415      * @param {Boolean} [grouped] Should the list be displayed grouped
416      * @param {Object} [context] context to send the server while loading the view
417      */
418     reload_view: function (grouped, context, initial) {
419         var self = this;
420         var callback = function (field_view_get) {
421             self.on_loaded(field_view_get, grouped);
422         };
423         if (this.embedded_view) {
424             return $.Deferred().then(callback).resolve(this.embedded_view);
425         } else {
426             return this.rpc('/web/listview/load', {
427                 model: this.model,
428                 view_id: this.view_id,
429                 view_type: "tree",
430                 context: this.dataset.get_context(context),
431                 toolbar: this.options.sidebar
432             }, callback);
433         }
434     },
435     /**
436      * re-renders the content of the list view
437      *
438      * @returns {$.Deferred} promise to content reloading
439      */
440     reload_content: function () {
441         var self = this;
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) {
447                     var has_one = false;
448                     self.records.each(function () { has_one = true; });
449                     if (has_one) {
450                         self.dataset.index = 0;
451                     }
452                 }
453                 self.compute_aggregates();
454                 reloaded.resolve();
455             }));
456         return reloaded.promise();
457     },
458     /**
459      * Handler for the result of eval_domain_and_context, actually perform the
460      * searching
461      *
462      * @param {Object} results results of evaluating domain and process for a search
463      */
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;
468
469         if (_.isEmpty(group_by) && !context['group_by_no_leaf']) {
470             group_by = null;
471         }
472
473         this.reload_view(!!group_by, context).then(
474             $.proxy(this, 'reload_content'));
475     },
476     /**
477      * Handles the signal to delete lines from the records list
478      *
479      * @param {Array} ids the ids of the records to delete
480      */
481     do_delete: function (ids) {
482         if (!(ids.length && confirm(_t("Do you really want to remove these records?")))) {
483             return;
484         }
485         var self = this;
486         return $.when(this.dataset.unlink(ids)).then(function () {
487             _(ids).each(function (id) {
488                 self.records.remove(self.records.get(id));
489             });
490             self.configure_pager(self.dataset);
491             self.compute_aggregates();
492         });
493     },
494     /**
495      * Handles the signal indicating that a new record has been selected
496      *
497      * @param {Array} ids selected record ids
498      * @param {Array} records selected record values
499      */
500     do_select: function (ids, records) {
501         this.$element.find('.oe-list-delete')
502             .attr('disabled', !ids.length);
503         if (this.sidebar) {
504             if (ids.length) {
505                 this.sidebar.do_unfold();
506             } else {
507                 this.sidebar.do_fold();
508             }
509         }
510         if (!records.length) {
511             this.compute_aggregates();
512             return;
513         }
514         this.compute_aggregates(_(records).map(function (record) {
515             return {count: 1, values: record};
516         }));
517     },
518     /**
519      * Handles action button signals on a record
520      *
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
524      */
525     do_button_action: function (name, id, callback) {
526         var action = _.detect(this.columns, function (field) {
527             return field.name === name;
528         });
529         if (!action) { return; }
530
531         var c = new openerp.web.CompoundContext();
532         c.set_eval_context(_.extend({
533             active_id: id,
534             active_ids: [id],
535             active_model: this.dataset.model
536         }, this.records.get(id).toContext()));
537         if (action.context) {
538             c.add(action.context);
539         }
540         action.context = c;
541         this.do_execute_action(action, this.dataset, id, callback);
542     },
543     /**
544      * Handles the activation of a record (clicking on it)
545      *
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)
549      */
550     do_activate_record: function (index, id, dataset) {
551         this.dataset.ids = dataset.ids;
552         this.select_record(index);
553     },
554     /**
555      * Handles signal for the addition of a new record (can be a creation,
556      * can be the addition from a remote source, ...)
557      *
558      * The default implementation is to switch to a new record on the form view
559      */
560     do_add_record: function () {
561         this.select_record(null);
562     },
563     /**
564      * Handles deletion of all selected lines
565      */
566     do_delete_selected: function () {
567         this.do_delete(this.groups.get_selection().ids);
568     },
569     /**
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`.
574      *
575      * Then displays the aggregates in the table through
576      * :js:method:`~openerp.web.ListView.display_aggregates`.
577      *
578      * @param {Array} [records]
579      */
580     compute_aggregates: function (records) {
581         var columns = _(this.aggregate_columns).filter(function (column) {
582             return column['function']; });
583         if (_.isEmpty(columns)) { return; }
584
585         if (_.isEmpty(records)) {
586             records = this.groups.get_records();
587         }
588         records = _(records).compact();
589
590         var count = 0, sums = {};
591         _(columns).each(function (column) {
592             switch (column['function']) {
593                 case 'max':
594                     sums[column.id] = -Infinity;
595                     break;
596                 case 'min':
597                     sums[column.id] = Infinity;
598                     break;
599                 default:
600                     sums[column.id] = 0;
601             }
602         });
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']) {
609                     case 'sum':
610                         sums[field] += value;
611                         break;
612                     case 'avg':
613                         sums[field] += record.count * value;
614                         break;
615                     case 'min':
616                         if (sums[field] > value) {
617                             sums[field] = value;
618                         }
619                         break;
620                     case 'max':
621                         if (sums[field] < value) {
622                             sums[field] = value;
623                         }
624                         break;
625                 }
626             });
627         });
628
629         var aggregates = {};
630         _(columns).each(function (column) {
631             var field = column.id;
632             switch (column['function']) {
633                 case 'avg':
634                     aggregates[field] = {value: sums[field] / count};
635                     break;
636                 default:
637                     aggregates[field] = {value: sums[field]};
638             }
639         });
640
641         this.display_aggregates(aggregates);
642     },
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']) {
647                 return;
648             }
649
650             $footer_cells.filter(_.sprintf('[data-field=%s]', column.id))
651                 .html(openerp.web.format_cell(aggregation, column, undefined, false));
652         });
653     },
654     get_selected_ids: function() {
655         var ids = this.groups.get_selection().ids;
656         return ids;
657     },
658     /**
659      * Adds padding columns at the start or end of all table rows (including
660      * field names row)
661      *
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
666      */
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');
672         if (colspan) {
673             if (!this.previous_colspan) {
674                 this.previous_colspan = colspan;
675             }
676             $first_header.attr('colspan', parseInt(colspan, 10) + count);
677         }
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);
685         } else {
686             $rows.append(newcols);
687         }
688     },
689     /**
690      * Removes all padding columns of the table
691      */
692     unpad_columns: function () {
693         this.$element.find('.oe-listview-padding').remove();
694         if (this.previous_colspan) {
695             this.$element
696                     .find('thead tr:first th')
697                     .attr('colspan', this.previous_colspan);
698             this.previous_colspan = null;
699         }
700     }
701 });
702 openerp.web.ListView.List = openerp.web.Class.extend( /** @lends openerp.web.ListView.List# */{
703     /**
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.
707      *
708      * Events on this object are registered via jQuery.
709      *
710      * Available events:
711      *
712      * `selected`
713      *   Triggered when a row is selected (using check boxes), provides an
714      *   array of ids of all the selected records.
715      * `deleted`
716      *   Triggered when deletion buttons are hit, provide an array of ids of
717      *   all the records being marked for suppression.
718      * `action`
719      *   Triggered when an action button is clicked, provides two parameters:
720      *
721      *   * The name of the action to execute (as a string)
722      *   * The id of the record to execute the action on
723      * `row_link`
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.
726      *
727      * @constructs openerp.web.ListView.List
728      * @extends openerp.web.Class
729      * 
730      * @param {Object} opts display options, identical to those of :js:class:`openerp.web.ListView`
731      */
732     init: function (group, opts) {
733         var self = this;
734         this.group = group;
735         this.view = group.view;
736         this.session = this.view.session;
737
738         this.options = opts.options;
739         this.columns = opts.columns;
740         this.dataset = opts.dataset;
741         this.records = opts.records;
742
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');
748                 $row.remove();
749                 self.refresh_zebra(index);
750             },
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));
755             },
756             'add': function (ev, records, record, index) {
757                 var $new_row = $('<tr>').attr({
758                     'data-id': record.get('id')
759                 });
760
761                 if (index === 0) {
762                     $new_row.prependTo(self.$current);
763                 } else {
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);
768                 }
769
770                 self.refresh_zebra(index, 1);
771             }
772         };
773         _(this.record_callbacks).each(function (callback, event) {
774             this.records.bind(event, callback);
775         }, this);
776
777         this.$_element = $('<tbody class="ui-widget-content">')
778             .appendTo(document.body)
779             .delegate('th.oe-record-selector', 'click', function (e) {
780                 e.stopPropagation();
781                 var selection = self.get_selection();
782                 $(self).trigger(
783                         'selected', [selection.ids, selection.records]);
784             })
785             .delegate('td.oe-record-delete button', 'click', function (e) {
786                 e.stopPropagation();
787                 var $row = $(e.target).closest('tr');
788                 $(self).trigger('deleted', [[self.row_id($row)]]);
789             })
790             .delegate('td.oe-field-cell button', 'click', function (e) {
791                 e.stopPropagation();
792                 var $target = $(e.currentTarget),
793                       field = $target.closest('td').data('field'),
794                        $row = $target.closest('tr'),
795                   record_id = self.row_id($row);
796
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));
803                 }]);
804             })
805             .delegate('tr', 'click', function (e) {
806                 e.stopPropagation();
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"
811                     }
812                     self.row_clicked(e);
813                 }
814             });
815     },
816     row_clicked: function () {
817         $(this).trigger(
818             'row_link',
819             [this.dataset.ids[this.dataset.index],
820              this.dataset]);
821     },
822     render_cell: function (record, column) {
823         var value;
824         if(column.type === 'reference') {
825             value = record.get(column.id);
826             var ref_match;
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]);
841                 });
842             }
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
848             // displayable value
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
852                 // row
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]);
857                 });
858             }
859         }
860         return openerp.web.format_cell(record.toForm().data, column);
861     },
862     render: function () {
863         if (this.$current) {
864             this.$current.remove();
865         }
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);
871     },
872     pad_table_to: function (count) {
873         if (this.records.length >= count ||
874                 _(this.columns).any(function(column) { return column.meta; })) {
875             return;
876         }
877         var cells = [];
878         if (this.options.selectable) {
879             cells.push('<th class="oe-record-selector"></td>');
880         }
881         _(this.columns).each(function(column) {
882             if (column.invisible === '1') {
883                 return;
884             }
885             if (column.tag === 'button') {
886                 cells.push('<td class="oe-button" title="' + column.string + '">&nbsp;</td>');
887             } else {
888                 cells.push('<td title="' + column.string + '">&nbsp;</td>');
889             }
890         });
891         if (this.options.deletable) {
892             cells.push('<td class="oe-record-delete"><button type="button" style="visibility: hidden"> </button></td>');
893         }
894         cells.unshift('<tr>');
895         cells.push('</tr>');
896
897         var row = cells.join('');
898         this.$current
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);
902     },
903     /**
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.
906      */
907     get_selection: function () {
908         if (!this.options.selectable) {
909             return [];
910         }
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);
918         });
919         return result;
920     },
921     /**
922      * Returns the identifier of the object displayed in the provided table
923      * row
924      *
925      * @param {Object} row the selected table row
926      * @returns {Number|String} the identifier of the row's object
927      */
928     row_id: function (row) {
929         return $(row).data('id');
930     },
931     /**
932      * Death signal, cleans up list display
933      */
934     on_records_reset: function () {
935         _(this.record_callbacks).each(function (callback, event) {
936             this.records.unbind(event, callback);
937         }, this);
938         if (!this.$current) { return; }
939         this.$current.remove();
940         this.$current = null;
941         this.$_element.remove();
942     },
943     get_records: function () {
944         return this.records.map(function (record) {
945             return {count: 1, values: record.attributes};
946         });
947     },
948     /**
949      * Reloads the provided record by re-reading its content from the server.
950      *
951      * @param {Record} record
952      * @returns {$.Deferred} promise to the finalization of the reloading
953      */
954     reload_record: function (record) {
955         return this.dataset.read_ids(
956             [record.get('id')],
957             _.pluck(_(this.columns).filter(function (r) {
958                     return r.tag === 'field';
959                 }), 'name'),
960             function (records) {
961                 _(records[0]).each(function (value, key) {
962                     record.set(key, value, {silent: true});
963                 });
964                 record.trigger('change', record);
965             }
966         );
967     },
968     /**
969      * Renders a list record to HTML
970      *
971      * @param {Record} record index of the record to render in ``this.rows``
972      * @returns {String} QWeb rendering of the selected record
973      */
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,
979             record: record,
980             row_parity: (index % 2 === 0) ? 'even' : 'odd',
981             view: this.view,
982             render_cell: $.proxy(this, 'render_cell')
983         });
984     },
985     /**
986      * Fixes fixes the even/odd classes
987      *
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
990      */
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);
1002         });
1003     }
1004 });
1005 openerp.web.ListView.Groups = openerp.web.Class.extend( /** @lends openerp.web.ListView.Groups# */{
1006     passtrough_events: 'action deleted row_link',
1007     /**
1008      * Grouped display for the ListView. Handles basic DOM events and interacts
1009      * with the :js:class:`~openerp.web.DataGroup` bound to it.
1010      *
1011      * Provides events similar to those of
1012      * :js:class:`~openerp.web.ListView.List`
1013      *
1014      * @constructs openerp.web.ListView.Groups
1015      * @extends openerp.web.Class
1016      *
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]
1022      */
1023     init: function (view, options) {
1024         options = options || {};
1025         this.view = view;
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;
1030
1031         this.$row = null;
1032         this.children = {};
1033
1034         this.page = 0;
1035
1036         this.records.bind('reset', $.proxy(this, 'on_records_reset'));
1037     },
1038     make_fragment: function () {
1039         return document.createDocumentFragment();
1040     },
1041     /**
1042      * Returns a DOM node after which a new tbody can be inserted, so that it
1043      * follows the provided row.
1044      *
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
1047      * elements
1048      *
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
1051      */
1052     point_insertion: function (row) {
1053         var $row = $(row);
1054         var red_letter_tboday = $row.closest('tbody')[0];
1055
1056         var $next_siblings = $row.nextAll();
1057         if ($next_siblings.length) {
1058             var $root_kanal = $('<tbody>').insertAfter(red_letter_tboday);
1059
1060             $root_kanal.append($next_siblings);
1061             this.elements.splice(
1062                 _.indexOf(this.elements, red_letter_tboday),
1063                 0,
1064                 $root_kanal[0]);
1065         }
1066         return red_letter_tboday;
1067     },
1068     make_paginator: function () {
1069         var self = this;
1070         var $prev = $('<button type="button" data-pager-action="previous">&lt;</button>')
1071             .click(function (e) {
1072                 e.stopPropagation();
1073                 self.page -= 1;
1074
1075                 self.$row.closest('tbody').next()
1076                     .replaceWith(self.render());
1077             });
1078         var $next = $('<button type="button" data-pager-action="next">&gt;</button>')
1079             .click(function (e) {
1080                 e.stopPropagation();
1081                 self.page += 1;
1082
1083                 self.$row.closest('tbody').next()
1084                     .replaceWith(self.render());
1085             });
1086         this.$row.children().last()
1087             .append($prev)
1088             .append('<span class="oe-pager-state"></span>')
1089             .append($next);
1090     },
1091     open: function (point_insertion) {
1092         this.render().insertAfter(point_insertion);
1093         this.make_paginator();
1094     },
1095     close: function () {
1096         this.$row.children().last().empty();
1097         this.records.reset();
1098     },
1099     /**
1100      * Prefixes ``$node`` with floated spaces in order to indent it relative
1101      * to its own left margin/baseline
1102      *
1103      * @param {jQuery} $node jQuery object to indent
1104      * @param {Number} level current nesting level, >= 1
1105      * @returns {jQuery} the indentation node created
1106      */
1107     indent: function ($node, level) {
1108         return $('<span>')
1109                 .css({'float': 'left', 'white-space': 'pre'})
1110                 .text(new Array(level).join('   '))
1111                 .prependTo($node);
1112     },
1113     render_groups: function (datagroups) {
1114         var self = this;
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];
1120             }
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
1125             });
1126             self.bind_child_events(child);
1127             child.datagroup = group;
1128
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));
1138                     } else {
1139                         $row.removeData('open')
1140                             .find('span.ui-icon')
1141                                 .removeClass('ui-icon-triangle-1-s')
1142                                 .addClass('ui-icon-triangle-1-e');
1143                         child.close();
1144                     }
1145                 });
1146             }
1147             placeholder.appendChild($row[0]);
1148
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) {
1152                 var row_data = {};
1153                 row_data[group.grouped_on] = group;
1154                 var group_column = _(self.columns).detect(function (column) {
1155                     return column.id === group.grouped_on; });
1156                 try {
1157                     $group_column.html(openerp.web.format_cell(
1158                         row_data, group_column, _t("Undefined")));
1159                 } catch (e) {
1160                     $group_column.html(row_data[group_column.id].value);
1161                 }
1162                 if (group.openable) {
1163                     // Make openable if not terminal group & group_by_no_leaf
1164                     $group_column
1165                         .prepend('<span class="ui-icon ui-icon-triangle-1-e" style="float: left;">');
1166                 }
1167             }
1168             self.indent($group_column, group.level);
1169             // count column
1170             $('<td>').text(group.length).appendTo($row);
1171
1172             if (self.options.selectable) {
1173                 $row.append('<td>');
1174             }
1175             _(self.columns).chain()
1176                 .filter(function (column) {return !column.invisible;})
1177                 .each(function (column) {
1178                     if (column.meta) {
1179                         // do not do anything
1180                     } else if (column.id in group.aggregates) {
1181                         var value = group.aggregates[column.id];
1182                         var format;
1183                         if (column.type === 'integer') {
1184                             format = "%.0f";
1185                         } else if (column.type === 'float') {
1186                             format = "%.2f";
1187                         }
1188                         $('<td>')
1189                             .text(_.sprintf(format, value))
1190                             .appendTo($row);
1191                     } else {
1192                         $row.append('<td>');
1193                     }
1194                 });
1195             if (self.options.deletable) {
1196                 $row.append('<td class="oe-group-pagination">');
1197             }
1198         });
1199         return placeholder;
1200     },
1201     bind_child_events: function (child) {
1202         var $this = $(this),
1203              self = 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);
1217         });
1218     },
1219     render_dataset: function (dataset) {
1220         var self = this,
1221             list = new openerp.web.ListView.List(this, {
1222                 options: this.options,
1223                 columns: this.columns,
1224                 dataset: dataset,
1225                 records: this.records
1226             });
1227         this.bind_child_events(list);
1228
1229         var view = this.view,
1230            limit = view.limit(),
1231                d = new $.Deferred(),
1232             page = this.datagroup.openable ? this.page : view.page;
1233
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});
1241             }
1242             if (!self.datagroup.openable) {
1243                 view.configure_pager(dataset);
1244             } else {
1245                 var pages = Math.ceil(dataset.ids.length / limit);
1246                 self.$row
1247                     .find('.oe-pager-state')
1248                         .text(_.sprintf('%d/%d', page + 1, pages))
1249                     .end()
1250                     .find('button[data-pager-action=previous]')
1251                         .attr('disabled', page === 0)
1252                     .end()
1253                     .find('button[data-pager-action=next]')
1254                         .attr('disabled', page === pages - 1);
1255             }
1256
1257             self.records.add(records, {silent: true});
1258             list.render();
1259             d.resolve(list);
1260         });}, 0);
1261         return d.promise();
1262     },
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'; })) {
1269             return;
1270         }
1271         // ondrop, move relevant record & fix sequences
1272         list.$current.sortable({
1273             axis: 'y',
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');
1278
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 });
1282
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);
1294                 }
1295
1296                 list.refresh_zebra();
1297             }
1298         });
1299     },
1300     render: function (post_render) {
1301         var self = this;
1302         var $element = $('<tbody>');
1303         this.elements = [$element[0]];
1304
1305         this.datagroup.list(
1306             _(this.view.visible_columns).chain()
1307                 .filter(function (column) { return column.tag === 'field' })
1308                 .pluck('name').value(),
1309             function (groups) {
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;
1316                     self.elements =
1317                         [list.$current.replaceAll($element)[0]];
1318                     self.setup_resequence_rows(list, dataset);
1319                     if (post_render) { post_render(); }
1320                 });
1321             });
1322         return $element;
1323     },
1324     /**
1325      * Returns the ids of all selected records for this group, and the records
1326      * themselves
1327      */
1328     get_selection: function () {
1329         var ids = [], records = [];
1330
1331         _(this.children)
1332             .each(function (child) {
1333                 var selection = child.get_selection();
1334                 ids.push.apply(ids, selection.ids);
1335                 records.push.apply(records, selection.records);
1336             });
1337
1338         return {ids: ids, records: records};
1339     },
1340     on_records_reset: function () {
1341         this.children = {};
1342         $(this.elements).remove();
1343     },
1344     get_records: function () {
1345         if (_(this.children).isEmpty()) {
1346             if (!this.datagroup.length) {
1347                 return;
1348             }
1349             return {
1350                 count: this.datagroup.length,
1351                 values: this.datagroup.aggregates
1352             }
1353         }
1354         return _(this.children).chain()
1355             .map(function (child) {
1356                 return child.get_records();
1357             }).flatten().value();
1358     }
1359 });
1360
1361 /**
1362  * @mixin Events
1363  */
1364 var Events = /** @lends Events# */{
1365     /**
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
1368      * @returns this
1369      */
1370     bind: function (event, handler) {
1371         var calls = this['_callbacks'] || (this._callbacks = {});
1372
1373         if (event in calls) {
1374             calls[event].push(handler);
1375         } else {
1376             calls[event] = [handler];
1377         }
1378         return this;
1379     },
1380     /**
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)
1383      * @returns this
1384      */
1385     unbind: function (event, handler) {
1386         var calls = this._callbacks || {};
1387         if (!(event in calls)) { return this; }
1388         if (!handler) {
1389             delete calls[event];
1390         } else {
1391             var handlers = calls[event];
1392             handlers.splice(
1393                 _(handlers).indexOf(handler),
1394                 1);
1395         }
1396         return this;
1397     },
1398     /**
1399      * @param {String} event
1400      * @returns this
1401      */
1402     trigger: function (event) {
1403         var calls;
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);
1408         }
1409         return this;
1410     }
1411 };
1412 var Record = openerp.web.Class.extend(/** @lends Record# */{
1413     /**
1414      * @constructs Record
1415      * @extends openerp.web.Class
1416      * 
1417      * @mixes Events
1418      * @param {Object} [data]
1419      */
1420     init: function (data) {
1421         this.attributes = data || {};
1422     },
1423     /**
1424      * @param {String} key
1425      * @returns {Object}
1426      */
1427     get: function (key) {
1428         return this.attributes[key];
1429     },
1430     /**
1431      * @param key
1432      * @param value
1433      * @param {Object} [options]
1434      * @param {Boolean} [options.silent=false]
1435      * @returns {Record}
1436      */
1437     set: function (key, value, options) {
1438         options = options || {};
1439         var old_value = this.attributes[key];
1440         if (old_value === value) {
1441             return this;
1442         }
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);
1447         }
1448         return this;
1449     },
1450     /**
1451      * Converts the current record to the format expected by form views:
1452      *
1453      * .. code-block:: javascript
1454      *
1455      *    data: {
1456      *         $fieldname: {
1457      *             value: $value
1458      *         }
1459      *     }
1460      *
1461      *
1462      * @returns {Object} record displayable in a form view
1463      */
1464     toForm: function () {
1465         var form_data = {}, attrs = this.attributes;
1466         for(var k in attrs) {
1467             form_data[k] = {value: attrs[k]};
1468         }
1469
1470         return {data: form_data};
1471     },
1472     /**
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)
1476      */
1477     toContext: function () {
1478         var output = {}, attrs = this.attributes;
1479         for(var k in attrs) {
1480             var val = attrs[k];
1481             if (typeof val !== 'object') {
1482                 output[k] = val;
1483             } else if (val instanceof Array) {
1484                 output[k] = val[0];
1485             } else {
1486                 throw new Error("Can't convert value " + val + " to context");
1487             }
1488         }
1489         return output;
1490     }
1491 });
1492 Record.include(Events);
1493 var Collection = openerp.web.Class.extend(/** @lends Collection# */{
1494     /**
1495      * Smarter collections, with events, very strongly inspired by Backbone's.
1496      *
1497      * Using a "dumb" array of records makes synchronization between the
1498      * various serious 
1499      *
1500      * @constructs Collection
1501      * @extends openerp.web.Class
1502      * 
1503      * @mixes Events
1504      * @param {Array} [records] records to initialize the collection with
1505      * @param {Object} [options]
1506      */
1507     init: function (records, options) {
1508         options = options || {};
1509         _.bindAll(this, '_onRecordEvent');
1510         this.length = 0;
1511         this.records = [];
1512         this._byId = {};
1513         this._proxies = {};
1514         this._key = options.key;
1515         this._parent = options.parent;
1516
1517         if (records) {
1518             this.add(records);
1519         }
1520     },
1521     /**
1522      * @param {Object|Array} record
1523      * @param {Object} [options]
1524      * @param {Number} [options.at]
1525      * @param {Boolean} [options.silent=false]
1526      * @returns this
1527      */
1528     add: function (record, options) {
1529         options = options || {};
1530         var records = record instanceof Array ? record : [record];
1531
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);
1540                 }
1541             } else {
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);
1546                 }
1547             }
1548             this.length++;
1549         }
1550         return this;
1551     },
1552
1553     /**
1554      * Get a record by its index in the collection, can also take a group if
1555      * the collection is not degenerate
1556      *
1557      * @param {Number} index
1558      * @param {String} [group]
1559      * @returns {Record|undefined}
1560      */
1561     at: function (index, group) {
1562         if (group) {
1563             var groups = group.split('.');
1564             return this._proxies[groups[0]].at(index, groups.join('.'));
1565         }
1566         return this.records[index];
1567     },
1568     /**
1569      * Get a record by its database id
1570      *
1571      * @param {Number} id
1572      * @returns {Record|undefined}
1573      */
1574     get: function (id) {
1575         if (!_(this._proxies).isEmpty()) {
1576             var record = null;
1577             _(this._proxies).detect(function (proxy) {
1578                 return record = proxy.get(id);
1579             });
1580             return record;
1581         }
1582         return this._byId[id];
1583     },
1584     /**
1585      * Builds a proxy (insert/retrieve) to a subtree of the collection, by
1586      * the subtree's group
1587      *
1588      * @param {String} section group path section
1589      * @returns {Collection}
1590      */
1591     proxy: function (section) {
1592         return this._proxies[section] = new Collection(null, {
1593             parent: this,
1594             key: section
1595         }).bind(null, this._onRecordEvent);
1596     },
1597     /**
1598      * @param {Array} [records]
1599      * @returns this
1600      */
1601     reset: function (records, options) {
1602         options = options || {};
1603         _(this._proxies).each(function (proxy) {
1604             proxy.reset();
1605         });
1606         this._proxies = {};
1607         this.length = 0;
1608         this.records = [];
1609         this._byId = {};
1610         if (records) {
1611             this.add(records);
1612         }
1613         if (!options.silent) {
1614             this.trigger('reset', this);
1615         }
1616         return this;
1617     },
1618     /**
1619      * Removes the provided record from the collection
1620      *
1621      * @param {Record} record
1622      * @returns this
1623      */
1624     remove: function (record) {
1625         var self = this;
1626         var index = _(this.records).indexOf(record);
1627         if (index === -1) {
1628             _(this._proxies).each(function (proxy) {
1629                 proxy.remove(record);
1630             });
1631             return this;
1632         }
1633
1634         this.records.splice(index, 1);
1635         delete this._byId[record.get('id')];
1636         this.length--;
1637         this.trigger('remove', record, this);
1638         return this;
1639     },
1640
1641     _onRecordEvent: function (event, record, options) {
1642         // don't propagate reset events
1643         if (event === 'reset') { return; }
1644         this.trigger.apply(this, arguments);
1645     },
1646
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);
1652             }
1653         }
1654         for(var i=0; i<this.length; ++i) {
1655             callback(this.records[i]);
1656         }
1657     },
1658     map: function (callback) {
1659         var results = [];
1660         this.each(function (record) {
1661             results.push(callback(record));
1662         });
1663         return results;
1664     },
1665     pluck: function (fieldname) {
1666         return this.map(function (record) {
1667             return record.get(fieldname);
1668         });
1669     },
1670     indexOf: function (record) {
1671         return _(this.records).indexOf(record);
1672     }
1673 });
1674 Collection.include(Events);
1675 openerp.web.list = {
1676     Events: Events,
1677     Record: Record,
1678     Collection: Collection
1679 }
1680 };
1681 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: