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