7afc726bb45e568357a00e5e0aa4f225469de59e
[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         // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
104         //this.current_query = null;
105         this.current_query=manifold.find_query(this.options.query_uuid);
106         if (debug) console.log("Hazelnut constructor: have set current_query -> " + this.current_query);
107         this.query_update = null;
108         this.current_resources = Array();
109
110         var object = this;
111
112         /* Transforms the table into DataTable, and keep a pointer to it */
113         actual_options = {
114             // Customize the position of Datatables elements (length,filter,button,...)
115             // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
116             sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
117             sPaginationType: 'bootstrap',
118             // Handle the null values & the error : Datatables warning Requested unknown parameter
119             // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
120             aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
121             // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
122             // sScrollX: '100%',       /* Horizontal scrolling */
123             bProcessing: true,      /* Loading */
124             fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
125         };
126         // the intention here is that options.datatables_options as coming from the python object take precedence
127         $.extend(actual_options, options.datatables_options );
128         this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
129
130         /* Setup the SelectAll button in the dataTable header */
131         /* xxx not sure this is still working */
132         var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
133         oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
134         oSelectAll.button();
135         oSelectAll.css('font-size','11px');
136         oSelectAll.css('float','right');
137         oSelectAll.css('margin-right','15px');
138         oSelectAll.css('margin-bottom','5px');
139         oSelectAll.unbind('click');
140         oSelectAll.click(selectAll);
141
142         /* Add a filtering function to the current table 
143          * Note: we use closure to get access to the 'options'
144          */
145         $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
146             /* No filtering if the table does not match */
147             if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
148                 return true;
149             return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
150         });
151
152         /* methods */
153
154         this.set_query = function(query) {
155             var options = this.options;
156             /* Compare current and advertised query to get added and removed fields */
157             previous_query = this.current_query;
158             /* Save the query as the current query */
159             this.current_query = query;
160             if (debug) console.log("hazelnut.set_query, current_query is now -> " + this.current_query);
161             /* We check all necessary fields : in column editor I presume XXX */
162             // XXX ID naming has no plugin_uuid
163             if (typeof(query.fields) != 'undefined') {        
164                 $.each (query.fields, function(index, value) { 
165                     if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
166                         $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
167                 });
168             }
169             /*Process updates in filters / current_query must be updated before this call for filtering ! */
170             this.table.fnDraw();
171
172             /*
173              * Process updates in fields
174              */
175             if (typeof(query.fields) != 'undefined') {     
176                 /* DataTable Settings */
177                 var oSettings = this.table.dataTable().fnSettings();
178                 var cols = oSettings.aoColumns;
179                 var colnames = cols.map(function(x) {return x.sTitle});
180                 colnames = $.grep(colnames, function(value) {return value != "+/-";});
181
182                 if (previous_query == null) {
183                     var added_fields = query.fields;
184                     var removed_fields = colnames;            
185                     removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
186                 } else {
187                     var tmp = previous_query.diff_fields(query);
188                     var added_fields = tmp.added;
189                     var removed_fields = tmp.removed;
190                 }
191
192                 /* Hide/unhide columns to match added/removed fields */
193                 var object = this;
194                 $.each(added_fields, function (index, field) {            
195                     var index = object.getColIndex(field,cols);
196                     if(index != -1)
197                         object.table.fnSetColumnVis(index, true);
198                 });
199                 $.each(removed_fields, function (index, field) {
200                     var index = object.getColIndex(field,cols);
201                     if(index != -1)
202                         object.table.fnSetColumnVis(index, false);
203                 });            
204             }
205         }
206
207         this.set_resources = function(resources, instance) {
208             if (debug) console.log("entering hazelnut.set_resources");
209             var options = this.options;
210             var previous_resources = this.current_resources;
211             this.current_resources = resources;
212     
213             /* We uncheck all checkboxes ... */
214             $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
215             /* ... and check the ones specified in the resource list */
216             $.each(this.current_resources, function(index, urn) {
217                 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
218             });
219             
220         }
221
222         /**
223          * @brief Determine index of key in the table columns 
224          * @param key
225          * @param cols
226          */
227         this.getColIndex = function(key, cols) {
228             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
229             return (tabIndex.length > 0) ? tabIndex[0] : -1;
230         }
231     
232         /**
233          * @brief
234          * XXX will be removed/replaced
235          */
236         this.selected_changed = function(e, change) {
237             if (debug) console.log("entering hazelnut.selected_changed");
238             var actions = change.split("/");
239             if (actions.length > 1) {
240                 var oNodes = this.table.fnGetNodes();
241                 var myNode = $.grep(oNodes, function(value) {
242                     if (value.id == actions[1]) { return value; }
243                 });                
244                 if( myNode.length>0 ) {
245                     if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
246                         checked='';
247                     else
248                         checked="checked='checked' ";
249                     var newValue = this.checkbox(actions[1], 'node', checked, false);
250                     var columnPos = this.table.fnSettings().aoColumns.length - 1;
251                     this.table.fnUpdate(newValue, myNode[0], columnPos);
252                     this.table.fnDraw();
253                 }
254             }
255         }
256     
257         this.update_plugin = function(e, rows) {
258             // e.data is what we passed in second argument to subscribe
259             // so here it is the jquery object attached to the plugin <div>
260             var $plugindiv=e.data;
261             if (debug) console.log("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
262             // clear the spinning wheel: look up an ancestor that has the need-spin class
263             // do this before we might return
264             $plugindiv.closest('.need-spin').spin(false);
265
266             var options = this.options;
267             var hazelnut = this;
268     
269             if (rows.length==0) {
270                 if (debug) console.l ("empty result");
271                 this.table.html(unfold.errorDisplay("No Result"));   
272                 return;
273             } else if (typeof(rows[0].error) != 'undefined') {
274                 if (debug) console.log ("undefined result");
275                 this.table.html(unfold.errorDisplay(rows[0].error));
276                 return;
277             }
278             newlines = new Array();
279     
280             this.current_resources = Array();
281     
282             $.each(rows, function(index, obj) {
283                 newline = new Array();
284     
285                 // go through table headers to get column names we want
286                 // in order (we have temporarily hack some adjustments in names)
287                 var cols = hazelnut.table.fnSettings().aoColumns;
288                 var colnames = cols.map(function(x) {return x.sTitle})
289                 var nb_col = colnames.length;
290                 if (options.checkboxes)
291                     nb_col -= 1;
292                 for (var j = 0; j < nb_col; j++) {
293                     if (typeof colnames[j] == 'undefined') {
294                         newline.push('...');
295                     } else if (colnames[j] == 'hostname') {
296                         if (obj['type'] == 'resource,link')
297                             //TODO: we need to add source/destination for links
298                             newline.push('');
299                         else
300                             newline.push(obj['hostname']);
301                     } else {
302                         if (obj[colnames[j]])
303                             newline.push(obj[colnames[j]]);
304                         else
305                             newline.push('');
306                     }
307                 }
308     
309                 if (options.checkboxes) {
310                     var checked = '';
311                     if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
312                         checked = 'checked ';
313                         hazelnut.current_resources.push(obj['urn']);
314                     }
315                     // Use a key instead of hostname (hard coded...)
316                     newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
317                 }
318     
319                 newlines.push(newline);
320     
321     
322             });
323     
324             this.table.fnClearTable();
325             if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
326             this.table.fnAddData(newlines);
327     
328         };
329
330         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
331             var result="";
332             /* Prefix id with plugin_uuid */
333             result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
334             result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
335             result +="></input>";
336             return result;
337         };
338     } // constructor
339
340     /***************************************************************************
341      * Private methods
342      * xxx I'm not sure why this should not be methods in the Hazelnut class above
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 );