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