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 ***************************************************************************/
35 * @brief Plugin initialization
36 * @param options : an associative array of setting values
37 * @return : a jQuery collection of objects on which the plugin is
38 * applied, which allows to maintain chainability of calls
40 init : function ( options ) {
42 /* Default settings */
43 var options = $.extend( {
47 return this.each(function() {
52 $this.on('show.Datatables', methods.show);
54 /* An object that will hold private variables and methods */
55 var hazelnut = new Hazelnut (options);
56 $this.data('Hazelnut', hazelnut);
57 var query_channel = '/query/' + options.query_uuid + '/changed';
58 var update_channel = '/update-set/' + options.query_uuid;
59 var results_channel = '/results/' + options.query_uuid + '/changed';
62 $.subscribe(query_channel, function(e, query) { hazelnut.set_query(query); });
64 $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
66 $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
68 messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
74 * @brief Plugin destruction
75 * @return : a jQuery collection of objects on which the plugin is
76 * applied, which allows to maintain chainability of calls
78 destroy : function( ) {
80 return this.each(function() {
82 var hazelnut = $this.data('Hazelnut');
84 // Unbind all events using namespacing
85 $(window).unbind('Hazelnut');
87 // Remove associated data
89 $this.removeData('Hazelnut');
95 // xxx wtf. why [1] ? would expect 0...
97 messages.debug("Hitting suspicious line in hazelnut.show");
98 var oTable = $($('.dataTable', $this)[1]).dataTable();
99 oTable.fnAdjustColumnSizing()
101 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
102 $(this).each(function(i,elt) {
103 if (jQuery(elt).hasClass('dataTables')) {
104 var myDiv=jQuery('#hazelnut-' + this.id).parent();
105 if(myDiv.height()==0) {
106 var oTable=$('#hazelnut-' + this.id).dataTable();
115 /***************************************************************************
117 ***************************************************************************/
119 function Hazelnut(options)
121 /* member variables */
122 this.options = options;
124 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
125 //this.current_query = null;
126 this.current_query=manifold.find_query(this.options.query_uuid);
127 // if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
128 this.query_update = null;
129 this.current_resources = Array();
133 /* Transforms the table into DataTable, and keep a pointer to it */
135 // Customize the position of Datatables elements (length,filter,button,...)
136 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
137 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
138 sPaginationType: 'bootstrap',
139 // Handle the null values & the error : Datatables warning Requested unknown parameter
140 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
141 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
142 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
143 // sScrollX: '100%', /* Horizontal scrolling */
144 bProcessing: true, /* Loading */
145 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
147 // the intention here is that options.datatables_options as coming from the python object take precedence
148 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
149 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
151 /* Setup the SelectAll button in the dataTable header */
152 /* xxx not sure this is still working */
153 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
154 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
156 oSelectAll.css('font-size','11px');
157 oSelectAll.css('float','right');
158 oSelectAll.css('margin-right','15px');
159 oSelectAll.css('margin-bottom','5px');
160 oSelectAll.unbind('click');
161 oSelectAll.click(selectAll);
163 /* Add a filtering function to the current table
164 * Note: we use closure to get access to the 'options'
166 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
167 /* No filtering if the table does not match */
168 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
170 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
175 this.set_query = function(query) {
176 messages.info('hazelnut.set_query');
177 var options = this.options;
178 /* Compare current and advertised query to get added and removed fields */
179 previous_query = this.current_query;
180 /* Save the query as the current query */
181 this.current_query = query;
183 messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
185 /* We check all necessary fields : in column editor I presume XXX */
186 // XXX ID naming has no plugin_uuid
187 if (typeof(query.fields) != 'undefined') {
188 $.each (query.fields, function(index, value) {
189 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
190 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
194 /* Process updates in filters / current_query must be updated before this call for filtering ! */
198 * Process updates in fields
200 if (typeof(query.fields) != 'undefined') {
201 /* DataTable Settings */
202 var oSettings = this.table.dataTable().fnSettings();
203 var cols = oSettings.aoColumns;
204 var colnames = cols.map(function(x) {return x.sTitle});
205 colnames = $.grep(colnames, function(value) {return value != "+/-";});
207 if (previous_query == null) {
208 var added_fields = query.fields;
209 var removed_fields = colnames;
210 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
212 var tmp = previous_query.diff_fields(query);
213 var added_fields = tmp.added;
214 var removed_fields = tmp.removed;
217 /* Hide/unhide columns to match added/removed fields */
219 $.each(added_fields, function (index, field) {
220 var index = object.getColIndex(field,cols);
222 object.table.fnSetColumnVis(index, true);
224 $.each(removed_fields, function (index, field) {
225 var index = object.getColIndex(field,cols);
227 object.table.fnSetColumnVis(index, false);
232 this.set_resources = function(resources, instance) {
234 messages.debug("entering hazelnut.set_resources");
235 var options = this.options;
236 var previous_resources = this.current_resources;
237 this.current_resources = resources;
239 /* We uncheck all checkboxes ... */
240 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
241 /* ... and check the ones specified in the resource list */
242 $.each(this.current_resources, function(index, urn) {
243 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
249 * @brief Determine index of key in the table columns
253 this.getColIndex = function(key, cols) {
254 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
255 return (tabIndex.length > 0) ? tabIndex[0] : -1;
260 * XXX will be removed/replaced
262 this.selected_changed = function(e, change) {
263 if (debug) messages.debug("entering hazelnut.selected_changed");
264 var actions = change.split("/");
265 if (actions.length > 1) {
266 var oNodes = this.table.fnGetNodes();
267 var myNode = $.grep(oNodes, function(value) {
268 if (value.id == actions[1]) { return value; }
270 if( myNode.length>0 ) {
271 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
274 checked="checked='checked' ";
275 var newValue = this.checkbox(actions[1], 'node', checked, false);
276 var columnPos = this.table.fnSettings().aoColumns.length - 1;
277 this.table.fnUpdate(newValue, myNode[0], columnPos);
283 this.update_plugin = function(e, rows) {
284 // e.data is what we passed in second argument to subscribe
285 // so here it is the jquery object attached to the plugin <div>
286 var $plugindiv=e.data;
287 if (debug) messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
288 // clear the spinning wheel: look up an ancestor that has the need-spin class
289 // do this before we might return
290 $plugindiv.closest('.need-spin').spin(false);
292 var options = this.options;
295 /* if we get no result, or an error, try to make that clear, and exit */
296 if (rows.length==0) {
297 if (debug) messages.debug("Empty result on hazelnut " + this.options.domid);
298 var placeholder=$(this.table).find("td.dataTables_empty");
299 console.log("placeholder "+placeholder);
300 if (placeholder.length==1) placeholder.html(unfold.warning("Empty result"));
301 else this.table.html(unfold.warning("Empty result"));
303 } else if (typeof(rows[0].error) != 'undefined') {
304 // we now should have another means to report errors that this inline/embedded hack
305 if (debug) messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
306 this.table.html(unfold.error(rows[0].error));
311 * fill the dataTables object
312 * we cannot set html content directly here, need to use fnAddData
314 var lines = new Array();
316 this.current_resources = Array();
318 $.each(rows, function(index, row) {
319 // this models a line in dataTables, each element in the line describes a cell
322 // go through table headers to get column names we want
323 // in order (we have temporarily hack some adjustments in names)
324 var cols = hazelnut.table.fnSettings().aoColumns;
325 var colnames = cols.map(function(x) {return x.sTitle})
326 var nb_col = cols.length;
327 /* if we've requested checkboxes, then forget about the checkbox column for now */
328 if (options.checkboxes) nb_col -= 1;
330 /* fill in stuff depending on the column name */
331 for (var j = 0; j < nb_col; j++) {
332 if (typeof colnames[j] == 'undefined') {
334 } else if (colnames[j] == 'hostname') {
335 if (row['type'] == 'resource,link')
336 //TODO: we need to add source/destination for links
339 line.push(row['hostname']);
341 if (row[colnames[j]])
342 line.push(row[colnames[j]]);
348 /* catch up with the last column if checkboxes were requested */
349 if (options.checkboxes) {
351 // xxx problem is, we don't get this 'sliver' thing set apparently
352 if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
353 checked = 'checked ';
354 hazelnut.current_resources.push(row['urn']);
356 // Use a key instead of hostname (hard coded...)
357 line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
364 this.table.fnClearTable();
365 if (debug) messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
366 this.table.fnAddData(lines);
370 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str) {
372 // Preafix id with plugin_uuid
374 result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
375 result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
376 result += " name='" + unfold.get_value(field) + "'";
377 result += " type='checkbox'";
378 result += selected_str;
379 result += disabled_str;
380 result += " autocomplete='off'";
381 result += " value='" + unfold.get_value(header) + "'";
382 result += "></input>";
387 /***************************************************************************
389 * xxx I'm not sure why this should not be methods in the Hazelnut class above
390 ***************************************************************************/
393 * @brief Hazelnut filtering function
395 function hazelnut_filter (oSettings, aData, iDataIndex) {
396 var cur_query = this.current_query;
397 if (!cur_query) return true;
400 /* We have an array of filters : a filter is an array (key op val)
401 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
402 * can we exploit the data property somewhere ?
403 * field values (unless formatting) : aData
404 * formatting should leave original data available in a hidden field
406 * The current line should validate all filters
408 $.each (cur_query.filters, function(index, filter) {
409 /* XXX How to manage checkbox ? */
412 var value = filter[2];
414 /* Determine index of key in the table columns */
415 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
417 /* Unknown key: no filtering */
418 if (typeof(col) == 'undefined')
421 col_value=unfold.get_value(aData[col]);
422 /* Test whether current filter is compatible with the column */
423 if (op == '=' || op == '==') {
424 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
426 }else if (op == '!=') {
427 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
430 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
433 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
435 } else if(op=='<=' || op=='≤') {
436 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
438 } else if(op=='>=' || op=='≥') {
439 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
442 // How to break out of a loop ?
443 alert("filter not supported");
451 function hazelnut_draw_callback() {
452 var options = this.options;
454 * Handle clicks on checkboxes: reassociate checkbox click every time
455 * the table is redrawn
457 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
458 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
463 /* Remove pagination if we show only a few results */
464 var wrapper = this.table; //.parent().parent().parent();
465 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
466 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
467 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
469 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
470 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
472 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
475 if ( rowsToShow <= minRowsPerPage ) {
476 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
478 $('.hazelnut_length', wrapper).css('visibility', 'visible');
482 function check_click (e) {
483 var object = e.data.instance;
484 var value = this.value;
487 object.current_resources.push(value);
489 tmp = $.grep(object.current_resources, function(x) { return x != value; });
490 object.current_resources = tmp;
493 /* inform slice that our selected resources have changed */
494 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
498 function selectAll() {
499 // requires jQuery id
500 var uuid=this.id.split("-");
501 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
502 // Function available in Hazelnut 1.9.x
503 // Filter : displayed data only
504 var filterData = oTable._('tr', {"filter":"applied"});
505 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
506 if(filterData.length<=100){
507 $.each(filterData, function(index, obj) {
508 var last=$(obj).last();
509 var key_value=unfold.get_value(last[0]);
510 if(typeof($(last[0]).attr('checked'))=="undefined"){
511 $.publish('selected', 'add/'+key_value);