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 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
121 sDom: "<'row-fluid'<'span1'r><'span4'l><'span7'f>>t<'row-fluid'<'span4'i><'span8'p>>",
122 sPaginationType: 'bootstrap',
123 // Handle the null values & the error : Datatables warning Requested unknown parameter
124 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
125 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
126 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
127 // sScrollX: '100%', /* Horizontal scrolling */
128 bProcessing: true, /* Loading */
129 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
131 // the intention here is that options.datatables_options as coming from the python object take precedence
132 $.extend(actual_options, options.datatables_options );
133 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
135 /* Setup the SelectAll button in the dataTable header */
136 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
137 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
139 oSelectAll.css('font-size','11px');
140 oSelectAll.css('float','right');
141 oSelectAll.css('margin-right','15px');
142 oSelectAll.css('margin-bottom','5px');
143 oSelectAll.unbind('click');
144 oSelectAll.click(selectAll);
146 /* Add a filtering function to the current table
147 * Note: we use closure to get access to the 'options'
149 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
150 /* No filtering if the table does not match */
151 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
153 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
158 this.set_query = function(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) console.log("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);
173 /*Process updates in filters / current_query must be updated before this call for filtering ! */
177 * Process updates in fields
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 != "+/-";});
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});
191 var tmp = previous_query.diff_fields(query);
192 var added_fields = tmp.added;
193 var removed_fields = tmp.removed;
196 /* Hide/unhide columns to match added/removed fields */
198 $.each(added_fields, function (index, field) {
199 var index = object.getColIndex(field,cols);
201 object.table.fnSetColumnVis(index, true);
203 $.each(removed_fields, function (index, field) {
204 var index = object.getColIndex(field,cols);
206 object.table.fnSetColumnVis(index, false);
211 this.set_resources = function(resources, instance) {
212 if (debug) console.log("entering hazelnut.set_resources");
213 var options = this.options;
214 var previous_resources = this.current_resources;
215 this.current_resources = resources;
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)
227 * @brief Determine index of key in the table columns
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;
238 * XXX will be removed/replaced
240 this.selected_changed = function(e, change) {
241 if (debug) console.log("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; }
248 if( myNode.length>0 ) {
249 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
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);
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) console.log("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);
270 var options = this.options;
273 if (rows.length==0) {
274 if (debug) console.l ("empty result");
275 this.table.html(unfold.errorDisplay("No Result"));
277 } else if (typeof(rows[0].error) != 'undefined') {
278 if (debug) console.log ("undefined result");
279 this.table.html(unfold.errorDisplay(rows[0].error));
282 newlines = new Array();
284 this.current_resources = Array();
286 $.each(rows, function(index, obj) {
287 newline = new Array();
289 // go through table headers to get column names we want
290 // in order (we have temporarily hack some adjustments in names)
291 var cols = hazelnut.table.fnSettings().aoColumns;
292 var colnames = cols.map(function(x) {return x.sTitle})
293 var nb_col = colnames.length;
294 if (options.checkboxes)
296 for (var j = 0; j < nb_col; j++) {
297 if (typeof colnames[j] == 'undefined') {
299 } else if (colnames[j] == 'hostname') {
300 if (obj['type'] == 'resource,link')
301 //TODO: we need to add source/destination for links
304 newline.push(obj['hostname']);
306 if (obj[colnames[j]])
307 newline.push(obj[colnames[j]]);
313 if (options.checkboxes) {
315 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
316 checked = 'checked ';
317 hazelnut.current_resources.push(obj['urn']);
319 // Use a key instead of hostname (hard coded...)
320 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
323 newlines.push(newline);
328 this.table.fnClearTable();
329 if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
330 this.table.fnAddData(newlines);
334 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
336 /* Prefix id with plugin_uuid */
337 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
338 result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
339 result +="></input>";
344 /***************************************************************************
346 ***************************************************************************/
349 * @brief Hazelnut filtering function
351 function hazelnut_filter (oSettings, aData, iDataIndex) {
352 var cur_query = this.current_query;
355 /* We have an array of filters : a filter is an array (key op val)
356 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
357 * can we exploit the data property somewhere ?
358 * field values (unless formatting) : aData
359 * formatting should leave original data available in a hidden field
361 * The current line should validate all filters
363 $.each (cur_query.filters, function(index, filter) {
364 /* XXX How to manage checkbox ? */
367 var value = filter[2];
369 /* Determine index of key in the table columns */
370 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
372 /* Unknown key: no filtering */
373 if (typeof(col) == 'undefined')
376 col_value=unfold.get_value(aData[col]);
377 /* Test whether current filter is compatible with the column */
378 if (op == '=' || op == '==') {
379 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
381 }else if (op == '!=') {
382 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
385 if ( parseFloat(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")
390 } else if(op=='<=' || op=='≤') {
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")
397 // How to break out of a loop ?
398 alert("filter not supported");
406 function hazelnut_draw_callback() {
407 var options = this.options;
409 * Handle clicks on checkboxes: reassociate checkbox click every time
410 * the table is redrawn
412 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
413 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
418 /* Remove pagination if we show only a few results */
419 var wrapper = this.table; //.parent().parent().parent();
420 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
421 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
422 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
424 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
425 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
427 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
430 if ( rowsToShow <= minRowsPerPage ) {
431 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
433 $('.hazelnut_length', wrapper).css('visibility', 'visible');
437 function check_click (e) {
438 var object = e.data.instance;
439 var value = this.value;
442 object.current_resources.push(value);
444 tmp = $.grep(object.current_resources, function(x) { return x != value; });
445 object.current_resources = tmp;
448 /* inform slice that our selected resources have changed */
449 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
453 function selectAll() {
454 // requires jQuery id
455 var uuid=this.id.split("-");
456 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
457 // Function available in Hazelnut 1.9.x
458 // Filter : displayed data only
459 var filterData = oTable._('tr', {"filter":"applied"});
460 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
461 if(filterData.length<=100){
462 $.each(filterData, function(index, obj) {
463 var last=$(obj).last();
464 var key_value=unfold.get_value(last[0]);
465 if(typeof($(last[0]).attr('checked'))=="undefined"){
466 $.publish('selected', 'add/'+key_value);