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