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