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