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 var oTable = $($('.dataTable', $this)[1]).dataTable();
82 oTable.fnAdjustColumnSizing()
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();
99 /***************************************************************************
101 ***************************************************************************/
102 function Hazelnut(options) {
103 /* member variables */
104 this.options = options;
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();
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,...)
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>',
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' ]}],
130 sScrollX: '100%', /* Horizontal scrolling */
131 bProcessing: true, /* Loading */
132 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
133 $(nRow).attr('id', get_value(aData[3]));
136 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
139 /* Setup the SelectAll button in the dataTable header */
140 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
141 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
143 oSelectAll.css('font-size','11px');
144 oSelectAll.css('float','right');
145 oSelectAll.css('margin-right','15px');
146 oSelectAll.css('margin-bottom','5px');
147 oSelectAll.unbind('click');
148 oSelectAll.click(selectAll);
150 /* Add a filtering function to the current table
151 * Note: we use closure to get access to the 'options'
153 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
154 /* No filtering if the table does not match */
155 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
157 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
162 this.set_query = function(query) {
163 var options = this.options;
164 /* Compare current and advertised query to get added and removed fields */
165 previous_query = this.current_query;
166 /* Save the query as the current query */
167 this.current_query = query;
168 if (debug) console.log("hazelnut.set_query, current_query is now -> " + this.current_query);
169 /* We check all necessary fields : in column editor I presume XXX */
170 // XXX ID naming has no plugin_uuid
171 if (typeof(query.fields) != 'undefined') {
172 $.each (query.fields, function(index, value) {
173 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
174 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
177 /*Process updates in filters / current_query must be updated before this call for filtering ! */
181 * Process updates in fields
183 if (typeof(query.fields) != 'undefined') {
184 /* DataTable Settings */
185 var oSettings = this.table.dataTable().fnSettings();
186 var cols = oSettings.aoColumns;
187 var colnames = cols.map(function(x) {return x.sTitle});
188 colnames = $.grep(colnames, function(value) {return value != "+/-";});
190 if (previous_query == null) {
191 var added_fields = query.fields;
192 var removed_fields = colnames;
193 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
195 var tmp = previous_query.diff_fields(query);
196 var added_fields = tmp.added;
197 var removed_fields = tmp.removed;
200 /* Hide/unhide columns to match added/removed fields */
202 $.each(added_fields, function (index, field) {
203 var index = object.getColIndex(field,cols);
205 object.table.fnSetColumnVis(index, true);
207 $.each(removed_fields, function (index, field) {
208 var index = object.getColIndex(field,cols);
210 object.table.fnSetColumnVis(index, false);
215 this.set_resources = function(resources, instance) {
216 if (debug) console.log("entering hazelnut.set_resources");
217 var options = this.options;
218 var previous_resources = this.current_resources;
219 this.current_resources = resources;
221 /* We uncheck all checkboxes ... */
222 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
223 /* ... and check the ones specified in the resource list */
224 $.each(this.current_resources, function(index, urn) {
225 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
231 * @brief Determine index of key in the table columns
235 this.getColIndex = function(key, cols) {
236 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
237 return (tabIndex.length > 0) ? tabIndex[0] : -1;
242 * XXX will be removed/replaced
244 this.selected_changed = function(e, change) {
245 if (debug) console.log("entering hazelnut.selected_changed");
246 var actions = change.split("/");
247 if (actions.length > 1) {
248 var oNodes = this.table.fnGetNodes();
249 var myNode = $.grep(oNodes, function(value) {
250 if (value.id == actions[1]) { return value; }
252 if( myNode.length>0 ) {
253 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
256 checked="checked='checked' ";
257 var newValue = this.checkbox(actions[1], 'node', checked, false);
258 var columnPos = this.table.fnSettings().aoColumns.length - 1;
259 this.table.fnUpdate(newValue, myNode[0], columnPos);
265 this.update_plugin = function(e, rows) {
266 // e.data is what we passed in second argument to subscribe
267 // so here it is the jquery object attached to the plugin <div>
268 var $plugindiv=e.data;
269 if (debug) console.log("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
270 // clear the spinning wheel: look up an ancestor that has the need-spin class
271 // do this before we might return
272 $plugindiv.closest('.need-spin').spin(false);
274 var options = this.options;
277 if (rows.length==0) {
278 if (debug) console.l ("empty result");
279 this.table.html(errorDisplay("No Result"));
281 } else if (typeof(rows[0].error) != 'undefined') {
282 if (debug) console.log ("undefined result");
283 this.table.html(errorDisplay(rows[0].error));
286 newlines = new Array();
288 this.current_resources = Array();
290 $.each(rows, function(index, obj) {
291 newline = new Array();
293 // go through table headers to get column names we want
294 // in order (we have temporarily hack some adjustments in names)
295 var cols = hazelnut.table.fnSettings().aoColumns;
296 var colnames = cols.map(function(x) {return x.sTitle})
297 var nb_col = colnames.length;
298 if (options.checkboxes)
300 for (var j = 0; j < nb_col; j++) {
301 if (typeof colnames[j] == 'undefined') {
303 } else if (colnames[j] == 'hostname') {
304 if (obj['type'] == 'resource,link')
305 //TODO: we need to add source/destination for links
308 newline.push(obj['hostname']);
310 if (obj[colnames[j]])
311 newline.push(obj[colnames[j]]);
317 if (options.checkboxes) {
319 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
320 checked = 'checked ';
321 hazelnut.current_resources.push(obj['urn']);
323 // Use a key instead of hostname (hard coded...)
324 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
327 newlines.push(newline);
332 if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
333 this.table.fnAddData(newlines);
337 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
339 /* Prefix id with plugin_uuid */
340 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + get_value(header) + "'";
341 result += " name='" + get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + get_value(header) + "'";
342 result +="></input>";
347 /***************************************************************************
349 ***************************************************************************/
352 * @brief Hazelnut filtering function
354 function hazelnut_filter (oSettings, aData, iDataIndex) {
355 var cur_query = this.current_query;
358 /* We have an array of filters : a filter is an array (key op val)
359 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
360 * can we exploit the data property somewhere ?
361 * field values (unless formatting) : aData
362 * formatting should leave original data available in a hidden field
364 * The current line should validate all filters
366 $.each (cur_query.filters, function(index, filter) {
367 /* XXX How to manage checkbox ? */
370 var value = filter[2];
372 /* Determine index of key in the table columns */
373 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
375 /* Unknown key: no filtering */
376 if (typeof(col) == 'undefined')
379 col_value=get_value(aData[col]);
380 /* Test whether current filter is compatible with the column */
381 if (op == '=' || op == '==') {
382 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
384 }else if (op == '!=') {
385 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
388 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
391 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
393 } else if(op=='<=' || op=='≤') {
394 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
396 } else if(op=='>=' || op=='≥') {
397 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
400 // How to break out of a loop ?
401 alert("filter not supported");
409 function hazelnut_draw_callback() {
410 var options = this.options;
412 * Handle clicks on checkboxes: reassociate checkbox click every time
413 * the table is redrawn
415 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
416 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
421 /* Remove pagination if we show only a few results */
422 var wrapper = this.table; //.parent().parent().parent();
423 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
424 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
425 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
427 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
428 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
430 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
433 if ( rowsToShow <= minRowsPerPage ) {
434 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
436 $('.hazelnut_length', wrapper).css('visibility', 'visible');
440 function check_click (e) {
441 var object = e.data.instance;
442 var value = this.value;
445 object.current_resources.push(value);
447 tmp = $.grep(object.current_resources, function(x) { return x != value; });
448 object.current_resources = tmp;
451 /* inform slice that our selected resources have changed */
452 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
456 function selectAll() {
457 // requires jQuery id
458 var uuid=this.id.split("-");
459 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
460 // Function available in Hazelnut 1.9.x
461 // Filter : displayed data only
462 var filterData = oTable._('tr', {"filter":"applied"});
463 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
464 if(filterData.length<=100){
465 $.each(filterData, function(index, obj) {
466 var last=$(obj).last();
467 var key_value=get_value(last[0]);
468 if(typeof($(last[0]).attr('checked'))=="undefined"){
469 $.publish('selected', 'add/'+key_value);