bbaf11ec764749c577770232366568569f5ae202
[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.__repr());
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             messages.info('hazelnut.set_query');
159             var options = this.options;
160             /* Compare current and advertised query to get added and removed fields */
161             previous_query = this.current_query;
162             /* Save the query as the current query */
163             this.current_query = query;
164             if (debug) messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
165             /* We check all necessary fields : in column editor I presume XXX */
166             // XXX ID naming has no plugin_uuid
167             if (typeof(query.fields) != 'undefined') {        
168                 $.each (query.fields, function(index, value) { 
169                     if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
170                         $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
171                 });
172             }
173             /*Process updates in filters / current_query must be updated before this call for filtering ! */
174             this.table.fnDraw();
175
176             /*
177              * Process updates in fields
178              */
179             if (typeof(query.fields) != 'undefined') {     
180                 /* DataTable Settings */
181                 var oSettings = this.table.dataTable().fnSettings();
182                 var cols = oSettings.aoColumns;
183                 var colnames = cols.map(function(x) {return x.sTitle});
184                 colnames = $.grep(colnames, function(value) {return value != "+/-";});
185
186                 if (previous_query == null) {
187                     var added_fields = query.fields;
188                     var removed_fields = colnames;            
189                     removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
190                 } else {
191                     var tmp = previous_query.diff_fields(query);
192                     var added_fields = tmp.added;
193                     var removed_fields = tmp.removed;
194                 }
195
196                 /* Hide/unhide columns to match added/removed fields */
197                 var object = this;
198                 $.each(added_fields, function (index, field) {            
199                     var index = object.getColIndex(field,cols);
200                     if(index != -1)
201                         object.table.fnSetColumnVis(index, true);
202                 });
203                 $.each(removed_fields, function (index, field) {
204                     var index = object.getColIndex(field,cols);
205                     if(index != -1)
206                         object.table.fnSetColumnVis(index, false);
207                 });            
208             }
209         }
210
211         this.set_resources = function(resources, instance) {
212             if (debug) messages.debug("entering hazelnut.set_resources");
213             var options = this.options;
214             var previous_resources = this.current_resources;
215             this.current_resources = resources;
216     
217             /* We uncheck all checkboxes ... */
218             $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
219             /* ... and check the ones specified in the resource list */
220             $.each(this.current_resources, function(index, urn) {
221                 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
222             });
223             
224         }
225
226         /**
227          * @brief Determine index of key in the table columns 
228          * @param key
229          * @param cols
230          */
231         this.getColIndex = function(key, cols) {
232             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
233             return (tabIndex.length > 0) ? tabIndex[0] : -1;
234         }
235     
236         /**
237          * @brief
238          * XXX will be removed/replaced
239          */
240         this.selected_changed = function(e, change) {
241             if (debug) messages.debug("entering hazelnut.selected_changed");
242             var actions = change.split("/");
243             if (actions.length > 1) {
244                 var oNodes = this.table.fnGetNodes();
245                 var myNode = $.grep(oNodes, function(value) {
246                     if (value.id == actions[1]) { return value; }
247                 });                
248                 if( myNode.length>0 ) {
249                     if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
250                         checked='';
251                     else
252                         checked="checked='checked' ";
253                     var newValue = this.checkbox(actions[1], 'node', checked, false);
254                     var columnPos = this.table.fnSettings().aoColumns.length - 1;
255                     this.table.fnUpdate(newValue, myNode[0], columnPos);
256                     this.table.fnDraw();
257                 }
258             }
259         }
260     
261         this.update_plugin = function(e, rows) {
262             // e.data is what we passed in second argument to subscribe
263             // so here it is the jquery object attached to the plugin <div>
264             var $plugindiv=e.data;
265             if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
266             // clear the spinning wheel: look up an ancestor that has the need-spin class
267             // do this before we might return
268             $plugindiv.closest('.need-spin').spin(false);
269
270             var options = this.options;
271             var hazelnut = this;
272     
273             /* if we get no result, or an error, try to make that clear, and exit */
274             if (rows.length==0) {
275                 if (debug) messages.debug("Empty result on hazelnut " + domid);
276                 var placeholder=$(this.table).find("td.dataTables_empty");
277                 console.log("placeholder "+placeholder);
278                 if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
279                 else                       this.table.html(unfold.warning("Empty result"));
280                 return;
281             } else if (typeof(rows[0].error) != 'undefined') {
282                 // we now should have another means to report errors that this inline/embedded hack
283                 if (debug) messages.error ("undefined result on " + domid + " - should not happen anymore");
284                 this.table.html(unfold.error(rows[0].error));
285                 return;
286             }
287
288             /* 
289              * fill the dataTables object
290              * we cannot set html content directly here, need to use fnAddData
291              */
292             var lines = new Array();
293     
294             this.current_resources = Array();
295     
296             $.each(rows, function(index, row) {
297                 // this models a line in dataTables, each element in the line describes a cell
298                 line = new Array();
299      
300                 // go through table headers to get column names we want
301                 // in order (we have temporarily hack some adjustments in names)
302                 var cols = hazelnut.table.fnSettings().aoColumns;
303                 var colnames = cols.map(function(x) {return x.sTitle})
304                 var nb_col = cols.length;
305                 /* if we've requested checkboxes, then forget about the checkbox column for now */
306                 if (options.checkboxes) nb_col -= 1;
307
308                 /* fill in stuff depending on the column name */
309                 for (var j = 0; j < nb_col; j++) {
310                     if (typeof colnames[j] == 'undefined') {
311                         line.push('...');
312                     } else if (colnames[j] == 'hostname') {
313                         if (row['type'] == 'resource,link')
314                             //TODO: we need to add source/destination for links
315                             line.push('');
316                         else
317                             line.push(row['hostname']);
318                     } else {
319                         if (row[colnames[j]])
320                             line.push(row[colnames[j]]);
321                         else
322                             line.push('');
323                     }
324                 }
325     
326                 /* catch up with the last column if checkboxes were requested */
327                 if (options.checkboxes) {
328                     var checked = '';
329                     // xxx problem is, we don't get this 'sliver' thing set apparently
330                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
331                         checked = 'checked ';
332                         hazelnut.current_resources.push(row['urn']);
333                     }
334                     // Use a key instead of hostname (hard coded...)
335                     line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
336                 }
337     
338                 lines.push(line);
339     
340             });
341     
342             this.table.fnClearTable();
343             if (debug) messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
344             this.table.fnAddData(lines);
345     
346         };
347
348         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
349             var result="";
350             // Preafix id with plugin_uuid
351             result += "<input";
352             result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
353             result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
354             result += " name='" + unfold.get_value(field) + "'";
355             result += " type='checkbox'";
356             result += selected_str;
357             result += disabled_str;
358             result += " autocomplete='off'";
359             result += " value='" + unfold.get_value(header) + "'";
360             result += "></input>";
361             return result;
362         };
363     } // constructor
364
365     /***************************************************************************
366      * Private methods
367      * xxx I'm not sure why this should not be methods in the Hazelnut class above
368      ***************************************************************************/
369
370     /** 
371      * @brief Hazelnut filtering function
372      */
373     function hazelnut_filter (oSettings, aData, iDataIndex) {
374         var cur_query = this.current_query;
375         var ret = true;
376
377         /* We have an array of filters : a filter is an array (key op val) 
378          * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
379          *     can we exploit the data property somewhere ?
380          * field values (unless formatting) : aData
381          *     formatting should leave original data available in a hidden field
382          *
383          * The current line should validate all filters
384          */
385         $.each (cur_query.filters, function(index, filter) { 
386             /* XXX How to manage checkbox ? */
387             var key = filter[0]; 
388             var op = filter[1];
389             var value = filter[2];
390
391             /* Determine index of key in the table columns */
392             var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
393
394             /* Unknown key: no filtering */
395             if (typeof(col) == 'undefined')
396                 return;
397
398             col_value=unfold.get_value(aData[col]);
399             /* Test whether current filter is compatible with the column */
400             if (op == '=' || op == '==') {
401                 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
402                     ret = false;
403             }else if (op == '!=') {
404                 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
405                     ret = false;
406             } else if(op=='<') {
407                 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
408                     ret = false;
409             } else if(op=='>') {
410                 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
411                     ret = false;
412             } else if(op=='<=' || op=='≤') {
413                 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
414                     ret = false;
415             } else if(op=='>=' || op=='≥') {
416                 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
417                     ret = false;
418             }else{
419                 // How to break out of a loop ?
420                 alert("filter not supported");
421                 return false;
422             }
423
424         });
425         return ret;
426     }
427
428     function hazelnut_draw_callback() {
429         var options = this.options;
430         /* 
431          * Handle clicks on checkboxes: reassociate checkbox click every time
432          * the table is redrawn 
433          */
434         $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
435         $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
436
437         if (!this.table)
438             return;
439
440         /* Remove pagination if we show only a few results */
441         var wrapper = this.table; //.parent().parent().parent();
442         var rowsPerPage = this.table.fnSettings()._iDisplayLength;
443         var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
444         var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
445
446         if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
447             $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
448         } else {
449             $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
450         }
451
452         if ( rowsToShow <= minRowsPerPage ) {
453             $('.hazelnut_length', wrapper).css('visibility', 'hidden');
454         } else {
455             $('.hazelnut_length', wrapper).css('visibility', 'visible');
456         }
457     }
458
459     function check_click (e) {
460         var object = e.data.instance;
461         var value = this.value;
462
463         if (this.checked) {
464             object.current_resources.push(value);
465         } else {
466             tmp = $.grep(object.current_resources, function(x) { return x != value; });
467             object.current_resources = tmp;
468         }
469
470         /* inform slice that our selected resources have changed */
471         $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
472
473     }
474
475     function selectAll() {
476         // requires jQuery id
477         var uuid=this.id.split("-");
478         var oTable=$("#hazelnut-"+uuid[1]).dataTable();
479         // Function available in Hazelnut 1.9.x
480         // Filter : displayed data only
481         var filterData = oTable._('tr', {"filter":"applied"});   
482         /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
483         if(filterData.length<=100){
484             $.each(filterData, function(index, obj) {
485                 var last=$(obj).last();
486                 var key_value=unfold.get_value(last[0]);
487                 if(typeof($(last[0]).attr('checked'))=="undefined"){
488                     $.publish('selected', 'add/'+key_value);
489                 }
490             });
491         }
492     }
493     
494 })( jQuery );