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
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.
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 );
27 $.error( 'Method ' + method + ' does not exist on jQuery.Hazelnut' );
31 /***************************************************************************
33 ***************************************************************************/
37 init : function ( options ) {
38 /* Default settings */
39 var options = $.extend( {
43 return this.each(function() {
46 $(this).on('show.Datatables', methods.show);
48 /* An object that will hold private variables and methods */
49 var hazelnut = new Hazelnut (options);
50 $(this).data('Hazelnut', hazelnut);
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';
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);
64 destroy : function( ) {
65 return this.each(function() {
67 var hazelnut = $this.data('Hazelnut');
69 // Unbind all events using namespacing
70 $(window).unbind('Hazelnut');
72 // Remove associated data
74 $this.removeData('Hazelnut');
80 // xxx wtf. why [1] ? would expect 0...
81 if (debug) console.log("Hitting suspicious line in hazelnut.show");
82 var oTable = $($('.dataTable', $this)[1]).dataTable();
83 oTable.fnAdjustColumnSizing()
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();
100 /***************************************************************************
102 ***************************************************************************/
103 function Hazelnut(options) {
104 /* member variables */
105 this.options = options;
108 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
109 //this.current_query = null;
110 this.current_query=manifold.find_query(this.options.query_uuid);
111 if (debug) console.log("Hazelnut constructor: have set current_query -> " + this.current_query);
112 this.query_update = null;
113 this.current_resources = Array();
117 /* Transforms the table into DataTable, and keep a pointer to it */
119 // Customize the position of Datatables elements (length,filter,button,...)
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: "<'row-fluid'<'span4'l><'span7'f><'span1'r>>t<'row-fluid'<'span4'i><'span8'p>>",
123 sPaginationType: 'bootstrap',
124 // Handle the null values & the error : Datatables warning Requested unknown parameter
125 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
126 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
127 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
128 // sScrollX: '100%', /* Horizontal scrolling */
129 bProcessing: true, /* Loading */
130 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
132 // the intention here is that options.datatables_options as coming from the python object take precedence
133 $.extend(actual_options, options.datatables_options );
134 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
136 /* Setup the SelectAll button in the dataTable header */
137 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
138 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
140 oSelectAll.css('font-size','11px');
141 oSelectAll.css('float','right');
142 oSelectAll.css('margin-right','15px');
143 oSelectAll.css('margin-bottom','5px');
144 oSelectAll.unbind('click');
145 oSelectAll.click(selectAll);
147 /* Add a filtering function to the current table
148 * Note: we use closure to get access to the 'options'
150 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
151 /* No filtering if the table does not match */
152 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
154 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
159 this.set_query = function(query) {
160 var options = this.options;
161 /* Compare current and advertised query to get added and removed fields */
162 previous_query = this.current_query;
163 /* Save the query as the current query */
164 this.current_query = query;
165 if (debug) console.log("hazelnut.set_query, current_query is now -> " + this.current_query);
166 /* We check all necessary fields : in column editor I presume XXX */
167 // XXX ID naming has no plugin_uuid
168 if (typeof(query.fields) != 'undefined') {
169 $.each (query.fields, function(index, value) {
170 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
171 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
174 /*Process updates in filters / current_query must be updated before this call for filtering ! */
178 * Process updates in fields
180 if (typeof(query.fields) != 'undefined') {
181 /* DataTable Settings */
182 var oSettings = this.table.dataTable().fnSettings();
183 var cols = oSettings.aoColumns;
184 var colnames = cols.map(function(x) {return x.sTitle});
185 colnames = $.grep(colnames, function(value) {return value != "+/-";});
187 if (previous_query == null) {
188 var added_fields = query.fields;
189 var removed_fields = colnames;
190 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
192 var tmp = previous_query.diff_fields(query);
193 var added_fields = tmp.added;
194 var removed_fields = tmp.removed;
197 /* Hide/unhide columns to match added/removed fields */
199 $.each(added_fields, function (index, field) {
200 var index = object.getColIndex(field,cols);
202 object.table.fnSetColumnVis(index, true);
204 $.each(removed_fields, function (index, field) {
205 var index = object.getColIndex(field,cols);
207 object.table.fnSetColumnVis(index, false);
212 this.set_resources = function(resources, instance) {
213 if (debug) console.log("entering hazelnut.set_resources");
214 var options = this.options;
215 var previous_resources = this.current_resources;
216 this.current_resources = resources;
218 /* We uncheck all checkboxes ... */
219 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
220 /* ... and check the ones specified in the resource list */
221 $.each(this.current_resources, function(index, urn) {
222 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
228 * @brief Determine index of key in the table columns
232 this.getColIndex = function(key, cols) {
233 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
234 return (tabIndex.length > 0) ? tabIndex[0] : -1;
239 * XXX will be removed/replaced
241 this.selected_changed = function(e, change) {
242 if (debug) console.log("entering hazelnut.selected_changed");
243 var actions = change.split("/");
244 if (actions.length > 1) {
245 var oNodes = this.table.fnGetNodes();
246 var myNode = $.grep(oNodes, function(value) {
247 if (value.id == actions[1]) { return value; }
249 if( myNode.length>0 ) {
250 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
253 checked="checked='checked' ";
254 var newValue = this.checkbox(actions[1], 'node', checked, false);
255 var columnPos = this.table.fnSettings().aoColumns.length - 1;
256 this.table.fnUpdate(newValue, myNode[0], columnPos);
262 this.update_plugin = function(e, rows) {
263 // e.data is what we passed in second argument to subscribe
264 // so here it is the jquery object attached to the plugin <div>
265 var $plugindiv=e.data;
266 if (debug) console.log("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
267 // clear the spinning wheel: look up an ancestor that has the need-spin class
268 // do this before we might return
269 $plugindiv.closest('.need-spin').spin(false);
271 var options = this.options;
274 if (rows.length==0) {
275 if (debug) console.l ("empty result");
276 this.table.html(unfold.errorDisplay("No Result"));
278 } else if (typeof(rows[0].error) != 'undefined') {
279 if (debug) console.log ("undefined result");
280 this.table.html(unfold.errorDisplay(rows[0].error));
283 newlines = new Array();
285 this.current_resources = Array();
287 $.each(rows, function(index, obj) {
288 newline = new Array();
290 // go through table headers to get column names we want
291 // in order (we have temporarily hack some adjustments in names)
292 var cols = hazelnut.table.fnSettings().aoColumns;
293 var colnames = cols.map(function(x) {return x.sTitle})
294 var nb_col = colnames.length;
295 if (options.checkboxes)
297 for (var j = 0; j < nb_col; j++) {
298 if (typeof colnames[j] == 'undefined') {
300 } else if (colnames[j] == 'hostname') {
301 if (obj['type'] == 'resource,link')
302 //TODO: we need to add source/destination for links
305 newline.push(obj['hostname']);
307 if (obj[colnames[j]])
308 newline.push(obj[colnames[j]]);
314 if (options.checkboxes) {
316 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
317 checked = 'checked ';
318 hazelnut.current_resources.push(obj['urn']);
320 // Use a key instead of hostname (hard coded...)
321 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
324 newlines.push(newline);
329 this.table.fnClearTable();
330 if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
331 this.table.fnAddData(newlines);
335 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
337 /* Prefix id with plugin_uuid */
338 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
339 result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
340 result +="></input>";
345 /***************************************************************************
347 ***************************************************************************/
350 * @brief Hazelnut filtering function
352 function hazelnut_filter (oSettings, aData, iDataIndex) {
353 var cur_query = this.current_query;
356 /* We have an array of filters : a filter is an array (key op val)
357 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
358 * can we exploit the data property somewhere ?
359 * field values (unless formatting) : aData
360 * formatting should leave original data available in a hidden field
362 * The current line should validate all filters
364 $.each (cur_query.filters, function(index, filter) {
365 /* XXX How to manage checkbox ? */
368 var value = filter[2];
370 /* Determine index of key in the table columns */
371 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
373 /* Unknown key: no filtering */
374 if (typeof(col) == 'undefined')
377 col_value=unfold.get_value(aData[col]);
378 /* Test whether current filter is compatible with the column */
379 if (op == '=' || op == '==') {
380 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
382 }else if (op == '!=') {
383 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
386 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
389 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
391 } else if(op=='<=' || op=='≤') {
392 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
394 } else if(op=='>=' || op=='≥') {
395 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
398 // How to break out of a loop ?
399 alert("filter not supported");
407 function hazelnut_draw_callback() {
408 var options = this.options;
410 * Handle clicks on checkboxes: reassociate checkbox click every time
411 * the table is redrawn
413 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
414 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
419 /* Remove pagination if we show only a few results */
420 var wrapper = this.table; //.parent().parent().parent();
421 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
422 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
423 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
425 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
426 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
428 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
431 if ( rowsToShow <= minRowsPerPage ) {
432 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
434 $('.hazelnut_length', wrapper).css('visibility', 'visible');
438 function check_click (e) {
439 var object = e.data.instance;
440 var value = this.value;
443 object.current_resources.push(value);
445 tmp = $.grep(object.current_resources, function(x) { return x != value; });
446 object.current_resources = tmp;
449 /* inform slice that our selected resources have changed */
450 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
454 function selectAll() {
455 // requires jQuery id
456 var uuid=this.id.split("-");
457 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
458 // Function available in Hazelnut 1.9.x
459 // Filter : displayed data only
460 var filterData = oTable._('tr', {"filter":"applied"});
461 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
462 if(filterData.length<=100){
463 $.each(filterData, function(index, obj) {
464 var last=$(obj).last();
465 var key_value=unfold.get_value(last[0]);
466 if(typeof($(last[0]).attr('checked'))=="undefined"){
467 $.publish('selected', 'add/'+key_value);