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() {
51 /* An object that will hold private variables and methods */
52 var hazelnut = new Hazelnut (options);
53 $this.data('Hazelnut', hazelnut);
56 $this.on('show.Datatables', methods.show);
58 // This is the new plugin API meant to replace the weird publish_subscribe mechanism
59 $this.set_query_handler(options.query_uuid, hazelnut.query_handler);
60 $this.set_record_handler(options.query_uuid, hazelnut.record_handler);
62 // /* Subscriptions */
63 // var query_channel = '/query/' + options.query_uuid + '/changed';
64 // var update_channel = '/update-set/' + options.query_uuid;
65 // var results_channel = '/results/' + options.query_uuid + '/changed';
67 // // xxx not tested yet
68 // $.subscribe(query_channel, function(e, query) { hazelnut.set_query(query); });
69 // // xxx not tested yet
70 // $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
71 // // expected to work
72 // $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
74 // messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
80 * @brief Plugin destruction
81 * @return : a jQuery collection of objects on which the plugin is
82 * applied, which allows to maintain chainability of calls
84 destroy : function( ) {
86 return this.each(function() {
88 var hazelnut = $this.data('Hazelnut');
90 // Unbind all events using namespacing
91 $(window).unbind('Hazelnut');
93 // Remove associated data
95 $this.removeData('Hazelnut');
101 // xxx wtf. why [1] ? would expect 0...
103 messages.debug("Hitting suspicious line in hazelnut.show");
104 var oTable = $($('.dataTable', $this)[1]).dataTable();
105 oTable.fnAdjustColumnSizing()
107 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
108 $(this).each(function(i,elt) {
109 if (jQuery(elt).hasClass('dataTables')) {
110 var myDiv=jQuery('#hazelnut-' + this.id).parent();
111 if(myDiv.height()==0) {
112 var oTable=$('#hazelnut-' + this.id).dataTable();
121 /***************************************************************************
123 ***************************************************************************/
125 function Hazelnut(options)
127 /* member variables */
128 this.options = options;
130 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
131 //this.current_query = null;
132 this.current_query=manifold.find_query(this.options.query_uuid);
133 // if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
134 this.query_update = null;
135 this.current_resources = Array();
139 /* Transforms the table into DataTable, and keep a pointer to it */
141 // Customize the position of Datatables elements (length,filter,button,...)
142 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
143 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
144 sPaginationType: 'bootstrap',
145 // Handle the null values & the error : Datatables warning Requested unknown parameter
146 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
147 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
148 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
149 // sScrollX: '100%', /* Horizontal scrolling */
150 bProcessing: true, /* Loading */
151 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
153 // the intention here is that options.datatables_options as coming from the python object take precedence
154 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
155 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
157 /* Setup the SelectAll button in the dataTable header */
158 /* xxx not sure this is still working */
159 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
160 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
162 oSelectAll.css('font-size','11px');
163 oSelectAll.css('float','right');
164 oSelectAll.css('margin-right','15px');
165 oSelectAll.css('margin-bottom','5px');
166 oSelectAll.unbind('click');
167 oSelectAll.click(selectAll);
169 /* Add a filtering function to the current table
170 * Note: we use closure to get access to the 'options'
172 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
173 /* No filtering if the table does not match */
174 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
176 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
181 this.set_query = function(query) {
182 messages.info('hazelnut.set_query');
183 var options = this.options;
184 /* Compare current and advertised query to get added and removed fields */
185 previous_query = this.current_query;
186 /* Save the query as the current query */
187 this.current_query = query;
189 messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
191 /* We check all necessary fields : in column editor I presume XXX */
192 // XXX ID naming has no plugin_uuid
193 if (typeof(query.fields) != 'undefined') {
194 $.each (query.fields, function(index, value) {
195 if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
196 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
200 /* Process updates in filters / current_query must be updated before this call for filtering ! */
204 * Process updates in fields
206 if (typeof(query.fields) != 'undefined') {
207 /* DataTable Settings */
208 var oSettings = this.table.dataTable().fnSettings();
209 var cols = oSettings.aoColumns;
210 var colnames = cols.map(function(x) {return x.sTitle});
211 colnames = $.grep(colnames, function(value) {return value != "+/-";});
213 if (previous_query == null) {
214 var added_fields = query.fields;
215 var removed_fields = colnames;
216 removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
218 var tmp = previous_query.diff_fields(query);
219 var added_fields = tmp.added;
220 var removed_fields = tmp.removed;
223 /* Hide/unhide columns to match added/removed fields */
225 $.each(added_fields, function (index, field) {
226 var index = object.getColIndex(field,cols);
228 object.table.fnSetColumnVis(index, true);
230 $.each(removed_fields, function (index, field) {
231 var index = object.getColIndex(field,cols);
233 object.table.fnSetColumnVis(index, false);
238 this.set_resources = function(resources, instance) {
240 messages.debug("entering hazelnut.set_resources");
241 var options = this.options;
242 var previous_resources = this.current_resources;
243 this.current_resources = resources;
245 /* We uncheck all checkboxes ... */
246 $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
247 /* ... and check the ones specified in the resource list */
248 $.each(this.current_resources, function(index, urn) {
249 $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
255 * @brief Determine index of key in the table columns
259 this.getColIndex = function(key, cols) {
260 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
261 return (tabIndex.length > 0) ? tabIndex[0] : -1;
266 * XXX will be removed/replaced
268 this.selected_changed = function(e, change) {
269 if (debug) messages.debug("entering hazelnut.selected_changed");
270 var actions = change.split("/");
271 if (actions.length > 1) {
272 var oNodes = this.table.fnGetNodes();
273 var myNode = $.grep(oNodes, function(value) {
274 if (value.id == actions[1]) { return value; }
276 if( myNode.length>0 ) {
277 if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
280 checked="checked='checked' ";
281 var newValue = this.checkbox(actions[1], 'node', checked, false);
282 var columnPos = this.table.fnSettings().aoColumns.length - 1;
283 this.table.fnUpdate(newValue, myNode[0], columnPos);
289 this.update_plugin = function(e, rows) {
290 // e.data is what we passed in second argument to subscribe
291 // so here it is the jquery object attached to the plugin <div>
292 var $plugindiv=e.data;
294 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
295 // clear the spinning wheel: look up an ancestor that has the need-spin class
296 // do this before we might return
297 $plugindiv.closest('.need-spin').spin(false);
299 var options = this.options;
302 /* if we get no result, or an error, try to make that clear, and exit */
303 if (rows.length==0) {
305 messages.debug("Empty result on hazelnut " + this.options.domid);
306 var placeholder=$(this.table).find("td.dataTables_empty");
307 console.log("placeholder "+placeholder);
308 if (placeholder.length==1)
309 placeholder.html(unfold.warning("Empty result"));
311 this.table.html(unfold.warning("Empty result"));
313 } else if (typeof(rows[0].error) != 'undefined') {
314 // we now should have another means to report errors that this inline/embedded hack
316 messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
317 this.table.html(unfold.error(rows[0].error));
322 * fill the dataTables object
323 * we cannot set html content directly here, need to use fnAddData
325 var lines = new Array();
327 this.current_resources = Array();
329 $.each(rows, function(index, row) {
330 // this models a line in dataTables, each element in the line describes a cell
333 // go through table headers to get column names we want
334 // in order (we have temporarily hack some adjustments in names)
335 var cols = object.table.fnSettings().aoColumns;
336 var colnames = cols.map(function(x) {return x.sTitle})
337 var nb_col = cols.length;
338 /* if we've requested checkboxes, then forget about the checkbox column for now */
339 if (options.checkboxes) nb_col -= 1;
341 /* fill in stuff depending on the column name */
342 for (var j = 0; j < nb_col; j++) {
343 if (typeof colnames[j] == 'undefined') {
345 } else if (colnames[j] == 'hostname') {
346 if (row['type'] == 'resource,link')
347 //TODO: we need to add source/destination for links
350 line.push(row['hostname']);
352 if (row[colnames[j]])
353 line.push(row[colnames[j]]);
359 /* catch up with the last column if checkboxes were requested */
360 if (options.checkboxes) {
362 // xxx problem is, we don't get this 'sliver' thing set apparently
363 if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
364 checked = 'checked ';
365 hazelnut.current_resources.push(row['urn']);
367 // Use a key instead of hostname (hard coded...)
368 line.push(hazelnut.checkbox(options.plugin_uuid, row['urn'], row['type'], checked, false));
375 this.table.fnClearTable();
377 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
378 this.table.fnAddData(lines);
382 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str)
385 // Prefix id with plugin_uuid
387 result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
388 result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header) + "'";
389 result += " name='" + unfold.get_value(field) + "'";
390 result += " type='checkbox'";
391 result += selected_str;
392 result += disabled_str;
393 result += " autocomplete='off'";
394 result += " value='" + unfold.get_value(header) + "'";
395 result += "></input>";
399 ////////////////////////////////////////////////////////////////////////
400 // New plugin API (in tests)
402 // TODO : signal empty/non empty table
404 this.new_record = function(record)
406 // this models a line in dataTables, each element in the line describes a cell
409 // go through table headers to get column names we want
410 // in order (we have temporarily hack some adjustments in names)
411 var cols = object.table.fnSettings().aoColumns;
412 var colnames = cols.map(function(x) {return x.sTitle})
413 var nb_col = cols.length;
414 /* if we've requested checkboxes, then forget about the checkbox column for now */
415 if (options.checkboxes) nb_col -= 1;
417 /* fill in stuff depending on the column name */
418 for (var j = 0; j < nb_col; j++) {
419 if (typeof colnames[j] == 'undefined') {
421 } else if (colnames[j] == 'hostname') {
422 if (record['type'] == 'resource,link')
423 //TODO: we need to add source/destination for links
426 line.push(record['hostname']);
428 if (record[colnames[j]])
429 line.push(record[colnames[j]]);
435 /* catch up with the last column if checkboxes were requested */
436 if (options.checkboxes) {
438 // xxx problem is, we don't get this 'sliver' thing set apparently
439 if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
440 checked = 'checked ';
441 hazelnut.current_resources.push(record['urn']);
443 // Use a key instead of hostname (hard coded...)
444 line.push(object.checkbox(options.plugin_uuid, record['urn'], record['type'], checked, false));
447 // XXX Is adding an array of lines more efficient ?
448 this.table.fnAddData(line);
452 this.record_handler = function(e, event_type, record)
456 object.new_record(record);
459 object.table.fnClearTable();
462 manifold.spin($(this));
465 manifold.spin($(this), false);
470 this.query_handler = function(e, event_type, query)
472 // This replaces the complex set_query function
473 // The plugin does not need to remember the query anymore
479 // XXX Here we might need to maintain the list of filters !
480 /* Process updates in filters / current_query must be updated before this call for filtering ! */
481 object.table.fnDraw();
485 /* Hide/unhide columns to match added/removed fields */
488 $.each(added_fields, function (index, field) {
489 var index = object.getColIndex(field,cols);
491 object.table.fnSetColumnVis(index, true);
496 $.each(removed_fields, function (index, field) {
497 var index = object.getColIndex(field,cols);
499 object.table.fnSetColumnVis(index, false);
503 alert('Hazelnut::clear_fields() not implemented');
511 /***************************************************************************
513 * xxx I'm not sure why this should not be methods in the Hazelnut class above
514 ***************************************************************************/
517 * @brief Hazelnut filtering function
519 function hazelnut_filter (oSettings, aData, iDataIndex) {
520 var cur_query = this.current_query;
521 if (!cur_query) return true;
524 /* We have an array of filters : a filter is an array (key op val)
525 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
526 * can we exploit the data property somewhere ?
527 * field values (unless formatting) : aData
528 * formatting should leave original data available in a hidden field
530 * The current line should validate all filters
532 $.each (cur_query.filters, function(index, filter) {
533 /* XXX How to manage checkbox ? */
536 var value = filter[2];
538 /* Determine index of key in the table columns */
539 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
541 /* Unknown key: no filtering */
542 if (typeof(col) == 'undefined')
545 col_value=unfold.get_value(aData[col]);
546 /* Test whether current filter is compatible with the column */
547 if (op == '=' || op == '==') {
548 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
550 }else if (op == '!=') {
551 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
554 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
557 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
559 } else if(op=='<=' || op=='≤') {
560 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
562 } else if(op=='>=' || op=='≥') {
563 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
566 // How to break out of a loop ?
567 alert("filter not supported");
575 function hazelnut_draw_callback() {
576 var options = this.options;
578 * Handle clicks on checkboxes: reassociate checkbox click every time
579 * the table is redrawn
581 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
582 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
587 /* Remove pagination if we show only a few results */
588 var wrapper = this.table; //.parent().parent().parent();
589 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
590 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
591 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
593 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
594 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
596 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
599 if ( rowsToShow <= minRowsPerPage ) {
600 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
602 $('.hazelnut_length', wrapper).css('visibility', 'visible');
606 function check_click (e) {
607 var object = e.data.instance;
608 var value = this.value;
611 object.current_resources.push(value);
613 tmp = $.grep(object.current_resources, function(x) { return x != value; });
614 object.current_resources = tmp;
617 /* inform slice that our selected resources have changed */
618 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
622 function selectAll() {
623 // requires jQuery id
624 var uuid=this.id.split("-");
625 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
626 // Function available in Hazelnut 1.9.x
627 // Filter : displayed data only
628 var filterData = oTable._('tr', {"filter":"applied"});
629 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
630 if(filterData.length<=100){
631 $.each(filterData, function(index, obj) {
632 var last=$(obj).last();
633 var key_value=unfold.get_value(last[0]);
634 if(typeof($(last[0]).attr('checked'))=="undefined"){
635 $.publish('selected', 'add/'+key_value);