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