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) console.log("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) console.log("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;
105 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
106 //this.current_query = null;
107 this.current_query=manifold.find_query(this.options.query_uuid);
108 if (debug) console.log("Hazelnut constructor: have set current_query -> " + this.current_query);
109 this.query_update = null;
110 this.current_resources = Array();
114 /* Transforms the table into DataTable, and keep a pointer to it */
116 // Customize the position of Datatables elements (length,filter,button,...)
117 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
118 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
119 sPaginationType: 'bootstrap',
120 // Handle the null values & the error : Datatables warning Requested unknown parameter
121 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
122 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
123 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
124 // sScrollX: '100%', /* Horizontal scrolling */
125 bProcessing: true, /* Loading */
126 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
128 // the intention here is that options.datatables_options as coming from the python object take precedence
129 $.extend(actual_options, options.datatables_options );
130 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
132 /* Setup the SelectAll button in the dataTable header */
133 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
134 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
136 oSelectAll.css('font-size','11px');
137 oSelectAll.css('float','right');
138 oSelectAll.css('margin-right','15px');
139 oSelectAll.css('margin-bottom','5px');
140 oSelectAll.unbind('click');
141 oSelectAll.click(selectAll);
143 /* Add a filtering function to the current table
144 * Note: we use closure to get access to the 'options'
146 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
147 /* No filtering if the table does not match */
148 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
150 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
155 this.set_query = function(query) {
156 var options = this.options;
157 /* Compare current and advertised query to get added and removed fields */
158 previous_query = this.current_query;
159 /* Save the query as the current query */
160 this.current_query = query;
161 if (debug) console.log("hazelnut.set_query, current_query is now -> " + this.current_query);
162 /* We check all necessary fields : in column editor I presume XXX */
163 // XXX ID naming has no plugin_uuid
164 if (typeof(query.fields) != 'undefined') {
165 $.each (query.fields, function(index, value) {
166 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
167 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
170 /*Process updates in filters / current_query must be updated before this call for filtering ! */
174 * Process updates in fields
176 if (typeof(query.fields) != 'undefined') {
177 /* DataTable Settings */
178 var oSettings = this.table.dataTable().fnSettings();
179 var cols = oSettings.aoColumns;
180 var colnames = cols.map(function(x) {return x.sTitle});
181 colnames = $.grep(colnames, function(value) {return value != "+/-";});
183 if (previous_query == null) {
184 var added_fields = query.fields;
185 var removed_fields = colnames;
186 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
188 var tmp = previous_query.diff_fields(query);
189 var added_fields = tmp.added;
190 var removed_fields = tmp.removed;
193 /* Hide/unhide columns to match added/removed fields */
195 $.each(added_fields, function (index, field) {
196 var index = object.getColIndex(field,cols);
198 object.table.fnSetColumnVis(index, true);
200 $.each(removed_fields, function (index, field) {
201 var index = object.getColIndex(field,cols);
203 object.table.fnSetColumnVis(index, false);
208 this.set_resources = function(resources, instance) {
209 if (debug) console.log("entering hazelnut.set_resources");
210 var options = this.options;
211 var previous_resources = this.current_resources;
212 this.current_resources = resources;
214 /* We uncheck all checkboxes ... */
215 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
216 /* ... and check the ones specified in the resource list */
217 $.each(this.current_resources, function(index, urn) {
218 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
224 * @brief Determine index of key in the table columns
228 this.getColIndex = function(key, cols) {
229 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
230 return (tabIndex.length > 0) ? tabIndex[0] : -1;
235 * XXX will be removed/replaced
237 this.selected_changed = function(e, change) {
238 if (debug) console.log("entering hazelnut.selected_changed");
239 var actions = change.split("/");
240 if (actions.length > 1) {
241 var oNodes = this.table.fnGetNodes();
242 var myNode = $.grep(oNodes, function(value) {
243 if (value.id == actions[1]) { return value; }
245 if( myNode.length>0 ) {
246 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
249 checked="checked='checked' ";
250 var newValue = this.checkbox(actions[1], 'node', checked, false);
251 var columnPos = this.table.fnSettings().aoColumns.length - 1;
252 this.table.fnUpdate(newValue, myNode[0], columnPos);
258 this.update_plugin = function(e, rows) {
259 // e.data is what we passed in second argument to subscribe
260 // so here it is the jquery object attached to the plugin <div>
261 var $plugindiv=e.data;
262 if (debug) console.log("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
263 // clear the spinning wheel: look up an ancestor that has the need-spin class
264 // do this before we might return
265 $plugindiv.closest('.need-spin').spin(false);
267 var options = this.options;
270 if (rows.length==0) {
271 if (debug) console.l ("empty result");
272 this.table.html(unfold.errorDisplay("No Result"));
274 } else if (typeof(rows[0].error) != 'undefined') {
275 if (debug) console.log ("undefined result");
276 this.table.html(unfold.errorDisplay(rows[0].error));
279 newlines = new Array();
281 this.current_resources = Array();
283 $.each(rows, function(index, obj) {
284 newline = new Array();
286 // go through table headers to get column names we want
287 // in order (we have temporarily hack some adjustments in names)
288 var cols = hazelnut.table.fnSettings().aoColumns;
289 var colnames = cols.map(function(x) {return x.sTitle})
290 var nb_col = colnames.length;
291 if (options.checkboxes)
293 for (var j = 0; j < nb_col; j++) {
294 if (typeof colnames[j] == 'undefined') {
296 } else if (colnames[j] == 'hostname') {
297 if (obj['type'] == 'resource,link')
298 //TODO: we need to add source/destination for links
301 newline.push(obj['hostname']);
303 if (obj[colnames[j]])
304 newline.push(obj[colnames[j]]);
310 if (options.checkboxes) {
312 if (typeof(obj['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
313 checked = 'checked ';
314 hazelnut.current_resources.push(obj['urn']);
316 // Use a key instead of hostname (hard coded...)
317 newline.push(hazelnut.checkbox(options.plugin_uuid, obj['urn'], obj['type'], checked, false));
320 newlines.push(newline);
325 this.table.fnClearTable();
326 if (debug) console.log("hazelnut.update_plugin: total of " + newlines.length + " rows");
327 this.table.fnAddData(newlines);
331 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
333 /* Prefix id with plugin_uuid */
334 result += "<input class='hazelnut-checkbox-" + plugin_uuid + "' id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
335 result += " name='" + unfold.get_value(field) + "' type='checkbox' " + selected_str + disabled_str + " autocomplete='off' value='" + unfold.get_value(header) + "'";
336 result +="></input>";
341 /***************************************************************************
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);