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';
53 $.subscribe(query_channel, function(e, query) { hazelnut.set_query(query); });
54 $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
55 $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
56 if (debug) messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
61 destroy : function( ) {
62 return this.each(function() {
64 var hazelnut = $this.data('Hazelnut');
66 // Unbind all events using namespacing
67 $(window).unbind('Hazelnut');
69 // Remove associated data
71 $this.removeData('Hazelnut');
77 // xxx wtf. why [1] ? would expect 0...
78 if (debug) messages.debug("Hitting suspicious line in hazelnut.show");
79 var oTable = $($('.dataTable', $this)[1]).dataTable();
80 oTable.fnAdjustColumnSizing()
82 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
83 $(this).each(function(i,elt) {
84 if (jQuery(elt).hasClass('dataTables')) {
85 var myDiv=jQuery('#hazelnut-' + this.id).parent();
86 if(myDiv.height()==0) {
87 var oTable=$('#hazelnut-' + this.id).dataTable();
97 /***************************************************************************
99 ***************************************************************************/
100 function Hazelnut(options) {
101 /* member variables */
102 this.options = options;
103 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
104 //this.current_query = null;
105 this.current_query=manifold.find_query(this.options.query_uuid);
106 if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query);
107 this.query_update = null;
108 this.current_resources = Array();
112 /* Transforms the table into DataTable, and keep a pointer to it */
114 // Customize the position of Datatables elements (length,filter,button,...)
115 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
116 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
117 sPaginationType: 'bootstrap',
118 // Handle the null values & the error : Datatables warning Requested unknown parameter
119 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
120 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
121 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
122 // sScrollX: '100%', /* Horizontal scrolling */
123 bProcessing: true, /* Loading */
124 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
126 // the intention here is that options.datatables_options as coming from the python object take precedence
127 $.extend(actual_options, options.datatables_options );
128 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
130 /* Setup the SelectAll button in the dataTable header */
131 /* xxx not sure this is still working */
132 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
133 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
135 oSelectAll.css('font-size','11px');
136 oSelectAll.css('float','right');
137 oSelectAll.css('margin-right','15px');
138 oSelectAll.css('margin-bottom','5px');
139 oSelectAll.unbind('click');
140 oSelectAll.click(selectAll);
142 /* Add a filtering function to the current table
143 * Note: we use closure to get access to the 'options'
145 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
146 /* No filtering if the table does not match */
147 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
149 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
154 this.set_query = function(query) {
155 var options = this.options;
156 /* Compare current and advertised query to get added and removed fields */
157 previous_query = this.current_query;
158 /* Save the query as the current query */
159 this.current_query = query;
160 if (debug) messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
161 /* We check all necessary fields : in column editor I presume XXX */
162 // XXX ID naming has no plugin_uuid
163 if (typeof(query.fields) != 'undefined') {
164 $.each (query.fields, function(index, value) {
165 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
166 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
169 /*Process updates in filters / current_query must be updated before this call for filtering ! */
173 * Process updates in fields
175 if (typeof(query.fields) != 'undefined') {
176 /* DataTable Settings */
177 var oSettings = this.table.dataTable().fnSettings();
178 var cols = oSettings.aoColumns;
179 var colnames = cols.map(function(x) {return x.sTitle});
180 colnames = $.grep(colnames, function(value) {return value != "+/-";});
182 if (previous_query == null) {
183 var added_fields = query.fields;
184 var removed_fields = colnames;
185 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
187 var tmp = previous_query.diff_fields(query);
188 var added_fields = tmp.added;
189 var removed_fields = tmp.removed;
192 /* Hide/unhide columns to match added/removed fields */
194 $.each(added_fields, function (index, field) {
195 var index = object.getColIndex(field,cols);
197 object.table.fnSetColumnVis(index, true);
199 $.each(removed_fields, function (index, field) {
200 var index = object.getColIndex(field,cols);
202 object.table.fnSetColumnVis(index, false);
207 this.set_resources = function(resources, instance) {
208 if (debug) messages.debug("entering hazelnut.set_resources");
209 var options = this.options;
210 var previous_resources = this.current_resources;
211 this.current_resources = resources;
213 /* We uncheck all checkboxes ... */
214 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
215 /* ... and check the ones specified in the resource list */
216 $.each(this.current_resources, function(index, urn) {
217 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
223 * @brief Determine index of key in the table columns
227 this.getColIndex = function(key, cols) {
228 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
229 return (tabIndex.length > 0) ? tabIndex[0] : -1;
234 * XXX will be removed/replaced
236 this.selected_changed = function(e, change) {
237 if (debug) messages.debug("entering hazelnut.selected_changed");
238 var actions = change.split("/");
239 if (actions.length > 1) {
240 var oNodes = this.table.fnGetNodes();
241 var myNode = $.grep(oNodes, function(value) {
242 if (value.id == actions[1]) { return value; }
244 if( myNode.length>0 ) {
245 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
248 checked="checked='checked' ";
249 var newValue = this.checkbox(actions[1], 'node', checked, false);
250 var columnPos = this.table.fnSettings().aoColumns.length - 1;
251 this.table.fnUpdate(newValue, myNode[0], columnPos);
257 this.update_plugin = function(e, rows) {
258 // e.data is what we passed in second argument to subscribe
259 // so here it is the jquery object attached to the plugin <div>
260 var $plugindiv=e.data;
261 if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
262 // clear the spinning wheel: look up an ancestor that has the need-spin class
263 // do this before we might return
264 $plugindiv.closest('.need-spin').spin(false);
266 var options = this.options;
269 if (rows.length==0) {
270 if (debug) console.l ("empty result");
271 this.table.html(unfold.errorDisplay("No Result"));
273 } else if (typeof(rows[0].error) != 'undefined') {
274 if (debug) messages.debug ("undefined result");
275 this.table.html(unfold.errorDisplay(rows[0].error));
278 newlines = new Array();
280 this.current_resources = Array();
282 $.each(rows, function(index, obj) {
283 newline = new Array();
285 // go through table headers to get column names we want
286 // in order (we have temporarily hack some adjustments in names)
287 var cols = hazelnut.table.fnSettings().aoColumns;
288 var colnames = cols.map(function(x) {return x.sTitle})
289 var nb_col = colnames.length;
290 if (options.checkboxes)
292 for (var j = 0; j < nb_col; j++) {
293 if (typeof colnames[j] == 'undefined') {
295 } else if (colnames[j] == 'hostname') {
296 if (obj['type'] == 'resource,link')
297 //TODO: we need to add source/destination for links
300 newline.push(obj['hostname']);
302 if (obj[colnames[j]])
303 newline.push(obj[colnames[j]]);
309 if (options.checkboxes) {
311 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
312 checked = 'checked ';
313 hazelnut.current_resources.push(obj['urn']);
315 // Use a key instead of hostname (hard coded...)
316 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
319 newlines.push(newline);
324 this.table.fnClearTable();
325 if (debug) messages.debug("hazelnut.update_plugin: total of " + newlines.length + " rows");
326 this.table.fnAddData(newlines);
330 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
332 /* Prefix id with plugin_uuid */
333 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
334 result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
335 result +="></input>";
340 /***************************************************************************
342 * xxx I'm not sure why this should not be methods in the Hazelnut class above
343 ***************************************************************************/
346 * @brief Hazelnut filtering function
348 function hazelnut_filter (oSettings, aData, iDataIndex) {
349 var cur_query = this.current_query;
352 /* We have an array of filters : a filter is an array (key op val)
353 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
354 * can we exploit the data property somewhere ?
355 * field values (unless formatting) : aData
356 * formatting should leave original data available in a hidden field
358 * The current line should validate all filters
360 $.each (cur_query.filters, function(index, filter) {
361 /* XXX How to manage checkbox ? */
364 var value = filter[2];
366 /* Determine index of key in the table columns */
367 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
369 /* Unknown key: no filtering */
370 if (typeof(col) == 'undefined')
373 col_value=unfold.get_value(aData[col]);
374 /* Test whether current filter is compatible with the column */
375 if (op == '=' || op == '==') {
376 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
378 }else if (op == '!=') {
379 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
382 if ( parseFloat(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")
387 } else if(op=='<=' || op=='≤') {
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")
394 // How to break out of a loop ?
395 alert("filter not supported");
403 function hazelnut_draw_callback() {
404 var options = this.options;
406 * Handle clicks on checkboxes: reassociate checkbox click every time
407 * the table is redrawn
409 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
410 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
415 /* Remove pagination if we show only a few results */
416 var wrapper = this.table; //.parent().parent().parent();
417 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
418 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
419 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
421 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
422 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
424 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
427 if ( rowsToShow <= minRowsPerPage ) {
428 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
430 $('.hazelnut_length', wrapper).css('visibility', 'visible');
434 function check_click (e) {
435 var object = e.data.instance;
436 var value = this.value;
439 object.current_resources.push(value);
441 tmp = $.grep(object.current_resources, function(x) { return x != value; });
442 object.current_resources = tmp;
445 /* inform slice that our selected resources have changed */
446 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
450 function selectAll() {
451 // requires jQuery id
452 var uuid=this.id.split("-");
453 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
454 // Function available in Hazelnut 1.9.x
455 // Filter : displayed data only
456 var filterData = oTable._('tr', {"filter":"applied"});
457 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
458 if(filterData.length<=100){
459 $.each(filterData, function(index, obj) {
460 var last=$(obj).last();
461 var key_value=unfold.get_value(last[0]);
462 if(typeof($(last[0]).attr('checked'))=="undefined"){
463 $.publish('selected', 'add/'+key_value);