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