Merge branch 'master' into scheduler
[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.method = query.object;
43
44             var keys = manifold.metadata.get_key(this.method);
45             this.key = (keys && keys.length == 1) ? keys[0] : null;
46
47             // xxx temporary hack
48             // as of nov. 28 2013 we have here this.key='urn', but in any place where
49             // the code tries to access record[this.key] the records only have
50             // keys=type,hrn,network_hrn,hostname
51             // so for now we force using hrn instead
52             // as soon as record have their primary key set this line can be removed
53             // see also same hack in googlemap
54             this.key= (this.key == 'urn') ? 'hrn' : 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             var checkbox_id = this.flat_id(this.id('checkbox', id));
283             // function escape_id(myid) is defined in portal/static/js/common.functions.js
284             checkbox_id = escape_id(checkbox_id);
285             // using dataTables's $ to search also in nodes that are not currently displayed
286             var element = this.table.$(checkbox_id);
287             if (debug) 
288                 messages.debug("set_checkbox checked=" + checked
289                                + " id=" + checkbox_id + " matches=" + element.length);
290             element.attr('checked', checked);
291         },
292
293         /*************************** QUERY HANDLER ****************************/
294
295         on_filter_added: function(filter)
296         {
297             this.filters.push(filter);
298             this.redraw_table();
299         },
300
301         on_filter_removed: function(filter)
302         {
303             // Remove corresponding filters
304             this.filters = $.grep(this.filters, function(x) {
305                 return x != filter;
306             });
307             this.redraw_table();
308         },
309         
310         on_filter_clear: function()
311         {
312             // XXX
313             this.redraw_table();
314         },
315
316         on_field_added: function(field)
317         {
318             this.show_column(field);
319         },
320
321         on_field_removed: function(field)
322         {
323             this.hide_column(field);
324         },
325
326         on_field_clear: function()
327         {
328             alert('QueryTable::clear_fields() not implemented');
329         },
330
331         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
332         /*************************** ALL QUERY HANDLER ****************************/
333
334         on_all_filter_added: function(filter)
335         {
336             // XXX
337             this.redraw_table();
338         },
339
340         on_all_filter_removed: function(filter)
341         {
342             // XXX
343             this.redraw_table();
344         },
345         
346         on_all_filter_clear: function()
347         {
348             // XXX
349             this.redraw_table();
350         },
351
352         on_all_field_added: function(field)
353         {
354             this.show_column(field);
355         },
356
357         on_all_field_removed: function(field)
358         {
359             this.hide_column(field);
360         },
361
362         on_all_field_clear: function()
363         {
364             alert('QueryTable::clear_fields() not implemented');
365         },
366
367
368         /*************************** RECORD HANDLER ***************************/
369
370         on_new_record: function(record)
371         {
372             if (this.received_all_query) {
373                 // if the 'all' query has been dealt with already we may turn on the checkbox
374                 this.set_checkbox(record, true);
375             } else {
376                 // otherwise we need to remember that and do it later on
377                 if (debug) messages.debug("Remembering record to check " + record[this.key]);
378                 this.buffered_records_to_check.push(record);
379             }
380         },
381
382         on_clear_records: function()
383         {
384         },
385
386         // Could be the default in parent
387         on_query_in_progress: function()
388         {
389             this.spin();
390         },
391
392         on_query_done: function()
393         {
394             this.received_query = true;
395             // unspin once we have received both
396             if (this.received_all_query && this.received_query) this.unspin();
397         },
398         
399         on_field_state_changed: function(data)
400         {
401             switch(data.request) {
402                 case FIELD_REQUEST_ADD:
403                 case FIELD_REQUEST_ADD_RESET:
404                     this.set_checkbox(data.value, true);
405                     break;
406                 case FIELD_REQUEST_REMOVE:
407                 case FIELD_REQUEST_REMOVE_RESET:
408                     this.set_checkbox(data.value, false);
409                     break;
410                 default:
411                     break;
412             }
413         },
414
415         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
416         // all
417         on_all_field_state_changed: function(data)
418         {
419             switch(data.request) {
420                 case FIELD_REQUEST_ADD:
421                 case FIELD_REQUEST_ADD_RESET:
422                     this.set_checkbox(data.value, true);
423                     break;
424                 case FIELD_REQUEST_REMOVE:
425                 case FIELD_REQUEST_REMOVE_RESET:
426                     this.set_checkbox(data.value, false);
427                     break;
428                 default:
429                     break;
430             }
431         },
432
433         on_all_new_record: function(record)
434         {
435             this.new_record(record);
436         },
437
438         on_all_clear_records: function()
439         {
440             this.clear_table();
441
442         },
443
444         on_all_query_in_progress: function()
445         {
446             // XXX parent
447             this.spin();
448         }, // on_all_query_in_progress
449
450         on_all_query_done: function()
451         {
452             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
453             this.table.fnAddData (this.buffered_lines);
454             this.buffered_lines=[];
455             
456             var self = this;
457             // if we've already received the slice query, we have not been able to set 
458             // checkboxes on the fly at that time (dom not yet created)
459             $.each(this.buffered_records_to_check, function(i, record) {
460                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
461                 self.set_checkbox(record, true);
462             });
463             this.buffered_records_to_check = [];
464
465             this.received_all_query = true;
466             // unspin once we have received both
467             if (this.received_all_query && this.received_query) this.unspin();
468
469         }, // on_all_query_done
470
471         /************************** PRIVATE METHODS ***************************/
472
473         /** 
474          * @brief QueryTable filtering function
475          */
476         _querytable_filter: function(oSettings, aData, iDataIndex)
477         {
478             var ret = true;
479             $.each (this.filters, function(index, filter) { 
480                 /* XXX How to manage checkbox ? */
481                 var key = filter[0]; 
482                 var op = filter[1];
483                 var value = filter[2];
484
485                 /* Determine index of key in the table columns */
486                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
487
488                 /* Unknown key: no filtering */
489                 if (typeof(col) == 'undefined')
490                     return;
491
492                 col_value=unfold.get_value(aData[col]);
493                 /* Test whether current filter is compatible with the column */
494                 if (op == '=' || op == '==') {
495                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
496                         ret = false;
497                 }else if (op == '!=') {
498                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
499                         ret = false;
500                 } else if(op=='<') {
501                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
502                         ret = false;
503                 } else if(op=='>') {
504                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
505                         ret = false;
506                 } else if(op=='<=' || op=='≤') {
507                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
508                         ret = false;
509                 } else if(op=='>=' || op=='≥') {
510                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
511                         ret = false;
512                 }else{
513                     // How to break out of a loop ?
514                     alert("filter not supported");
515                     return false;
516                 }
517
518             });
519             return ret;
520         },
521
522         _querytable_draw_callback: function()
523         {
524             /* 
525              * Handle clicks on checkboxes: reassociate checkbox click every time
526              * the table is redrawn 
527              */
528             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
529
530             if (!this.table)
531                 return;
532
533             /* Remove pagination if we show only a few results */
534             var wrapper = this.table; //.parent().parent().parent();
535             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
536             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
537             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
538
539             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
540                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
541             } else {
542                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
543             }
544
545             if ( rowsToShow <= minRowsPerPage ) {
546                 $('.querytable_length', wrapper).css('visibility', 'hidden');
547             } else {
548                 $('.querytable_length', wrapper).css('visibility', 'visible');
549             }
550         },
551
552         _check_click: function(e) 
553         {
554             e.stopPropagation();
555
556             var self = e.data;
557
558             // XXX this.value = key of object to be added... what about multiple keys ?
559             if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
560             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
561             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
562             
563         },
564
565         _selectAll: function() 
566         {
567             // requires jQuery id
568             var uuid=this.id.split("-");
569             var oTable=$("#querytable-"+uuid[1]).dataTable();
570             // Function available in QueryTable 1.9.x
571             // Filter : displayed data only
572             var filterData = oTable._('tr', {"filter":"applied"});   
573             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
574             if(filterData.length<=100){
575                 $.each(filterData, function(index, obj) {
576                     var last=$(obj).last();
577                     var key_value=unfold.get_value(last[0]);
578                     if(typeof($(last[0]).attr('checked'))=="undefined"){
579                         $.publish('selected', 'add/'+key_value);
580                     }
581                 });
582             }
583         },
584
585     });
586
587     $.plugin('QueryTable', QueryTable);
588
589   /* define the 'dom-checkbox' type for sorting in datatables 
590      http://datatables.net/examples/plug-ins/dom_sort.html
591      using trial and error I found that the actual column number
592      was in fact given as a third argument, and not second 
593      as the various online resources had it - go figure */
594     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
595         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
596             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
597         } );
598     }
599
600 })(jQuery);
601