2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012 UPMC Sorbonne Universite - INRIA
8 * It's a best practice to pass jQuery to an IIFE (Immediately Invoked Function
9 * Expression) that maps it to the dollar sign so it can't be overwritten by
10 * another library in the scope of its execution.
18 $.fn.Hazelnut = function( method ) {
19 if ( methods[method] ) {
20 return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
21 } else if ( typeof method === 'object' || ! method ) {
22 return methods.init.apply( this, arguments );
24 $.error( 'Method ' + method + ' does not exist on jQuery.Hazelnut' );
28 /***************************************************************************
30 ***************************************************************************/
34 init : function ( options ) {
35 /* Default settings */
36 var options = $.extend( {
40 return this.each(function() {
43 $this.on('show.Datatables', methods.show);
45 /* An object that will hold private variables and methods */
46 var hazelnut = new Hazelnut (options);
47 $this.data('Hazelnut', hazelnut);
49 var query_channel = '/query/' + options.query_uuid + '/changed';
50 var update_channel = '/update-set/' + options.query_uuid;
51 var results_channel = '/results/' + options.query_uuid + '/changed';
54 $.subscribe(query_channel, function(e, query) { hazelnut.set_query(query); });
56 $.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) messages.debug("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) messages.debug("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;
106 // xxx thierry : initialize 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) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
110 this.query_update = null;
111 this.current_resources = Array();
115 /* Transforms the table into DataTable, and keep a pointer to it */
117 // Customize the position of Datatables elements (length,filter,button,...)
118 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
119 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
120 sPaginationType: 'bootstrap',
121 // Handle the null values & the error : Datatables warning Requested unknown parameter
122 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
123 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
124 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
125 // sScrollX: '100%', /* Horizontal scrolling */
126 bProcessing: true, /* Loading */
127 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
129 // the intention here is that options.datatables_options as coming from the python object take precedence
130 $.extend(actual_options, options.datatables_options );
131 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
133 /* Setup the SelectAll button in the dataTable header */
134 /* xxx not sure this is still working */
135 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
136 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
138 oSelectAll.css('font-size','11px');
139 oSelectAll.css('float','right');
140 oSelectAll.css('margin-right','15px');
141 oSelectAll.css('margin-bottom','5px');
142 oSelectAll.unbind('click');
143 oSelectAll.click(selectAll);
145 /* Add a filtering function to the current table
146 * Note: we use closure to get access to the 'options'
148 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
149 /* No filtering if the table does not match */
150 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
152 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
157 this.set_query = function(query) {
158 var options = this.options;
159 /* Compare current and advertised query to get added and removed fields */
160 previous_query = this.current_query;
161 /* Save the query as the current query */
162 this.current_query = query;
163 if (debug) messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
164 /* We check all necessary fields : in column editor I presume XXX */
165 // XXX ID naming has no plugin_uuid
166 if (typeof(query.fields) != 'undefined') {
167 $.each (query.fields, function(index, value) {
168 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
169 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
172 /*Process updates in filters / current_query must be updated before this call for filtering ! */
176 * Process updates in fields
178 if (typeof(query.fields) != 'undefined') {
179 /* DataTable Settings */
180 var oSettings = this.table.dataTable().fnSettings();
181 var cols = oSettings.aoColumns;
182 var colnames = cols.map(function(x) {return x.sTitle});
183 colnames = $.grep(colnames, function(value) {return value != "+/-";});
185 if (previous_query == null) {
186 var added_fields = query.fields;
187 var removed_fields = colnames;
188 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
190 var tmp = previous_query.diff_fields(query);
191 var added_fields = tmp.added;
192 var removed_fields = tmp.removed;
195 /* Hide/unhide columns to match added/removed fields */
197 $.each(added_fields, function (index, field) {
198 var index = object.getColIndex(field,cols);
200 object.table.fnSetColumnVis(index, true);
202 $.each(removed_fields, function (index, field) {
203 var index = object.getColIndex(field,cols);
205 object.table.fnSetColumnVis(index, false);
210 this.set_resources = function(resources, instance) {
211 if (debug) messages.debug("entering hazelnut.set_resources");
212 var options = this.options;
213 var previous_resources = this.current_resources;
214 this.current_resources = resources;
216 /* We uncheck all checkboxes ... */
217 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
218 /* ... and check the ones specified in the resource list */
219 $.each(this.current_resources, function(index, urn) {
220 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
226 * @brief Determine index of key in the table columns
230 this.getColIndex = function(key, cols) {
231 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
232 return (tabIndex.length > 0) ? tabIndex[0] : -1;
237 * XXX will be removed/replaced
239 this.selected_changed = function(e, change) {
240 if (debug) messages.debug("entering hazelnut.selected_changed");
241 var actions = change.split("/");
242 if (actions.length > 1) {
243 var oNodes = this.table.fnGetNodes();
244 var myNode = $.grep(oNodes, function(value) {
245 if (value.id == actions[1]) { return value; }
247 if( myNode.length>0 ) {
248 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
251 checked="checked='checked' ";
252 var newValue = this.checkbox(actions[1], 'node', checked, false);
253 var columnPos = this.table.fnSettings().aoColumns.length - 1;
254 this.table.fnUpdate(newValue, myNode[0], columnPos);
260 this.update_plugin = function(e, rows) {
261 // e.data is what we passed in second argument to subscribe
262 // so here it is the jquery object attached to the plugin <div>
263 var $plugindiv=e.data;
264 if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
265 // clear the spinning wheel: look up an ancestor that has the need-spin class
266 // do this before we might return
267 $plugindiv.closest('.need-spin').spin(false);
269 var options = this.options;
272 if (rows.length==0) {
273 if (debug) messages.debug("Empty result on hazelnut " + domid);
274 var placeholder=$(this.table).find("td.dataTables_empty");
275 console.log("placeholder "+placeholder);
276 if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
277 else this.table.html(unfold.warning("Empty result"));
279 } else if (typeof(rows[0].error) != 'undefined') {
280 // we now should have another means to report errors that this inline/embedded hack
281 if (debug) messages.error ("undefined result on " + domid + " - should not happen anymore");
282 this.table.html(unfold.error(rows[0].error));
285 newlines = new Array();
287 this.current_resources = Array();
289 $.each(rows, function(index, obj) {
290 newline = new Array();
292 // go through table headers to get column names we want
293 // in order (we have temporarily hack some adjustments in names)
294 var cols = hazelnut.table.fnSettings().aoColumns;
295 var colnames = cols.map(function(x) {return x.sTitle})
296 var nb_col = colnames.length;
297 if (options.checkboxes)
299 for (var j = 0; j < nb_col; j++) {
300 if (typeof colnames[j] == 'undefined') {
302 } else if (colnames[j] == 'hostname') {
303 if (obj['type'] == 'resource,link')
304 //TODO: we need to add source/destination for links
307 newline.push(obj['hostname']);
309 if (obj[colnames[j]])
310 newline.push(obj[colnames[j]]);
316 if (options.checkboxes) {
318 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
319 checked = 'checked ';
320 hazelnut.current_resources.push(obj['urn']);
322 // Use a key instead of hostname (hard coded...)
323 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
326 newlines.push(newline);
331 this.table.fnClearTable();
332 if (debug) messages.debug("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 + "-" + unfold.get_value(header) + "'";
341 result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
342 result +="></input>";
347 /***************************************************************************
349 * xxx I'm not sure why this should not be methods in the Hazelnut class above
350 ***************************************************************************/
353 * @brief Hazelnut filtering function
355 function hazelnut_filter (oSettings, aData, iDataIndex) {
356 var cur_query = this.current_query;
359 /* We have an array of filters : a filter is an array (key op val)
360 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
361 * can we exploit the data property somewhere ?
362 * field values (unless formatting) : aData
363 * formatting should leave original data available in a hidden field
365 * The current line should validate all filters
367 $.each (cur_query.filters, function(index, filter) {
368 /* XXX How to manage checkbox ? */
371 var value = filter[2];
373 /* Determine index of key in the table columns */
374 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
376 /* Unknown key: no filtering */
377 if (typeof(col) == 'undefined')
380 col_value=unfold.get_value(aData[col]);
381 /* Test whether current filter is compatible with the column */
382 if (op == '=' || op == '==') {
383 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
385 }else if (op == '!=') {
386 if ( 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")
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")
397 } else if(op=='>=' || op=='≥') {
398 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
401 // How to break out of a loop ?
402 alert("filter not supported");
410 function hazelnut_draw_callback() {
411 var options = this.options;
413 * Handle clicks on checkboxes: reassociate checkbox click every time
414 * the table is redrawn
416 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
417 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
422 /* Remove pagination if we show only a few results */
423 var wrapper = this.table; //.parent().parent().parent();
424 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
425 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
426 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
428 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
429 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
431 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
434 if ( rowsToShow <= minRowsPerPage ) {
435 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
437 $('.hazelnut_length', wrapper).css('visibility', 'visible');
441 function check_click (e) {
442 var object = e.data.instance;
443 var value = this.value;
446 object.current_resources.push(value);
448 tmp = $.grep(object.current_resources, function(x) { return x != value; });
449 object.current_resources = tmp;
452 /* inform slice that our selected resources have changed */
453 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
457 function selectAll() {
458 // requires jQuery id
459 var uuid=this.id.split("-");
460 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
461 // Function available in Hazelnut 1.9.x
462 // Filter : displayed data only
463 var filterData = oTable._('tr', {"filter":"applied"});
464 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
465 if(filterData.length<=100){
466 $.each(filterData, function(index, obj) {
467 var last=$(obj).last();
468 var key_value=unfold.get_value(last[0]);
469 if(typeof($(last[0]).attr('checked'))=="undefined"){
470 $.publish('selected', 'add/'+key_value);