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); });
63 destroy : function( ) {
64 return this.each(function() {
66 var hazelnut = $this.data('Hazelnut');
68 // Unbind all events using namespacing
69 $(window).unbind('Hazelnut');
71 // Remove associated data
73 $this.removeData('Hazelnut');
79 // xxx wtf. why [1] ? would expect 0...
80 var oTable = $($('.dataTable', $this)[1]).dataTable();
81 oTable.fnAdjustColumnSizing()
83 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
84 $(this).each(function(i,elt) {
85 if (jQuery(elt).hasClass('dataTables')) {
86 var myDiv=jQuery('#hazelnut-' + this.id).parent();
87 if(myDiv.height()==0) {
88 var oTable=$('#hazelnut-' + this.id).dataTable();
98 /***************************************************************************
100 ***************************************************************************/
101 function Hazelnut(options) {
102 /* member variables */
103 this.options = options;
106 // xxx thierry : init 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) console.log("Hazelnut constructor: have set current_query -> " + this.current_query);
110 this.query_update = null;
111 this.current_resources = Array();
115 /* Transforms the table into DataTable, and keep a pointer to it */
116 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable({
117 // Customize the position of Datatables elements (length,filter,button,...)
119 // http://datatables.net/release-datatables/examples/advanced_init/dom_toolbar.html
120 // http://www.datatables.net/forums/discussion/3914/adding-buttons-to-header-or-footer/p1
121 //"sDom": 'lf<"#datatableSelectAll-'+ options.plugin_uuid+'">rtip',
122 sDom: '<"H"Tfr>t<"F"ip>',
124 sPaginationType: 'full_numbers',
125 // Handle the null values & the error : Datatables warning Requested unknown parameter
126 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
127 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
129 sScrollX: '100%', /* Horizontal scrolling */
130 bProcessing: true, /* Loading */
131 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
132 $(nRow).attr('id', get_value(aData[3]));
135 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
138 /* Setup the SelectAll button in the dataTable header */
139 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
140 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
142 oSelectAll.css('font-size','11px');
143 oSelectAll.css('float','right');
144 oSelectAll.css('margin-right','15px');
145 oSelectAll.css('margin-bottom','5px');
146 oSelectAll.unbind('click');
147 oSelectAll.click(selectAll);
149 /* Spinner (could be done when the query is received = a query is in progress, also for update) */
150 // $('#' + options.plugin_uuid).spin()
152 /* Add a filtering function to the current table
153 * Note: we use closure to get access to the 'options'
155 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
156 /* No filtering if the table does not match */
157 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
159 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
164 this.set_query = function(query) {
165 if (debug) console.log("entering set_query");
166 var o = this.options;
167 /* Compare current and advertised query to get added and removed fields */
168 previous_query = this.current_query;
169 /* Save the query as the current query */
170 this.current_query = query;
171 if (debug) console.log("set_query, current_query is now -> " + this.current_query);
172 /* We check all necessary fields : in column editor I presume XXX */
173 // XXX ID naming has no plugin_uuid
174 if (typeof(query.fields) != 'undefined') {
175 $.each (query.fields, function(index, value) {
176 if (!$('#hazelnut-checkbox-' + o.plugin_uuid + "-" + value).attr('checked'))
177 $('#hazelnut-checkbox-' + o.plugin_uuid + "-" + value).attr('checked', true);
180 /*Process updates in filters / current_query must be updated before this call for filtering ! */
184 * Process updates in fields
186 if (typeof(query.fields) != 'undefined') {
187 /* DataTable Settings */
188 var oSettings = this.table.dataTable().fnSettings();
189 var cols = oSettings.aoColumns;
190 var colnames = cols.map(function(x) {return x.sTitle});
191 colnames = $.grep(colnames, function(value) {return value != "+/-";});
193 if (previous_query == null) {
194 var added_fields = query.fields;
195 var removed_fields = colnames;
196 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
198 var tmp = previous_query.diff_fields(query);
199 var added_fields = tmp.added;
200 var removed_fields = tmp.removed;
203 /* Hide/unhide columns to match added/removed fields */
205 $.each(added_fields, function (index, field) {
206 var index = object.getColIndex(field,cols);
208 object.table.fnSetColumnVis(index, true);
210 $.each(removed_fields, function (index, field) {
211 var index = object.getColIndex(field,cols);
213 object.table.fnSetColumnVis(index, false);
218 this.set_resources = function(resources, instance) {
219 if (debug) console.log("entering set_resources");
220 var o = this.options;
221 var previous_resources = this.current_resources;
222 this.current_resources = resources;
224 /* We uncheck all checkboxes ... */
225 $('hazelnut-checkbox-' + o.plugin_uuid).attr('checked', false);
226 /* ... and check the ones specified in the resource list */
227 $.each(this.current_resources, function(index, urn) {
228 $('#hazelnut-checkbox-' + o.plugin_uuid + "-" + urn).attr('checked', true)
234 * @brief Determine index of key in the table columns
238 this.getColIndex = function(key, cols) {
239 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
240 return (tabIndex.length > 0) ? tabIndex[0] : -1;
245 * XXX will be removed/replaced
247 this.selected_changed = function(e, change) {
248 if (debug) console.log("entering selected_changed");
249 var actions = change.split("/");
250 if (actions.length > 1) {
251 var oNodes = this.table.fnGetNodes();
252 var myNode = $.grep(oNodes, function(value) {
253 if (value.id == actions[1]) { return value; }
255 if( myNode.length>0 ) {
256 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
259 checked="checked='checked' ";
260 var newValue = this.checkbox(actions[1], 'node', checked, false);
261 var columnPos = this.table.fnSettings().aoColumns.length - 1;
262 this.table.fnUpdate(newValue, myNode[0], columnPos);
268 this.update_plugin = function(e, rows) {
269 if (debug) console.log("entering update_plugin");
270 // e.data is what we passed in second argument to subscribe
271 // so here it is the jquery object attached to the plugin <div>
272 var $plugindiv=e.data;
273 // clear the spinning wheel: look up an ancestor that has the need-spin class
274 // do this before we might return
275 $plugindiv.closest('.need-spin').spin(false);
277 var options = this.options;
280 if (rows.length==0) {
281 this.table.html(errorDisplay("No Result"));
284 if (typeof(rows[0].error) != 'undefined') {
285 this.table.html(errorDisplay(rows[0].error));
289 newlines = new Array();
291 this.current_resources = Array();
293 $.each(rows, function(index, obj) {
294 newline = new Array();
296 // go through table headers to get column names we want
297 // in order (we have temporarily hack some adjustments in names)
298 var cols = hazelnut.table.fnSettings().aoColumns;
299 var colnames = cols.map(function(x) {return x.sTitle})
300 var nb_col = colnames.length;
301 if (options.checkboxes)
303 for (var j = 0; j < nb_col; j++) {
304 if (typeof colnames[j] == 'undefined') {
306 } else if (colnames[j] == 'hostname') {
307 if (obj['type'] == 'resource,link')
308 //TODO: we need to add source/destination for links
311 newline.push(obj['hostname']);
313 if (obj[colnames[j]])
314 newline.push(obj[colnames[j]]);
320 if (options.checkboxes) {
322 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
323 checked = 'checked ';
324 hazelnut.current_resources.push(obj['urn']);
326 // Use a key instead of hostname (hard coded...)
327 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
330 newlines.push(newline);
335 // console.log ("end of each, newlines=" + newlines.length);
336 this.table.fnAddData(newlines);
338 // console.log (" exiting update_plugin = ");
341 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
343 /* Prefix id with plugin_uuid */
344 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + get_value(header) + "'";
345 result += " name='" + get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + get_value(header) + "'";
346 result +="></input>";
351 /***************************************************************************
353 ***************************************************************************/
356 * @brief Hazelnut filtering function
358 function hazelnut_filter (oSettings, aData, iDataIndex) {
359 var cur_query = this.current_query;
362 /* We have an array of filters : a filter is an array (key op val)
363 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
364 * can we exploit the data property somewhere ?
365 * field values (unless formatting) : aData
366 * formatting should leave original data available in a hidden field
368 * The current line should validate all filters
370 $.each (cur_query.filters, function(index, filter) {
371 /* XXX How to manage checkbox ? */
374 var value = filter[2];
376 /* Determine index of key in the table columns */
377 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
379 /* Unknown key: no filtering */
380 if (typeof(col) == 'undefined')
383 col_value=get_value(aData[col]);
384 /* Test whether current filter is compatible with the column */
385 if (op == '=' || op == '==') {
386 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
388 }else if (op == '!=') {
389 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
392 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
395 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
397 } else if(op=='<=' || op=='≤') {
398 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
400 } else if(op=='>=' || op=='≥') {
401 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
404 // How to break out of a loop ?
405 alert("filter not supported");
413 function hazelnut_draw_callback() {
414 var options = this.options;
416 * Handle clicks on checkboxes: reassociate checkbox click every time
417 * the table is redrawn
419 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
420 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
425 /* Remove pagination if we show only a few results */
426 var wrapper = this.table; //.parent().parent().parent();
427 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
428 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
429 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
431 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
432 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
434 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
437 if ( rowsToShow <= minRowsPerPage ) {
438 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
440 $('.hazelnut_length', wrapper).css('visibility', 'visible');
444 function check_click (e) {
445 var object = e.data.instance;
446 var value = this.value;
449 object.current_resources.push(value);
451 tmp = $.grep(object.current_resources, function(x) { return x != value; });
452 object.current_resources = tmp;
455 /* inform slice that our selected resources have changed */
456 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
460 function selectAll() {
461 // requires jQuery id
462 var uuid=this.id.split("-");
463 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
464 // Function available in Hazelnut 1.9.x
465 // Filter : displayed data only
466 var filterData = oTable._('tr', {"filter":"applied"});
467 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
468 if(filterData.length<=100){
469 $.each(filterData, function(index, obj) {
470 var last=$(obj).last();
471 var key_value=get_value(last[0]);
472 if(typeof($(last[0]).attr('checked'))=="undefined"){
473 $.publish('selected', 'add/'+key_value);