reworked slice page, added ResourcesSelected plugin
[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         /**
35          * @brief Plugin initialization
36          * @param options : an associative array of setting values
37          * @return : a jQuery collection of objects on which the plugin is
38          *     applied, which allows to maintain chainability of calls
39          */
40         init : function ( options ) {
41
42             /* Default settings */
43             var options = $.extend( {
44                 'checkboxes': false
45             }, options);
46
47             return this.each(function() {
48
49                 var $this = $(this);
50
51                 /* Events */
52                 $this.on('show.Datatables', methods.show);
53
54                 /* An object that will hold private variables and methods */
55                 var hazelnut = new Hazelnut (options);
56                 $this.data('Hazelnut', hazelnut);
57                 var query_channel   = '/query/' + options.query_uuid + '/changed';
58                 var update_channel  = '/update-set/' + options.query_uuid;
59                 var results_channel = '/results/' + options.query_uuid + '/changed';
60
61                 // xxx not tested yet
62                 $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
63                 // xxx not tested yet
64                 $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
65                 // expected to work
66                 $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
67                 if (debug)
68                     messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
69
70             }); // this.each
71         }, // init
72
73         /**
74          * @brief Plugin destruction
75          * @return : a jQuery collection of objects on which the plugin is
76          *     applied, which allows to maintain chainability of calls
77          */
78         destroy : function( ) {
79
80             return this.each(function() {
81                 var $this = $(this);
82                 var hazelnut = $this.data('Hazelnut');
83
84                 // Unbind all events using namespacing
85                 $(window).unbind('Hazelnut');
86
87                 // Remove associated data
88                 hazelnut.remove();
89                 $this.removeData('Hazelnut');
90             });
91         }, // destroy
92
93         show : function( ) {
94             var $this=$(this);
95             // xxx wtf. why [1] ? would expect 0...
96             if (debug)
97                 messages.debug("Hitting suspicious line in hazelnut.show");
98             var oTable = $($('.dataTable', $this)[1]).dataTable();
99             oTable.fnAdjustColumnSizing()
100         
101             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
102             $(this).each(function(i,elt) {
103                 if (jQuery(elt).hasClass('dataTables')) {
104                     var myDiv=jQuery('#hazelnut-' + this.id).parent();
105                     if(myDiv.height()==0) {
106                         var oTable=$('#hazelnut-' + this.id).dataTable();            
107                         oTable.fnDraw();
108                     }
109                 }
110             });
111         } // show
112
113     }; // var methods;
114
115     /***************************************************************************
116      * Hazelnut object
117      ***************************************************************************/
118
119     function Hazelnut(options) 
120     {
121         /* member variables */
122         this.options = options;
123
124         // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
125         //this.current_query = null;
126         this.current_query=manifold.find_query(this.options.query_uuid);
127         //  if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
128         this.query_update = null;
129         this.current_resources = Array();
130
131         var object = this;
132
133         /* Transforms the table into DataTable, and keep a pointer to it */
134         actual_options = {
135             // Customize the position of Datatables elements (length,filter,button,...)
136             // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
137             sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
138             sPaginationType: 'bootstrap',
139             // Handle the null values & the error : Datatables warning Requested unknown parameter
140             // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
141             aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
142             // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
143             // sScrollX: '100%',       /* Horizontal scrolling */
144             bProcessing: true,      /* Loading */
145             fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
146         };
147         // the intention here is that options.datatables_options as coming from the python object take precedence
148         //  XXX DISABLED by jordan: was causing errors in datatables.js     $.extend(actual_options, options.datatables_options );
149         this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
150
151         /* Setup the SelectAll button in the dataTable header */
152         /* xxx not sure this is still working */
153         var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
154         oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
155         oSelectAll.button();
156         oSelectAll.css('font-size','11px');
157         oSelectAll.css('float','right');
158         oSelectAll.css('margin-right','15px');
159         oSelectAll.css('margin-bottom','5px');
160         oSelectAll.unbind('click');
161         oSelectAll.click(selectAll);
162
163         /* Add a filtering function to the current table 
164          * Note: we use closure to get access to the 'options'
165          */
166         $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
167             /* No filtering if the table does not match */
168             if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
169                 return true;
170             return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
171         });
172
173         /* methods */
174
175         this.set_query = function(query) {
176             messages.info('hazelnut.set_query');
177             var options = this.options;
178             /* Compare current and advertised query to get added and removed fields */
179             previous_query = this.current_query;
180             /* Save the query as the current query */
181             this.current_query = query;
182             if (debug)
183                 messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
184
185             /* We check all necessary fields : in column editor I presume XXX */
186             // XXX ID naming has no plugin_uuid
187             if (typeof(query.fields) != 'undefined') {        
188                 $.each (query.fields, function(index, value) { 
189                     if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
190                         $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
191                 });
192             }
193
194             /* Process updates in filters / current_query must be updated before this call for filtering ! */
195             this.table.fnDraw();
196
197             /*
198              * Process updates in fields
199              */
200             if (typeof(query.fields) != 'undefined') {     
201                 /* DataTable Settings */
202                 var oSettings = this.table.dataTable().fnSettings();
203                 var cols = oSettings.aoColumns;
204                 var colnames = cols.map(function(x) {return x.sTitle});
205                 colnames = $.grep(colnames, function(value) {return value != "+/-";});
206
207                 if (previous_query == null) {
208                     var added_fields = query.fields;
209                     var removed_fields = colnames;            
210                     removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
211                 } else {
212                     var tmp = previous_query.diff_fields(query);
213                     var added_fields = tmp.added;
214                     var removed_fields = tmp.removed;
215                 }
216
217                 /* Hide/unhide columns to match added/removed fields */
218                 var object = this;
219                 $.each(added_fields, function (index, field) {            
220                     var index = object.getColIndex(field,cols);
221                     if(index != -1)
222                         object.table.fnSetColumnVis(index, true);
223                 });
224                 $.each(removed_fields, function (index, field) {
225                     var index = object.getColIndex(field,cols);
226                     if(index != -1)
227                         object.table.fnSetColumnVis(index, false);
228                 });            
229             }
230         }
231
232         this.set_resources = function(resources, instance) {
233             if (debug)
234                 messages.debug("entering hazelnut.set_resources");
235             var options = this.options;
236             var previous_resources = this.current_resources;
237             this.current_resources = resources;
238     
239             /* We uncheck all checkboxes ... */
240             $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
241             /* ... and check the ones specified in the resource list */
242             $.each(this.current_resources, function(index, urn) {
243                 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
244             });
245             
246         }
247
248         /**
249          * @brief Determine index of key in the table columns 
250          * @param key
251          * @param cols
252          */
253         this.getColIndex = function(key, cols) {
254             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
255             return (tabIndex.length > 0) ? tabIndex[0] : -1;
256         }
257     
258         /**
259          * @brief
260          * XXX will be removed/replaced
261          */
262         this.selected_changed = function(e, change) {
263         if (debug) messages.debug("entering hazelnut.selected_changed");
264             var actions = change.split("/");
265             if (actions.length > 1) {
266                 var oNodes = this.table.fnGetNodes();
267                 var myNode = $.grep(oNodes, function(value) {
268                     if (value.id == actions[1]) { return value; }
269                 });                
270                 if( myNode.length>0 ) {
271                     if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
272                         checked='';
273                     else
274                         checked="checked='checked' ";
275                     var newValue = this.checkbox(actions[1], 'node', checked, false);
276                     var columnPos = this.table.fnSettings().aoColumns.length - 1;
277                     this.table.fnUpdate(newValue, myNode[0], columnPos);
278                     this.table.fnDraw();
279                 }
280             }
281         }
282     
283         this.update_plugin = function(e, rows) {
284         // e.data is what we passed in second argument to subscribe
285         // so here it is the jquery object attached to the plugin <div>
286         var $plugindiv=e.data;
287         if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
288         // clear the spinning wheel: look up an ancestor that has the need-spin class
289         // do this before we might return
290         $plugindiv.closest('.need-spin').spin(false);
291
292             var options = this.options;
293             var hazelnut = this;
294     
295         /* if we get no result, or an error, try to make that clear, and exit */
296             if (rows.length==0) {
297         if (debug) messages.debug("Empty result on hazelnut " + this.options.domid);
298         var placeholder=$(this.table).find("td.dataTables_empty");
299         console.log("placeholder "+placeholder);
300         if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
301         else               this.table.html(unfold.warning("Empty result"));
302                 return;
303             } else if (typeof(rows[0].error) != 'undefined') {
304         // we now should have another means to report errors that this inline/embedded hack
305         if (debug) messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
306                 this.table.html(unfold.error(rows[0].error));
307                 return;
308             }
309
310         /* 
311          * fill the dataTables object
312          * we cannot set html content directly here, need to use fnAddData
313          */
314             var lines = new Array();
315     
316             this.current_resources = Array();
317     
318             $.each(rows, function(index, row) {
319         // this models a line in dataTables, each element in the line describes a cell
320                 line = new Array();
321      
322                 // go through table headers to get column names we want
323                 // in order (we have temporarily hack some adjustments in names)
324                 var cols = hazelnut.table.fnSettings().aoColumns;
325                 var colnames = cols.map(function(x) {return x.sTitle})
326                 var nb_col = cols.length;
327         /* if we've requested checkboxes, then forget about the checkbox column for now */
328                 if (options.checkboxes) nb_col -= 1;
329
330         /* fill in stuff depending on the column name */
331                 for (var j = 0; j < nb_col; j++) {
332                     if (typeof colnames[j] == 'undefined') {
333                         line.push('...');
334                     } else if (colnames[j] == 'hostname') {
335                         if (row['type'] == 'resource,link')
336                             //TODO: we need to add source/destination for links
337                             line.push('');
338                         else
339                             line.push(row['hostname']);
340                     } else {
341                         if (row[colnames[j]])
342                             line.push(row[colnames[j]]);
343                         else
344                             line.push('');
345                     }
346                 }
347     
348         /* catch up with the last column if checkboxes were requested */
349                 if (options.checkboxes) {
350                     var checked = '';
351             // xxx problem is, we don't get this 'sliver' thing set apparently
352                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
353                         checked = 'checked ';
354                         hazelnut.current_resources.push(row['urn']);
355                     }
356                     // Use a key instead of hostname (hard coded...)
357                     line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
358                 }
359     
360                 lines.push(line);
361     
362             });
363     
364         this.table.fnClearTable();
365         if (debug) messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
366             this.table.fnAddData(lines);
367     
368         };
369
370         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
371         var result="";
372             // Preafix id with plugin_uuid
373         result += "<input";
374         result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
375         result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
376         result += " name='" + unfold.get_value(field) + "'";
377         result += " type='checkbox'";
378         result += selected_str;
379         result += disabled_str;
380         result += " autocomplete='off'";
381         result += " value='" + unfold.get_value(header) + "'";
382         result += "></input>";
383         return result;
384         };
385     } // constructor
386
387     /***************************************************************************
388      * Private methods
389      * xxx I'm not sure why this should not be methods in the Hazelnut class above
390      ***************************************************************************/
391
392     /** 
393      * @brief Hazelnut filtering function
394      */
395     function hazelnut_filter (oSettings, aData, iDataIndex) {
396         var cur_query = this.current_query;
397         if (!cur_query) return true;
398         var ret = true;
399
400         /* We have an array of filters : a filter is an array (key op val) 
401          * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
402          *     can we exploit the data property somewhere ?
403          * field values (unless formatting) : aData
404          *     formatting should leave original data available in a hidden field
405          *
406          * The current line should validate all filters
407          */
408         $.each (cur_query.filters, function(index, filter) { 
409             /* XXX How to manage checkbox ? */
410             var key = filter[0]; 
411             var op = filter[1];
412             var value = filter[2];
413
414             /* Determine index of key in the table columns */
415             var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
416
417             /* Unknown key: no filtering */
418             if (typeof(col) == 'undefined')
419                 return;
420
421             col_value=unfold.get_value(aData[col]);
422             /* Test whether current filter is compatible with the column */
423             if (op == '=' || op == '==') {
424                 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
425                     ret = false;
426             }else if (op == '!=') {
427                 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
428                     ret = false;
429             } else if(op=='<') {
430                 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
431                     ret = false;
432             } else if(op=='>') {
433                 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
434                     ret = false;
435             } else if(op=='<=' || op=='≤') {
436                 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
437                     ret = false;
438             } else if(op=='>=' || op=='≥') {
439                 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
440                     ret = false;
441             }else{
442                 // How to break out of a loop ?
443                 alert("filter not supported");
444                 return false;
445             }
446
447         });
448         return ret;
449     }
450
451     function hazelnut_draw_callback() {
452         var options = this.options;
453         /* 
454          * Handle clicks on checkboxes: reassociate checkbox click every time
455          * the table is redrawn 
456          */
457         $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
458         $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
459
460         if (!this.table)
461             return;
462
463         /* Remove pagination if we show only a few results */
464         var wrapper = this.table; //.parent().parent().parent();
465         var rowsPerPage = this.table.fnSettings()._iDisplayLength;
466         var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
467         var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
468
469         if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
470             $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
471         } else {
472             $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
473         }
474
475         if ( rowsToShow <= minRowsPerPage ) {
476             $('.hazelnut_length', wrapper).css('visibility', 'hidden');
477         } else {
478             $('.hazelnut_length', wrapper).css('visibility', 'visible');
479         }
480     }
481
482     function check_click (e) {
483         var object = e.data.instance;
484         var value = this.value;
485
486         if (this.checked) {
487             object.current_resources.push(value);
488         } else {
489             tmp = $.grep(object.current_resources, function(x) { return x != value; });
490             object.current_resources = tmp;
491         }
492
493         /* inform slice that our selected resources have changed */
494         $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
495
496     }
497
498     function selectAll() {
499         // requires jQuery id
500         var uuid=this.id.split("-");
501         var oTable=$("#hazelnut-"+uuid[1]).dataTable();
502         // Function available in Hazelnut 1.9.x
503         // Filter : displayed data only
504         var filterData = oTable._('tr', {"filter":"applied"});   
505         /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
506         if(filterData.length<=100){
507             $.each(filterData, function(index, obj) {
508                 var last=$(obj).last();
509                 var key_value=unfold.get_value(last[0]);
510                 if(typeof($(last[0]).attr('checked'))=="undefined"){
511                     $.publish('selected', 'add/'+key_value);
512                 }
513             });
514         }
515     }
516     
517 })( jQuery );