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