nicer display for empty results
[unfold.git] / plugins / hazelnut / hazelnut.js
1 /**
2  * Description: display a query result in a datatables-powered <table>
3  * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 /*
8  * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
9  * Expression) that maps it to the dollar sign so it can't be overwritten by
10  * another library in the scope of its execution.
11  */
12 (function($){
13
14     var debug=false;
15 //    debug=true
16
17     // routing calls
18     $.fn.Hazelnut = function( method ) {
19         if ( methods[method] ) {
20             return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
21         } else if ( typeof method === 'object' || ! method ) {
22             return methods.init.apply( this, arguments );
23         } else {
24             $.error( 'Method ' +  method + ' does not exist on jQuery.Hazelnut' );
25         }    
26     };
27
28     /***************************************************************************
29      * Public methods
30      ***************************************************************************/
31
32     var methods = {
33
34         init : function ( options ) {
35             /* Default settings */
36             var options = $.extend( {
37                 'checkboxes': false
38             }, options);
39
40             return this.each(function() {
41                 var $this = $(this);
42                 /* Events */
43                 $this.on('show.Datatables', methods.show);
44
45                 /* An object that will hold private variables and methods */
46                 var hazelnut = new Hazelnut (options);
47                 $this.data('Hazelnut', hazelnut);
48
49                 var query_channel   = '/query/' + options.query_uuid + '/changed';
50                 var update_channel  = '/update-set/' + options.query_uuid;
51                 var results_channel = '/results/' + options.query_uuid + '/changed';
52
53                 // xxx not tested yet
54                 $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
55                 // xxx not tested yet
56                 $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
57                 // expected to work
58                 $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
59                 if (debug) messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
60
61             }); // this.each
62         }, // init
63
64         destroy : function( ) {
65             return this.each(function() {
66                 var $this = $(this);
67                 var hazelnut = $this.data('Hazelnut');
68
69                 // Unbind all events using namespacing
70                 $(window).unbind('Hazelnut');
71
72                 // Remove associated data
73                 hazelnut.remove();
74                 $this.removeData('Hazelnut');
75             });
76         }, // destroy
77
78         show : function( ) {
79             var $this=$(this);
80             // xxx wtf. why [1] ? would expect 0...
81             if (debug) messages.debug("Hitting suspicious line in hazelnut.show");
82             var oTable = $($('.dataTable', $this)[1]).dataTable();
83             oTable.fnAdjustColumnSizing()
84     
85             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
86             $(this).each(function(i,elt) {
87                 if (jQuery(elt).hasClass('dataTables')) {
88                     var myDiv=jQuery('#hazelnut-' + this.id).parent();
89                     if(myDiv.height()==0) {
90                         var oTable=$('#hazelnut-' + this.id).dataTable();            
91                         oTable.fnDraw();
92                     }
93                 }
94             });
95         } // show
96
97     }; // var methods;
98
99
100     /***************************************************************************
101      * Hazelnut object
102      ***************************************************************************/
103     function Hazelnut(options) {
104         /* member variables */
105         this.options = options;
106         // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
107         //this.current_query = null;
108         this.current_query=manifold.find_query(this.options.query_uuid);
109 //      if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
110         this.query_update = null;
111         this.current_resources = Array();
112
113         var object = this;
114
115         /* Transforms the table into DataTable, and keep a pointer to it */
116         actual_options = {
117             // Customize the position of Datatables elements (length,filter,button,...)
118             // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
119             sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
120             sPaginationType: 'bootstrap',
121             // Handle the null values & the error : Datatables warning Requested unknown parameter
122             // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
123             aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
124             // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
125             // sScrollX: '100%',       /* Horizontal scrolling */
126             bProcessing: true,      /* Loading */
127             fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
128         };
129         // the intention here is that options.datatables_options as coming from the python object take precedence
130         $.extend(actual_options, options.datatables_options );
131         this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
132
133         /* Setup the SelectAll button in the dataTable header */
134         /* xxx not sure this is still working */
135         var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
136         oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
137         oSelectAll.button();
138         oSelectAll.css('font-size','11px');
139         oSelectAll.css('float','right');
140         oSelectAll.css('margin-right','15px');
141         oSelectAll.css('margin-bottom','5px');
142         oSelectAll.unbind('click');
143         oSelectAll.click(selectAll);
144
145         /* Add a filtering function to the current table 
146          * Note: we use closure to get access to the 'options'
147          */
148         $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
149             /* No filtering if the table does not match */
150             if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
151                 return true;
152             return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
153         });
154
155         /* methods */
156
157         this.set_query = function(query) {
158             var options = this.options;
159             /* Compare current and advertised query to get added and removed fields */
160             previous_query = this.current_query;
161             /* Save the query as the current query */
162             this.current_query = query;
163             if (debug) messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
164             /* We check all necessary fields : in column editor I presume XXX */
165             // XXX ID naming has no plugin_uuid
166             if (typeof(query.fields) != 'undefined') {        
167                 $.each (query.fields, function(index, value) { 
168                     if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
169                         $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
170                 });
171             }
172             /*Process updates in filters / current_query must be updated before this call for filtering ! */
173             this.table.fnDraw();
174
175             /*
176              * Process updates in fields
177              */
178             if (typeof(query.fields) != 'undefined') {     
179                 /* DataTable Settings */
180                 var oSettings = this.table.dataTable().fnSettings();
181                 var cols = oSettings.aoColumns;
182                 var colnames = cols.map(function(x) {return x.sTitle});
183                 colnames = $.grep(colnames, function(value) {return value != "+/-";});
184
185                 if (previous_query == null) {
186                     var added_fields = query.fields;
187                     var removed_fields = colnames;            
188                     removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
189                 } else {
190                     var tmp = previous_query.diff_fields(query);
191                     var added_fields = tmp.added;
192                     var removed_fields = tmp.removed;
193                 }
194
195                 /* Hide/unhide columns to match added/removed fields */
196                 var object = this;
197                 $.each(added_fields, function (index, field) {            
198                     var index = object.getColIndex(field,cols);
199                     if(index != -1)
200                         object.table.fnSetColumnVis(index, true);
201                 });
202                 $.each(removed_fields, function (index, field) {
203                     var index = object.getColIndex(field,cols);
204                     if(index != -1)
205                         object.table.fnSetColumnVis(index, false);
206                 });            
207             }
208         }
209
210         this.set_resources = function(resources, instance) {
211             if (debug) messages.debug("entering hazelnut.set_resources");
212             var options = this.options;
213             var previous_resources = this.current_resources;
214             this.current_resources = resources;
215     
216             /* We uncheck all checkboxes ... */
217             $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
218             /* ... and check the ones specified in the resource list */
219             $.each(this.current_resources, function(index, urn) {
220                 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
221             });
222             
223         }
224
225         /**
226          * @brief Determine index of key in the table columns 
227          * @param key
228          * @param cols
229          */
230         this.getColIndex = function(key, cols) {
231             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
232             return (tabIndex.length > 0) ? tabIndex[0] : -1;
233         }
234     
235         /**
236          * @brief
237          * XXX will be removed/replaced
238          */
239         this.selected_changed = function(e, change) {
240             if (debug) messages.debug("entering hazelnut.selected_changed");
241             var actions = change.split("/");
242             if (actions.length > 1) {
243                 var oNodes = this.table.fnGetNodes();
244                 var myNode = $.grep(oNodes, function(value) {
245                     if (value.id == actions[1]) { return value; }
246                 });                
247                 if( myNode.length>0 ) {
248                     if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
249                         checked='';
250                     else
251                         checked="checked='checked' ";
252                     var newValue = this.checkbox(actions[1], 'node', checked, false);
253                     var columnPos = this.table.fnSettings().aoColumns.length - 1;
254                     this.table.fnUpdate(newValue, myNode[0], columnPos);
255                     this.table.fnDraw();
256                 }
257             }
258         }
259     
260         this.update_plugin = function(e, rows) {
261             // e.data is what we passed in second argument to subscribe
262             // so here it is the jquery object attached to the plugin <div>
263             var $plugindiv=e.data;
264             if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
265             // clear the spinning wheel: look up an ancestor that has the need-spin class
266             // do this before we might return
267             $plugindiv.closest('.need-spin').spin(false);
268
269             var options = this.options;
270             var hazelnut = this;
271     
272             if (rows.length==0) {
273                 if (debug) messages.debug("Empty result on hazelnut " + domid);
274                 var placeholder=$(this.table).find("td.dataTables_empty");
275                 console.log("placeholder "+placeholder);
276                 if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
277                 else                       this.table.html(unfold.warning("Empty result"));
278                 return;
279             } else if (typeof(rows[0].error) != 'undefined') {
280                 // we now should have another means to report errors that this inline/embedded hack
281                 if (debug) messages.error ("undefined result on " + domid + " - should not happen anymore");
282                 this.table.html(unfold.error(rows[0].error));
283                 return;
284             }
285             newlines = new Array();
286     
287             this.current_resources = Array();
288     
289             $.each(rows, function(index, obj) {
290                 newline = new Array();
291     
292                 // go through table headers to get column names we want
293                 // in order (we have temporarily hack some adjustments in names)
294                 var cols = hazelnut.table.fnSettings().aoColumns;
295                 var colnames = cols.map(function(x) {return x.sTitle})
296                 var nb_col = colnames.length;
297                 if (options.checkboxes)
298                     nb_col -= 1;
299                 for (var j = 0; j < nb_col; j++) {
300                     if (typeof colnames[j] == 'undefined') {
301                         newline.push('...');
302                     } else if (colnames[j] == 'hostname') {
303                         if (obj['type'] == 'resource,link')
304                             //TODO: we need to add source/destination for links
305                             newline.push('');
306                         else
307                             newline.push(obj['hostname']);
308                     } else {
309                         if (obj[colnames[j]])
310                             newline.push(obj[colnames[j]]);
311                         else
312                             newline.push('');
313                     }
314                 }
315     
316                 if (options.checkboxes) {
317                     var checked = '';
318                     if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
319                         checked = 'checked ';
320                         hazelnut.current_resources.push(obj['urn']);
321                     }
322                     // Use a key instead of hostname (hard coded...)
323                     newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
324                 }
325     
326                 newlines.push(newline);
327     
328     
329             });
330     
331             this.table.fnClearTable();
332             if (debug) messages.debug("hazelnut.update_plugin: total of " + newlines.length + " rows");
333             this.table.fnAddData(newlines);
334     
335         };
336
337         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
338             var result="";
339             /* Prefix id with plugin_uuid */
340             result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
341             result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
342             result +="></input>";
343             return result;
344         };
345     } // constructor
346
347     /***************************************************************************
348      * Private methods
349      * xxx I'm not sure why this should not be methods in the Hazelnut class above
350      ***************************************************************************/
351
352     /** 
353      * @brief Hazelnut filtering function
354      */
355     function hazelnut_filter (oSettings, aData, iDataIndex) {
356         var cur_query = this.current_query;
357         var ret = true;
358
359         /* We have an array of filters : a filter is an array (key op val) 
360          * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
361          *     can we exploit the data property somewhere ?
362          * field values (unless formatting) : aData
363          *     formatting should leave original data available in a hidden field
364          *
365          * The current line should validate all filters
366          */
367         $.each (cur_query.filters, function(index, filter) { 
368             /* XXX How to manage checkbox ? */
369             var key = filter[0]; 
370             var op = filter[1];
371             var value = filter[2];
372
373             /* Determine index of key in the table columns */
374             var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
375
376             /* Unknown key: no filtering */
377             if (typeof(col) == 'undefined')
378                 return;
379
380             col_value=unfold.get_value(aData[col]);
381             /* Test whether current filter is compatible with the column */
382             if (op == '=' || op == '==') {
383                 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
384                     ret = false;
385             }else if (op == '!=') {
386                 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
387                     ret = false;
388             } else if(op=='<') {
389                 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
390                     ret = false;
391             } else if(op=='>') {
392                 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
393                     ret = false;
394             } else if(op=='<=' || op=='≤') {
395                 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
396                     ret = false;
397             } else if(op=='>=' || op=='≥') {
398                 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
399                     ret = false;
400             }else{
401                 // How to break out of a loop ?
402                 alert("filter not supported");
403                 return false;
404             }
405
406         });
407         return ret;
408     }
409
410     function hazelnut_draw_callback() {
411         var options = this.options;
412         /* 
413          * Handle clicks on checkboxes: reassociate checkbox click every time
414          * the table is redrawn 
415          */
416         $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
417         $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
418
419         if (!this.table)
420             return;
421
422         /* Remove pagination if we show only a few results */
423         var wrapper = this.table; //.parent().parent().parent();
424         var rowsPerPage = this.table.fnSettings()._iDisplayLength;
425         var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
426         var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
427
428         if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
429             $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
430         } else {
431             $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
432         }
433
434         if ( rowsToShow <= minRowsPerPage ) {
435             $('.hazelnut_length', wrapper).css('visibility', 'hidden');
436         } else {
437             $('.hazelnut_length', wrapper).css('visibility', 'visible');
438         }
439     }
440
441     function check_click (e) {
442         var object = e.data.instance;
443         var value = this.value;
444
445         if (this.checked) {
446             object.current_resources.push(value);
447         } else {
448             tmp = $.grep(object.current_resources, function(x) { return x != value; });
449             object.current_resources = tmp;
450         }
451
452         /* inform slice that our selected resources have changed */
453         $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
454
455     }
456
457     function selectAll() {
458         // requires jQuery id
459         var uuid=this.id.split("-");
460         var oTable=$("#hazelnut-"+uuid[1]).dataTable();
461         // Function available in Hazelnut 1.9.x
462         // Filter : displayed data only
463         var filterData = oTable._('tr', {"filter":"applied"});   
464         /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
465         if(filterData.length<=100){
466             $.each(filterData, function(index, obj) {
467                 var last=$(obj).last();
468                 var key_value=unfold.get_value(last[0]);
469                 if(typeof($(last[0]).attr('checked'))=="undefined"){
470                     $.publish('selected', 'add/'+key_value);
471                 }
472             });
473         }
474     }
475     
476 })( jQuery );