Merge branch 'master' of ssh://git.onelab.eu/git/myslice
[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
12     var QueryTable = Plugin.extend({
13
14         init: function(options, element) 
15         {
16             this._super(options, element);
17
18             /* Member variables */
19             // in general we expect 2 queries here
20             // query_uuid refers to a single object (typically a slice)
21             // query_all_uuid refers to a list (typically resources or users)
22             // these can return in any order so we keep track of which has been received yet
23             this.received_all_query = false;
24             this.received_query = false;
25
26             // We need to remember the active filter for datatables filtering
27             this.filters = Array(); 
28
29             // an internal buffer for records that are 'in' and thus need to be checked 
30             this.buffered_records_to_check = [];
31             // an internal buffer for keeping lines and display them in one call to fnAddData
32             this.buffered_lines = [];
33
34             /* XXX Events XXX */
35             // this.$element.on('show.Datatables', this.on_show);
36             this.elmt().on('show', this, this.on_show);
37             // Unbind all events using namespacing
38             // TODO in destructor
39             // $(window).unbind('QueryTable');
40
41             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
42             this.object = query.object;
43
44             // xxx beware that this.key needs to contain a key that all records will have
45             // in general query_all will return well populated records, but query
46             // returns records with only the fields displayed on startup. 
47             this.key = (this.options.id_key);
48             if (typeof(this.key)=='undefined' || (this.key).startsWith("unknown")) {
49                     // if not specified by caller, decide from metadata
50                     var keys = manifold.metadata.get_key(this.object);
51                     this.key = (keys && keys.length == 1) ? keys[0] : null;
52             }
53             if (! this.key) messages.warning("querytable.init could not kind valid key");
54             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         {
68             var self = e.data;
69
70             self.table.fnAdjustColumnSizing()
71         
72             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
73             /* temp disabled... useful ? -- jordan
74             $(this).each(function(i,elt) {
75                 if (jQuery(elt).hasClass('dataTables')) {
76                     var myDiv=jQuery('#querytable-' + this.id).parent();
77                     if(myDiv.height()==0) {
78                         var oTable=$('#querytable-' + this.id).dataTable();            
79                         oTable.fnDraw();
80                     }
81                 }
82             });
83             */
84         }, // on_show
85
86         /* GUI EVENTS */
87
88         /* GUI MANIPULATION */
89
90         initialize_table: function() 
91         {
92             /* Transforms the table into DataTable, and keep a pointer to it */
93             var self = this;
94             var actual_options = {
95                 // Customize the position of Datatables elements (length,filter,button,...)
96                 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
97                 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
98                 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
99                 // hopefully this would come with dataTables v1.10 ?
100                 // in any case, search for 'sPaginationType' all over the code for more comments
101                 sPaginationType: 'bootstrap',
102                 // Handle the null values & the error : Datatables warning Requested unknown parameter
103                 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
104                 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
105                 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
106                 // sScrollX: '100%',       /* Horizontal scrolling */
107                 bProcessing: true,      /* Loading */
108                 fnDrawCallback: function() { self._querytable_draw_callback.call(self); }
109                 // XXX use $.proxy here !
110             };
111             // the intention here is that options.datatables_options as coming from the python object take precedence
112             // xxx DISABLED by jordan: was causing errors in datatables.js
113             // xxx turned back on by Thierry - this is the code that takes python-provided options into account
114             // check your datatables_options tag instead 
115             // however, we have to accumulate in aoColumnDefs from here (above) 
116             // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
117             if ( 'aoColumnDefs' in this.options.datatables_options) {
118                 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
119                 delete this.options.datatables_options['aoColumnDefs'];
120             }
121             $.extend(actual_options, this.options.datatables_options );
122             this.table = this.elmt('table').dataTable(actual_options);
123
124             /* Setup the SelectAll button in the dataTable header */
125             /* xxx not sure this is still working */
126             var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
127             oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
128             oSelectAll.button();
129             oSelectAll.css('font-size','11px');
130             oSelectAll.css('float','right');
131             oSelectAll.css('margin-right','15px');
132             oSelectAll.css('margin-bottom','5px');
133             oSelectAll.unbind('click');
134             oSelectAll.click(this._selectAll);
135
136             /* Add a filtering function to the current table 
137              * Note: we use closure to get access to the 'options'
138              */
139             $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
140                 /* No filtering if the table does not match */
141                 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
142                     return true;
143                 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
144             });
145
146             /* Processing hidden_columns */
147             $.each(this.options.hidden_columns, function(i, field) {
148                 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
149                 self.hide_column(field);
150             });
151         }, // initialize_table
152
153         /**
154          * @brief Determine index of key in the table columns 
155          * @param key
156          * @param cols
157          */
158         getColIndex: function(key, cols) {
159             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
160             return (tabIndex.length > 0) ? tabIndex[0] : -1;
161         }, // getColIndex
162
163         checkbox_html : function (key, value)
164         {
165 //          if (debug) messages.debug("checkbox_html, value="+value);
166             var result="";
167             // Prefix id with plugin_uuid
168             result += "<input";
169             result += " class='querytable-checkbox'";
170             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
171             result += " name='" + key + "'";
172             result += " type='checkbox'";
173             result += " autocomplete='off'";
174             if (value === undefined) {
175                 messages.warning("querytable.checkbox_html - undefined value");
176             } else {
177                 result += " value='" + value + "'";
178             }
179             result += "></input>";
180             return result;
181         }, 
182
183
184         new_record: function(record)
185         {
186             // this models a line in dataTables, each element in the line describes a cell
187             line = new Array();
188      
189             // go through table headers to get column names we want
190             // in order (we have temporarily hack some adjustments in names)
191             var cols = this.table.fnSettings().aoColumns;
192             var colnames = cols.map(function(x) {return x.sTitle})
193             var nb_col = cols.length;
194             /* if we've requested checkboxes, then forget about the checkbox column for now */
195             if (this.options.checkboxes) nb_col -= 1;
196
197             /* fill in stuff depending on the column name */
198             for (var j = 0; j < nb_col; j++) {
199                 if (typeof colnames[j] == 'undefined') {
200                     line.push('...');
201                 } else if (colnames[j] == 'hostname') {
202                     if (record['type'] == 'resource,link')
203                         //TODO: we need to add source/destination for links
204                         line.push('');
205                     else
206                         line.push(record['hostname']);
207
208                 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
209                     line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
210                 } else {
211                     if (record[colnames[j]])
212                         line.push(record[colnames[j]]);
213                     else
214                         line.push('');
215                 }
216             }
217     
218             // catch up with the last column if checkboxes were requested 
219             if (this.options.checkboxes) {
220                 // Use a key instead of hostname (hard coded...)
221                 line.push(this.checkbox_html(this.key, record[this.key]));
222                 }
223     
224             // adding an array in one call is *much* more efficient
225                 // this.table.fnAddData(line);
226                 this.buffered_lines.push(line);
227         },
228
229         clear_table: function()
230         {
231             this.table.fnClearTable();
232         },
233
234         redraw_table: function()
235         {
236             this.table.fnDraw();
237         },
238
239         show_column: function(field)
240         {
241             var oSettings = this.table.fnSettings();
242             var cols = oSettings.aoColumns;
243             var index = this.getColIndex(field,cols);
244             if (index != -1)
245                 this.table.fnSetColumnVis(index, true);
246         },
247
248         hide_column: function(field)
249         {
250             var oSettings = this.table.fnSettings();
251             var cols = oSettings.aoColumns;
252             var index = this.getColIndex(field,cols);
253             if (index != -1)
254                 this.table.fnSetColumnVis(index, false);
255         },
256
257         set_checkbox: function(record, checked)
258         {
259             /* Default: checked = true */
260             if (checked === undefined) checked = true;
261
262             var id;
263             /* The function accepts both records and their key */
264             switch (manifold.get_type(record)) {
265             case TYPE_VALUE:
266                 id = record;
267                 break;
268             case TYPE_RECORD:
269                 /* XXX Test the key before ? */
270                 id = record[this.key];
271                 break;
272             default:
273                 throw "Not implemented";
274                 break;
275             }
276
277
278                 if (id === undefined) {
279                         messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
280                         return;
281                 }
282             // PB TO CHECK THE RIGHT CHECKBOXES IS HERE... flat_id using \ in the key
283             // need to use escape_id when creating the id of the checkboxes
284             var checkbox_id = this.flat_id(this.id('checkbox', id));
285             // function escape_id(myid) is defined in portal/static/js/common.functions.js
286             checkbox_id = escape_id(checkbox_id);
287             // As we are using [id="x"] syntax, we need to remove the # in the checkbox_id
288             checkbox_id = checkbox_id.replace("#","");
289             // using dataTables's $ to search also in nodes that are not currently displayed
290             var element = this.table.$('[id="' + checkbox_id + '"]');
291             if (debug) 
292                 messages.debug("set_checkbox checked=" + checked
293                                + " id=" + checkbox_id + " matches=" + element.length);
294             element.attr('checked', checked);
295         },
296
297         /*************************** QUERY HANDLER ****************************/
298
299         on_filter_added: function(filter)
300         {
301             this.filters.push(filter);
302             this.redraw_table();
303         },
304
305         on_filter_removed: function(filter)
306         {
307             // Remove corresponding filters
308             this.filters = $.grep(this.filters, function(x) {
309                 return x != filter;
310             });
311             this.redraw_table();
312         },
313         
314         on_filter_clear: function()
315         {
316             // XXX
317             this.redraw_table();
318         },
319
320         on_field_added: function(field)
321         {
322             this.show_column(field);
323         },
324
325         on_field_removed: function(field)
326         {
327             this.hide_column(field);
328         },
329
330         on_field_clear: function()
331         {
332             alert('QueryTable::clear_fields() not implemented');
333         },
334
335         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
336         /*************************** ALL QUERY HANDLER ****************************/
337
338         on_all_filter_added: function(filter)
339         {
340             // XXX
341             this.redraw_table();
342         },
343
344         on_all_filter_removed: function(filter)
345         {
346             // XXX
347             this.redraw_table();
348         },
349         
350         on_all_filter_clear: function()
351         {
352             // XXX
353             this.redraw_table();
354         },
355
356         on_all_field_added: function(field)
357         {
358             this.show_column(field);
359         },
360
361         on_all_field_removed: function(field)
362         {
363             this.hide_column(field);
364         },
365
366         on_all_field_clear: function()
367         {
368             alert('QueryTable::clear_fields() not implemented');
369         },
370
371
372         /*************************** RECORD HANDLER ***************************/
373
374         on_new_record: function(record)
375         {
376             if (this.received_all_query) {
377                 // if the 'all' query has been dealt with already we may turn on the checkbox
378                 this.set_checkbox(record, true);
379             } else {
380                 // otherwise we need to remember that and do it later on
381                 if (debug) messages.debug("Remembering record to check " + record[this.key]);
382                 this.buffered_records_to_check.push(record);
383             }
384         },
385
386         on_clear_records: function()
387         {
388         },
389
390         // Could be the default in parent
391         on_query_in_progress: function()
392         {
393             this.spin();
394         },
395
396         on_query_done: function()
397         {
398             this.received_query = true;
399             // unspin once we have received both
400             if (this.received_all_query && this.received_query) this.unspin();
401         },
402         
403         on_field_state_changed: function(data)
404         {
405             switch(data.request) {
406                 case FIELD_REQUEST_ADD:
407                 case FIELD_REQUEST_ADD_RESET:
408                     this.set_checkbox(data.value, true);
409                     break;
410                 case FIELD_REQUEST_REMOVE:
411                 case FIELD_REQUEST_REMOVE_RESET:
412                     this.set_checkbox(data.value, false);
413                     break;
414                 default:
415                     break;
416             }
417         },
418
419         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
420         // all
421         on_all_field_state_changed: function(data)
422         {
423             switch(data.request) {
424                 case FIELD_REQUEST_ADD:
425                 case FIELD_REQUEST_ADD_RESET:
426                     this.set_checkbox(data.value, true);
427                     break;
428                 case FIELD_REQUEST_REMOVE:
429                 case FIELD_REQUEST_REMOVE_RESET:
430                     this.set_checkbox(data.value, false);
431                     break;
432                 default:
433                     break;
434             }
435         },
436
437         on_all_new_record: function(record)
438         {
439             this.new_record(record);
440         },
441
442         on_all_clear_records: function()
443         {
444             this.clear_table();
445
446         },
447
448         on_all_query_in_progress: function()
449         {
450             // XXX parent
451             this.spin();
452         }, // on_all_query_in_progress
453
454         on_all_query_done: function()
455         {
456             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
457             this.table.fnAddData (this.buffered_lines);
458             this.buffered_lines=[];
459             
460             var self = this;
461             // if we've already received the slice query, we have not been able to set 
462             // checkboxes on the fly at that time (dom not yet created)
463             $.each(this.buffered_records_to_check, function(i, record) {
464                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
465                 self.set_checkbox(record, true);
466             });
467             this.buffered_records_to_check = [];
468
469             this.received_all_query = true;
470             // unspin once we have received both
471             if (this.received_all_query && this.received_query) this.unspin();
472
473         }, // on_all_query_done
474
475         /************************** PRIVATE METHODS ***************************/
476
477         /** 
478          * @brief QueryTable filtering function
479          */
480         _querytable_filter: function(oSettings, aData, iDataIndex)
481         {
482             var ret = true;
483             $.each (this.filters, function(index, filter) { 
484                 /* XXX How to manage checkbox ? */
485                 var key = filter[0]; 
486                 var op = filter[1];
487                 var value = filter[2];
488
489                 /* Determine index of key in the table columns */
490                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
491
492                 /* Unknown key: no filtering */
493                 if (typeof(col) == 'undefined')
494                     return;
495
496                 col_value=unfold.get_value(aData[col]);
497                 /* Test whether current filter is compatible with the column */
498                 if (op == '=' || op == '==') {
499                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
500                         ret = false;
501                 }else if (op == '!=') {
502                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
503                         ret = false;
504                 } else if(op=='<') {
505                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
506                         ret = false;
507                 } else if(op=='>') {
508                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
509                         ret = false;
510                 } else if(op=='<=' || op=='≤') {
511                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
512                         ret = false;
513                 } else if(op=='>=' || op=='≥') {
514                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
515                         ret = false;
516                 }else{
517                     // How to break out of a loop ?
518                     alert("filter not supported");
519                     return false;
520                 }
521
522             });
523             return ret;
524         },
525
526         _querytable_draw_callback: function()
527         {
528             /* 
529              * Handle clicks on checkboxes: reassociate checkbox click every time
530              * the table is redrawn 
531              */
532             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
533
534             if (!this.table)
535                 return;
536
537             /* Remove pagination if we show only a few results */
538             var wrapper = this.table; //.parent().parent().parent();
539             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
540             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
541             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
542
543             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
544                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
545             } else {
546                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
547             }
548
549             if ( rowsToShow <= minRowsPerPage ) {
550                 $('.querytable_length', wrapper).css('visibility', 'hidden');
551             } else {
552                 $('.querytable_length', wrapper).css('visibility', 'visible');
553             }
554         },
555
556         _check_click: function(e) 
557         {
558             e.stopPropagation();
559
560             var self = e.data;
561
562             // XXX this.value = key of object to be added... what about multiple keys ?
563             if (debug) messages.debug("querytable click handler checked=" + this.checked + " "+this.key+"=" + this.value);
564             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
565             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
566             
567         },
568
569         _selectAll: function() 
570         {
571             // requires jQuery id
572             var uuid=this.id.split("-");
573             var oTable=$("#querytable-"+uuid[1]).dataTable();
574             // Function available in QueryTable 1.9.x
575             // Filter : displayed data only
576             var filterData = oTable._('tr', {"filter":"applied"});   
577             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
578             if(filterData.length<=100){
579                 $.each(filterData, function(index, obj) {
580                     var last=$(obj).last();
581                     var key_value=unfold.get_value(last[0]);
582                     if(typeof($(last[0]).attr('checked'))=="undefined"){
583                         $.publish('selected', 'add/'+key_value);
584                     }
585                 });
586             }
587         },
588
589     });
590
591     $.plugin('QueryTable', QueryTable);
592
593   /* define the 'dom-checkbox' type for sorting in datatables 
594      http://datatables.net/examples/plug-ins/dom_sort.html
595      using trial and error I found that the actual column number
596      was in fact given as a third argument, and not second 
597      as the various online resources had it - go figure */
598     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
599         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
600             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
601         } );
602     }
603
604 })(jQuery);
605