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