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