manifold-core deprecated, keep its -leftovers for further ref
[unfold.git] / plugins / hazelnut / hazelnut.js
1 /**
2  * MySlice Hazelnut plugin
3  * URL: http://trac.myslice.info
4  * Description: display a query result in a datatables-powered <table>
5  * Author: The MySlice Team
6  * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
7  * License: GPLv3
8  */
9
10 /*
11  * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
12  * Expression) that maps it to the dollar sign so it can't be overwritten by
13  * another library in the scope of its execution.
14  */
15 (function($){
16
17     var debug=false;
18 //    debug=true
19
20     // routing calls
21     $.fn.Hazelnut = function( method ) {
22         if ( methods[method] ) {
23             return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
24         } else if ( typeof method === 'object' || ! method ) {
25             return methods.init.apply( this, arguments );
26         } else {
27             $.error( 'Method ' +  method + ' does not exist on jQuery.Hazelnut' );
28         }    
29     };
30
31     /***************************************************************************
32      * Public methods
33      ***************************************************************************/
34
35     var methods = {
36
37         init : function ( options ) {
38             /* Default settings */
39             var options = $.extend( {
40                 'checkboxes': false
41             }, options);
42
43             return this.each(function() {
44                 var $this = $(this);
45                 /* Events */
46                 $(this).on('show.Datatables', methods.show);
47
48                 /* An object that will hold private variables and methods */
49                 var hazelnut = new Hazelnut (options);
50                 $(this).data('Hazelnut', hazelnut);
51
52                 var query_channel   = '/query/' + options.query_uuid + '/changed';
53                 var update_channel  = '/update-set/' + options.query_uuid;
54                 var results_channel = '/results/' + options.query_uuid + '/changed';
55
56                 $.subscribe(query_channel,  function(e, query) { hazelnut.set_query(query); });
57                 $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
58                 $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
59                 if (debug) console.log("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
60
61             }); // this.each
62         }, // init
63
64         destroy : function( ) {
65             return this.each(function() {
66                 var $this = $(this);
67                 var hazelnut = $this.data('Hazelnut');
68
69                 // Unbind all events using namespacing
70                 $(window).unbind('Hazelnut');
71
72                 // Remove associated data
73                 hazelnut.remove();
74                 $this.removeData('Hazelnut');
75             });
76         }, // destroy
77
78         show : function( ) {
79             var $this=$(this);
80             // xxx wtf. why [1] ? would expect 0...
81             var oTable = $($('.dataTable', $this)[1]).dataTable();
82             oTable.fnAdjustColumnSizing()
83     
84             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
85             $(this).each(function(i,elt) {
86                 if (jQuery(elt).hasClass('dataTables')) {
87                     var myDiv=jQuery('#hazelnut-' + this.id).parent();
88                     if(myDiv.height()==0) {
89                         var oTable=$('#hazelnut-' + this.id).dataTable();            
90                         oTable.fnDraw();
91                     }
92                 }
93             });
94         } // show
95
96     }; // var methods;
97
98
99     /***************************************************************************
100      * Hazelnut object
101      ***************************************************************************/
102     function Hazelnut(options) {
103         /* member variables */
104         this.options = options;
105         /* constructor */
106         this.table = null;
107         // xxx thierry : init this here - it was not, I expect this relied on set_query somehow..
108         //this.current_query = null;
109         this.current_query=manifold.find_query(this.options.query_uuid);
110         if (debug) console.log("Hazelnut constructor: have set current_query -> " + this.current_query);
111         this.query_update = null;
112         this.current_resources = Array();
113
114         var object = this;
115
116         /* Transforms the table into DataTable, and keep a pointer to it */
117         this.table = $('#hazelnut-' + options.plugin_uuid).dataTable({
118             // Customize the position of Datatables elements (length,filter,button,...)
119             // inspired from : 
120             // http://datatables.net/release-datatables/examples/advanced_init/dom_toolbar.html
121             // http://www.datatables.net/forums/discussion/3914/adding-buttons-to-header-or-footer/p1
122             //"sDom": 'lf<"#datatableSelectAll-'+ options.plugin_uuid+'">rtip',
123             sDom: '<"H"Tfr>t<"F"ip>',
124             bJQueryUI: true,
125             sPaginationType: 'full_numbers',
126             // Handle the null values & the error : Datatables warning Requested unknown parameter
127             // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
128             aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
129             bRetrieve: true,
130             // xxx this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
131             // sScrollX: '100%',       /* Horizontal scrolling */
132             bProcessing: true,      /* Loading */
133             fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
134                 $(nRow).attr('id', unfold.get_value(aData[3]));
135                 return nRow;
136             },
137             fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
138         });
139
140         /* Setup the SelectAll button in the dataTable header */
141         var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
142         oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
143         oSelectAll.button();
144         oSelectAll.css('font-size','11px');
145         oSelectAll.css('float','right');
146         oSelectAll.css('margin-right','15px');
147         oSelectAll.css('margin-bottom','5px');
148         oSelectAll.unbind('click');
149         oSelectAll.click(selectAll);
150
151         /* Add a filtering function to the current table 
152          * Note: we use closure to get access to the 'options'
153          */
154         $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
155             /* No filtering if the table does not match */
156             if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
157                 return true;
158             return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
159         });
160
161         /* methods */
162
163         this.set_query = function(query) {
164             var options = this.options;
165             /* Compare current and advertised query to get added and removed fields */
166             previous_query = this.current_query;
167             /* Save the query as the current query */
168             this.current_query = query;
169             if (debug) console.log("hazelnut.set_query, current_query is now -> " + this.current_query);
170             /* We check all necessary fields : in column editor I presume XXX */
171             // XXX ID naming has no plugin_uuid
172             if (typeof(query.fields) != 'undefined') {        
173                 $.each (query.fields, function(index, value) { 
174                     if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
175                         $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
176                 });
177             }
178             /*Process updates in filters / current_query must be updated before this call for filtering ! */
179             this.table.fnDraw();
180
181             /*
182              * Process updates in fields
183              */
184             if (typeof(query.fields) != 'undefined') {     
185                 /* DataTable Settings */
186                 var oSettings = this.table.dataTable().fnSettings();
187                 var cols = oSettings.aoColumns;
188                 var colnames = cols.map(function(x) {return x.sTitle});
189                 colnames = $.grep(colnames, function(value) {return value != "+/-";});
190
191                 if (previous_query == null) {
192                     var added_fields = query.fields;
193                     var removed_fields = colnames;            
194                     removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
195                 } else {
196                     var tmp = previous_query.diff_fields(query);
197                     var added_fields = tmp.added;
198                     var removed_fields = tmp.removed;
199                 }
200
201                 /* Hide/unhide columns to match added/removed fields */
202                 var object = this;
203                 $.each(added_fields, function (index, field) {            
204                     var index = object.getColIndex(field,cols);
205                     if(index != -1)
206                         object.table.fnSetColumnVis(index, true);
207                 });
208                 $.each(removed_fields, function (index, field) {
209                     var index = object.getColIndex(field,cols);
210                     if(index != -1)
211                         object.table.fnSetColumnVis(index, false);
212                 });            
213             }
214         }
215
216         this.set_resources = function(resources, instance) {
217             if (debug) console.log("entering hazelnut.set_resources");
218             var options = this.options;
219             var previous_resources = this.current_resources;
220             this.current_resources = resources;
221     
222             /* We uncheck all checkboxes ... */
223             $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
224             /* ... and check the ones specified in the resource list */
225             $.each(this.current_resources, function(index, urn) {
226                 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
227             });
228             
229         }
230
231         /**
232          * @brief Determine index of key in the table columns 
233          * @param key
234          * @param cols
235          */
236         this.getColIndex = function(key, cols) {
237             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
238             return (tabIndex.length > 0) ? tabIndex[0] : -1;
239         }
240     
241         /**
242          * @brief
243          * XXX will be removed/replaced
244          */
245         this.selected_changed = function(e, change) {
246             if (debug) console.log("entering hazelnut.selected_changed");
247             var actions = change.split("/");
248             if (actions.length > 1) {
249                 var oNodes = this.table.fnGetNodes();
250                 var myNode = $.grep(oNodes, function(value) {
251                     if (value.id == actions[1]) { return value; }
252                 });                
253                 if( myNode.length>0 ) {
254                     if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
255                         checked='';
256                     else
257                         checked="checked='checked' ";
258                     var newValue = this.checkbox(actions[1], 'node', checked, false);
259                     var columnPos = this.table.fnSettings().aoColumns.length - 1;
260                     this.table.fnUpdate(newValue, myNode[0], columnPos);
261                     this.table.fnDraw();
262                 }
263             }
264         }
265     
266         this.update_plugin = function(e, rows) {
267             // e.data is what we passed in second argument to subscribe
268             // so here it is the jquery object attached to the plugin <div>
269             var $plugindiv=e.data;
270             if (debug) console.log("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
271             // clear the spinning wheel: look up an ancestor that has the need-spin class
272             // do this before we might return
273             $plugindiv.closest('.need-spin').spin(false);
274
275             var options = this.options;
276             var hazelnut = this;
277     
278             if (rows.length==0) {
279                 if (debug) console.l ("empty result");
280                 this.table.html(unfold.errorDisplay("No Result"));   
281                 return;
282             } else if (typeof(rows[0].error) != 'undefined') {
283                 if (debug) console.log ("undefined result");
284                 this.table.html(unfold.errorDisplay(rows[0].error));
285                 return;
286             }
287             newlines = new Array();
288     
289             this.current_resources = Array();
290     
291             $.each(rows, function(index, obj) {
292                 newline = new Array();
293     
294                 // go through table headers to get column names we want
295                 // in order (we have temporarily hack some adjustments in names)
296                 var cols = hazelnut.table.fnSettings().aoColumns;
297                 var colnames = cols.map(function(x) {return x.sTitle})
298                 var nb_col = colnames.length;
299                 if (options.checkboxes)
300                     nb_col -= 1;
301                 for (var j = 0; j < nb_col; j++) {
302                     if (typeof colnames[j] == 'undefined') {
303                         newline.push('...');
304                     } else if (colnames[j] == 'hostname') {
305                         if (obj['type'] == 'resource,link')
306                             //TODO: we need to add source/destination for links
307                             newline.push('');
308                         else
309                             newline.push(obj['hostname']);
310                     } else {
311                         if (obj[colnames[j]])
312                             newline.push(obj[colnames[j]]);
313                         else
314                             newline.push('');
315                     }
316                 }
317     
318                 if (options.checkboxes) {
319                     var checked = '';
320                     if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
321                         checked = 'checked ';
322                         hazelnut.current_resources.push(obj['urn']);
323                     }
324                     // Use a key instead of hostname (hard coded...)
325                     newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
326                 }
327     
328                 newlines.push(newline);
329     
330     
331             });
332     
333             this.table.fnClearTable();
334             if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
335             this.table.fnAddData(newlines);
336     
337         };
338
339         this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
340             var result="";
341             /* Prefix id with plugin_uuid */
342             result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
343             result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
344             result +="></input>";
345             return result;
346         };
347     } // constructor
348
349     /***************************************************************************
350      * Private methods
351      ***************************************************************************/
352
353     /** 
354      * @brief Hazelnut filtering function
355      */
356     function hazelnut_filter (oSettings, aData, iDataIndex) {
357         var cur_query = this.current_query;
358         var ret = true;
359
360         /* We have an array of filters : a filter is an array (key op val) 
361          * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
362          *     can we exploit the data property somewhere ?
363          * field values (unless formatting) : aData
364          *     formatting should leave original data available in a hidden field
365          *
366          * The current line should validate all filters
367          */
368         $.each (cur_query.filters, function(index, filter) { 
369             /* XXX How to manage checkbox ? */
370             var key = filter[0]; 
371             var op = filter[1];
372             var value = filter[2];
373
374             /* Determine index of key in the table columns */
375             var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
376
377             /* Unknown key: no filtering */
378             if (typeof(col) == 'undefined')
379                 return;
380
381             col_value=unfold.get_value(aData[col]);
382             /* Test whether current filter is compatible with the column */
383             if (op == '=' || op == '==') {
384                 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
385                     ret = false;
386             }else if (op == '!=') {
387                 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
388                     ret = false;
389             } else if(op=='<') {
390                 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
391                     ret = false;
392             } else if(op=='>') {
393                 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
394                     ret = false;
395             } else if(op=='<=' || op=='≤') {
396                 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
397                     ret = false;
398             } else if(op=='>=' || op=='≥') {
399                 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
400                     ret = false;
401             }else{
402                 // How to break out of a loop ?
403                 alert("filter not supported");
404                 return false;
405             }
406
407         });
408         return ret;
409     }
410
411     function hazelnut_draw_callback() {
412         var options = this.options;
413         /* 
414          * Handle clicks on checkboxes: reassociate checkbox click every time
415          * the table is redrawn 
416          */
417         $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
418         $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
419
420         if (!this.table)
421             return;
422
423         /* Remove pagination if we show only a few results */
424         var wrapper = this.table; //.parent().parent().parent();
425         var rowsPerPage = this.table.fnSettings()._iDisplayLength;
426         var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
427         var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
428
429         if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
430             $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
431         } else {
432             $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
433         }
434
435         if ( rowsToShow <= minRowsPerPage ) {
436             $('.hazelnut_length', wrapper).css('visibility', 'hidden');
437         } else {
438             $('.hazelnut_length', wrapper).css('visibility', 'visible');
439         }
440     }
441
442     function check_click (e) {
443         var object = e.data.instance;
444         var value = this.value;
445
446         if (this.checked) {
447             object.current_resources.push(value);
448         } else {
449             tmp = $.grep(object.current_resources, function(x) { return x != value; });
450             object.current_resources = tmp;
451         }
452
453         /* inform slice that our selected resources have changed */
454         $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
455
456     }
457
458     function selectAll() {
459         // requires jQuery id
460         var uuid=this.id.split("-");
461         var oTable=$("#hazelnut-"+uuid[1]).dataTable();
462         // Function available in Hazelnut 1.9.x
463         // Filter : displayed data only
464         var filterData = oTable._('tr', {"filter":"applied"});   
465         /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
466         if(filterData.length<=100){
467             $.each(filterData, function(index, obj) {
468                 var last=$(obj).last();
469                 var key_value=unfold.get_value(last[0]);
470                 if(typeof($(last[0]).attr('checked'))=="undefined"){
471                     $.publish('selected', 'add/'+key_value);
472                 }
473             });
474         }
475     }
476     
477 })( jQuery );