split data and dataview
[myslice.git] / plugins / querytable / static / js / querytable.js
1 /**
2  * Description: display a query result in a datatables-powered <table>
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 (function($) {
8
9     var debug=false;
10     debug=true
11     var debug_deep=false;
12 //    debug_deep=true;
13
14     var QueryTable = Plugin.extend({
15
16         init: function(options, element) {
17             this._super(options, element);
18
19             /* Member variables */
20             // in general we expect 2 queries here
21             // query_uuid refers to a single object (typically a slice)
22             // query_all_uuid refers to a list (typically resources or users)
23             // these can return in any order so we keep track of which has been received yet
24             this.received_all_query = false;
25             this.received_query = false;
26
27 //            // We need to remember the active filter for datatables filtering
28 //            this.filters = Array(); 
29
30             // an internal buffer for records that are 'in' and thus need to be checked 
31             this.buffered_records_to_check = [];
32
33             /* XXX Events XXX */
34             // this.$element.on('show.Datatables', this.on_show);
35             this.elmt().on('show', this, this.on_show);
36             // Unbind all events using namespacing
37             // TODO in destructor
38             // $(window).unbind('QueryTable');
39
40             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
41             this.method = query.object;
42
43             // xxx beware that this.key needs to contain a key that all records will have
44             // in general query_all will return well populated records, but query
45             // returns records with only the fields displayed on startup. 
46             this.key = (this.options.id_key);
47             if (! this.key) {
48                 // if not specified by caller, decide from metadata
49                 var keys = manifold.metadata.get_key(this.method);
50                 this.key = (keys && keys.length == 1) ? keys[0] : null;
51             }
52             if (! this.key) messages.warning("querytable.init could not kind valid key");
53
54             if (debug) messages.debug("querytable: key="+this.key);
55
56             /* Setup query and record handlers */
57             this.listen_query(options.query_uuid);
58             this.listen_query(options.query_all_uuid, 'all');
59
60             /* GUI setup and event binding */
61             this.initialize_table();
62         },
63
64         /* PLUGIN EVENTS */
65
66         on_show: function(e) {
67             var self = e.data;
68             self.table.fnAdjustColumnSizing()
69         }, // on_show
70
71         /* GUI EVENTS */
72
73         /* GUI MANIPULATION */
74
75         initialize_table: function() {
76             // compute columns based on columns and hidden_columns
77             this.slick_columns = [];
78             var all_columns = this.options.columns; // .concat(this.options.hidden_columns)
79             // xxx would be helpful to support a column_renamings options arg
80             // for redefining some labels like 'network_hrn' that really are not meaningful
81             for (c in all_columns) {
82                 var column=all_columns[c];
83                 this.slick_columns.push ( {id:column, name:column, field:column, 
84                                            cssClass: "querytable-column-"+column,
85                                            width:100, minWidth:40, });
86             }
87
88             // xxx should be extensible from caller with this.options.slickgrid_options 
89             this.slick_options = {
90                 enableCellNavigation: false,
91                 enableColumnReorder: true,
92             };
93
94             this.slick_data = [];
95             this.slick_dataview = new Slick.Data.DataView();
96             var self=this;
97             this.slick_dataview.onRowCountChanged.subscribe ( function (e,args) {
98                 self.slick_grid.updateRowCount();
99                 self.slick_grid.autosizeColumns();
100                 self.slick_grid.render();
101             });
102             
103             var selector="#grid-"+this.options.domid;
104             if (debug_deep) {
105                 messages.debug("slick grid selector is " + selector);
106                 for (c in this.slick_columns) {
107                     var col=this.slick_columns[c];
108                     var msg="";
109                     for (k in col) msg = msg+" col["+k+"]="+col[k];
110                     messages.debug("slick_column["+c+"]:"+msg);
111                 }
112             }
113             // add a checkbox column
114             var checkbox_selector = new Slick.CheckboxSelectColumn({
115                 cssClass: "slick-cell-checkboxsel"
116             });
117             this.slick_columns.push(checkbox_selector.getColumnDefinition());
118             this.slick_grid = new Slick.Grid(selector, this.slick_dataview, this.slick_columns, this.slick_options);
119             this.slick_grid.setSelectionModel (new Slick.RowSelectionModel ({selectActiveRow: false}));
120             this.slick_grid.registerPlugin (checkbox_selector);
121             // autotooltips: for showing the full column name when ellipsed
122             var auto_tooltips = new Slick.AutoTooltips ({ enableForHeaderCells: true });
123             this.slick_grid.registerPlugin (auto_tooltips);
124             
125             this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
126
127         }, // initialize_table
128
129         // Determine index of key in the table columns 
130         getColIndex: function(key, cols) {
131             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
132             return (tabIndex.length > 0) ? tabIndex[0] : -1;
133         }, // getColIndex
134
135         checkbox_html : function (key, value) {
136             if (debug_deep) messages.debug("checkbox_html, value="+value);
137             var result="";
138             // Prefix id with plugin_uuid
139             result += "<input";
140             result += " class='querytable-checkbox'";
141             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
142             result += " name='" + key + "'";
143             result += " type='checkbox'";
144             result += " autocomplete='off'";
145             if (value === undefined) {
146                 messages.warning("querytable.checkbox_html - undefined value");
147             } else {
148                 result += " value='" + value + "'";
149             }
150             result += "></input>";
151             return result;
152         }, 
153
154         new_record: function(record) {
155             // xxx having a field named 'id' is a requirement from dataview
156             record['id']=record[this.key];
157             this.slick_data.push(record);
158         },
159
160         clear_table: function() {
161             console.log("clear_table not implemented");
162         },
163
164         redraw_table: function() {
165             this.table.fnDraw();
166         },
167
168         show_column: function(field) {
169             var oSettings = this.table.fnSettings();
170             var cols = oSettings.aoColumns;
171             var index = this.getColIndex(field,cols);
172             if (index != -1)
173                 this.table.fnSetColumnVis(index, true);
174         },
175
176         hide_column: function(field) {
177             console.log("hide_column not implemented - field="+field);
178         },
179
180         set_checkbox: function(record, checked) {
181             console.log("set_checkbox not yet implemented with slickgrid");
182             return;
183             /* Default: checked = true */
184             if (checked === undefined) checked = true;
185
186             var id;
187             /* The function accepts both records and their key */
188             switch (manifold.get_type(record)) {
189             case TYPE_VALUE:
190                 id = record;
191                 break;
192             case TYPE_RECORD:
193                 /* XXX Test the key before ? */
194                 id = record[this.key];
195                 break;
196             default:
197                 throw "Not implemented";
198                 break;
199             }
200
201
202             if (id === undefined) {
203                 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
204                 return;
205             }
206             var checkbox_id = this.flat_id(this.id('checkbox', id));
207             // function escape_id(myid) is defined in portal/static/js/common.functions.js
208             checkbox_id = escape_id(checkbox_id);
209             // using dataTables's $ to search also in nodes that are not currently displayed
210             var element = this.table.$(checkbox_id);
211             if (debug_deep) 
212                 messages.debug("set_checkbox checked=" + checked
213                                + " id=" + checkbox_id + " matches=" + element.length);
214             element.attr('checked', checked);
215         },
216
217         /*************************** QUERY HANDLER ****************************/
218
219         on_filter_added: function(filter) {
220             this.filters.push(filter);
221             this.redraw_table();
222         },
223
224         on_filter_removed: function(filter) {
225             // Remove corresponding filters
226             this.filters = $.grep(this.filters, function(x) {
227                 return x != filter;
228             });
229             this.redraw_table();
230         },
231         
232         on_filter_clear: function() {
233             this.redraw_table();
234         },
235
236         on_field_added: function(field) {
237             this.show_column(field);
238         },
239
240         on_field_removed: function(field) {
241             this.hide_column(field);
242         },
243
244         on_field_clear: function() {
245             alert('QueryTable::clear_fields() not implemented');
246         },
247
248         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
249         /*************************** ALL QUERY HANDLER ****************************/
250
251         on_all_filter_added: function(filter) {
252             // XXX
253             this.redraw_table();
254         },
255
256         on_all_filter_removed: function(filter) {
257             // XXX
258             this.redraw_table();
259         },
260         
261         on_all_filter_clear: function() {
262             // XXX
263             this.redraw_table();
264         },
265
266         on_all_field_added: function(field) {
267             this.show_column(field);
268         },
269
270         on_all_field_removed: function(field) {
271             this.hide_column(field);
272         },
273
274         on_all_field_clear: function() {
275             alert('QueryTable::clear_fields() not implemented');
276         },
277
278
279         /*************************** RECORD HANDLER ***************************/
280
281         on_new_record: function(record) {
282             if (this.received_all_query) {
283                 // if the 'all' query has been dealt with already we may turn on the checkbox
284                 this.set_checkbox(record, true);
285             } else {
286                 // otherwise we need to remember that and do it later on
287                 if (debug) messages.debug("Remembering record to check " + record[this.key]);
288                 this.buffered_records_to_check.push(record);
289             }
290         },
291
292         on_clear_records: function() {
293         },
294
295         // Could be the default in parent
296         on_query_in_progress: function() {
297             this.spin();
298         },
299
300         on_query_done: function() {
301             this.received_query = true;
302             // unspin once we have received both
303             if (this.received_all_query && this.received_query) this.unspin();
304         },
305         
306         on_field_state_changed: function(data) {
307             switch(data.request) {
308                 case FIELD_REQUEST_ADD:
309                 case FIELD_REQUEST_ADD_RESET:
310                     this.set_checkbox(data.value, true);
311                     break;
312                 case FIELD_REQUEST_REMOVE:
313                 case FIELD_REQUEST_REMOVE_RESET:
314                     this.set_checkbox(data.value, false);
315                     break;
316                 default:
317                     break;
318             }
319         },
320
321         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
322         // all
323         on_all_field_state_changed: function(data) {
324             switch(data.request) {
325                 case FIELD_REQUEST_ADD:
326                 case FIELD_REQUEST_ADD_RESET:
327                     this.set_checkbox(data.value, true);
328                     break;
329                 case FIELD_REQUEST_REMOVE:
330                 case FIELD_REQUEST_REMOVE_RESET:
331                     this.set_checkbox(data.value, false);
332                     break;
333                 default:
334                     break;
335             }
336         },
337
338         on_all_new_record: function(record) {
339             this.new_record(record);
340         },
341
342         on_all_clear_records: function() {
343             this.clear_table();
344
345         },
346
347         on_all_query_in_progress: function() {
348             // XXX parent
349             this.spin();
350         }, // on_all_query_in_progress
351
352         on_all_query_done: function() {
353             if (debug) messages.debug("1-shot initializing dataTables content with " + this.slick_data.length + " lines");
354             var start=new Date();
355             this.slick_dataview.setItems (this.slick_data);
356             var duration=new Date()-start;
357             if (debug) messages.debug("setItems " + duration + " ms");
358             if (debug_deep) {
359                 // show full contents of first row app
360                 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
361             }
362             
363             var self = this;
364             // if we've already received the slice query, we have not been able to set 
365             // checkboxes on the fly at that time (dom not yet created)
366             $.each(this.buffered_records_to_check, function(i, record) {
367                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
368                 self.set_checkbox(record, true);
369             });
370             this.buffered_records_to_check = [];
371
372             this.received_all_query = true;
373             // unspin once we have received both
374             if (this.received_all_query && this.received_query) this.unspin();
375
376         }, // on_all_query_done
377
378         /************************** PRIVATE METHODS ***************************/
379
380         /** 
381          * @brief QueryTable filtering function
382          */
383         _querytable_filter: function(oSettings, aData, iDataIndex) {
384             var ret = true;
385             $.each (this.filters, function(index, filter) { 
386                 /* XXX How to manage checkbox ? */
387                 var key = filter[0]; 
388                 var op = filter[1];
389                 var value = filter[2];
390
391                 /* Determine index of key in the table columns */
392                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
393
394                 /* Unknown key: no filtering */
395                 if (typeof(col) == 'undefined')
396                     return;
397
398                 col_value=unfold.get_value(aData[col]);
399                 /* Test whether current filter is compatible with the column */
400                 if (op == '=' || op == '==') {
401                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
402                         ret = false;
403                 }else if (op == '!=') {
404                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
405                         ret = false;
406                 } else if(op=='<') {
407                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
408                         ret = false;
409                 } else if(op=='>') {
410                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
411                         ret = false;
412                 } else if(op=='<=' || op=='≤') {
413                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
414                         ret = false;
415                 } else if(op=='>=' || op=='≥') {
416                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
417                         ret = false;
418                 }else{
419                     // How to break out of a loop ?
420                     alert("filter not supported");
421                     return false;
422                 }
423
424             });
425             return ret;
426         },
427
428         _querytable_draw_callback: function() {
429             /* 
430              * Handle clicks on checkboxes: reassociate checkbox click every time
431              * the table is redrawn 
432              */
433             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
434
435             if (!this.table)
436                 return;
437
438             /* Remove pagination if we show only a few results */
439             var wrapper = this.table; //.parent().parent().parent();
440             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
441             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
442             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
443
444             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
445                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
446             } else {
447                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
448             }
449
450             if ( rowsToShow <= minRowsPerPage ) {
451                 $('.querytable_length', wrapper).css('visibility', 'hidden');
452             } else {
453                 $('.querytable_length', wrapper).css('visibility', 'visible');
454             }
455         },
456
457         _check_click: function(e) {
458             e.stopPropagation();
459
460             var self = e.data;
461
462             // XXX this.value = key of object to be added... what about multiple keys ?
463             if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
464             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
465             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
466             
467         },
468
469         _selectAll: function() {
470             // requires jQuery id
471             var uuid=this.id.split("-");
472             var oTable=$("#querytable-"+uuid[1]).dataTable();
473             // Function available in QueryTable 1.9.x
474             // Filter : displayed data only
475             var filterData = oTable._('tr', {"filter":"applied"});   
476             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
477             if(filterData.length<=100){
478                 $.each(filterData, function(index, obj) {
479                     var last=$(obj).last();
480                     var key_value=unfold.get_value(last[0]);
481                     if(typeof($(last[0]).attr('checked'))=="undefined"){
482                         $.publish('selected', 'add/'+key_value);
483                     }
484                 });
485             }
486         },
487
488     });
489
490     $.plugin('QueryTable', QueryTable);
491
492 //  /* define the 'dom-checkbox' type for sorting in datatables 
493 //     http://datatables.net/examples/plug-ins/dom_sort.html
494 //     using trial and error I found that the actual column number
495 //     was in fact given as a third argument, and not second 
496 //     as the various online resources had it - go figure */
497 //    $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
498 //      return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
499 //          return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
500 //      } );
501 //    }
502
503 })(jQuery);
504