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