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.
14 var ELEMENT_KEY = 'resource_hrn';
22 $.fn.Hazelnut = function( method ) {
23 if ( methods[method] ) {
24 return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
25 } else if ( typeof method === 'object' || ! method ) {
26 return methods.init.apply( this, arguments );
28 $.error( 'Method ' + method + ' does not exist on jQuery.Hazelnut' );
32 /***************************************************************************
34 ***************************************************************************/
39 * @brief Plugin initialization
40 * @param options : an associative array of setting values
41 * @return : a jQuery collection of objects on which the plugin is
42 * applied, which allows to maintain chainability of calls
44 init : function ( options ) {
46 /* Default settings */
47 var options = $.extend( {
51 return this.each(function() {
55 /* An object that will hold private variables and methods */
56 var plugin = new Hazelnut (options);
57 $this.data('Hazelnut', plugin);
60 $this.on('show.Datatables', methods.show);
62 // This is the new plugin API meant to replace the weird publish_subscribe mechanism
63 $this.set_query_handler(options.query_uuid, plugin.query_handler);
64 $this.set_record_handler(options.query_uuid, plugin.record_handler);
65 $this.set_record_handler(options.query_all_uuid, plugin.record_handler_all);
67 // /* Subscriptions */
68 // var query_channel = '/query/' + options.query_uuid + '/changed';
69 // var update_channel = '/update-set/' + options.query_uuid;
70 // var results_channel = '/results/' + options.query_uuid + '/changed';
72 // // xxx not tested yet
73 // $.subscribe(query_channel, function(e, query) { hazelnut.set_query(query); });
74 // // xxx not tested yet
75 // $.subscribe(update_channel, function(e, resources, instance) { hazelnut.set_resources(resources, instance); });
76 // // expected to work
77 // $.subscribe(results_channel, $this, function(e, rows) { hazelnut.update_plugin(e,rows); });
79 // messages.debug("hazelnut '" + this.id + "' subscribed to e.g." + results_channel);
85 * @brief Plugin destruction
86 * @return : a jQuery collection of objects on which the plugin is
87 * applied, which allows to maintain chainability of calls
89 destroy : function( ) {
91 return this.each(function() {
93 var hazelnut = $this.data('Hazelnut');
95 // Unbind all events using namespacing
96 $(window).unbind('Hazelnut');
98 // Remove associated data
100 $this.removeData('Hazelnut');
106 // xxx wtf. why [1] ? would expect 0...
108 messages.debug("Hitting suspicious line in hazelnut.show");
109 var oTable = $($('.dataTable', $this)[1]).dataTable();
110 oTable.fnAdjustColumnSizing()
112 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
113 $(this).each(function(i,elt) {
114 if (jQuery(elt).hasClass('dataTables')) {
115 var myDiv=jQuery('#hazelnut-' + this.id).parent();
116 if(myDiv.height()==0) {
117 var oTable=$('#hazelnut-' + this.id).dataTable();
126 /***************************************************************************
128 ***************************************************************************/
130 function Hazelnut(options)
132 /* member variables */
133 this.options = options;
135 // xxx thierry : initialize this here - it was not, I expect this relied on set_query somehow..
136 //this.current_query = null;
137 this.current_query=manifold.find_query(this.options.query_uuid);
138 // if (debug) messages.debug("Hazelnut constructor: have set current_query -> " + this.current_query.__repr());
139 this.query_update = null;
140 this.current_resources = Array();
143 this.received_all = false;
144 this.received_set = false;
145 this.in_set_buffer = Array();
149 this.initialize = function() {
150 /* Transforms the table into DataTable, and keep a pointer to it */
152 // Customize the position of Datatables elements (length,filter,button,...)
153 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
154 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
155 sPaginationType: 'bootstrap',
156 // Handle the null values & the error : Datatables warning Requested unknown parameter
157 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
158 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
159 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
160 // sScrollX: '100%', /* Horizontal scrolling */
161 bProcessing: true, /* Loading */
162 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
164 // the intention here is that options.datatables_options as coming from the python object take precedence
165 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
166 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
168 /* Setup the SelectAll button in the dataTable header */
169 /* xxx not sure this is still working */
170 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
171 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
173 oSelectAll.css('font-size','11px');
174 oSelectAll.css('float','right');
175 oSelectAll.css('margin-right','15px');
176 oSelectAll.css('margin-bottom','5px');
177 oSelectAll.unbind('click');
178 oSelectAll.click(selectAll);
180 /* Add a filtering function to the current table
181 * Note: we use closure to get access to the 'options'
183 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
184 /* No filtering if the table does not match */
185 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
187 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
190 /* Processing hidden_columns */
191 $.each(options.hidden_columns, function(i, field) {
192 object.hide_column(field);
198 // DEPRECATED // this.set_query = function(query) {
199 // DEPRECATED // messages.info('hazelnut.set_query');
200 // DEPRECATED // var options = this.options;
201 // DEPRECATED // /* Compare current and advertised query to get added and removed fields */
202 // DEPRECATED // previous_query = this.current_query;
203 // DEPRECATED // /* Save the query as the current query */
204 // DEPRECATED // this.current_query = query;
205 // DEPRECATED // if (debug)
206 // DEPRECATED // messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
208 // DEPRECATED // /* We check all necessary fields : in column editor I presume XXX */
209 // DEPRECATED // // XXX ID naming has no plugin_uuid
210 // DEPRECATED // if (typeof(query.fields) != 'undefined') {
211 // DEPRECATED // $.each (query.fields, function(index, value) {
212 // DEPRECATED // if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
213 // DEPRECATED // $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
217 // DEPRECATED // /* Process updates in filters / current_query must be updated before this call for filtering ! */
218 // DEPRECATED // this.table.fnDraw();
221 // DEPRECATED // * Process updates in fields
223 // DEPRECATED // if (typeof(query.fields) != 'undefined') {
224 // DEPRECATED // /* DataTable Settings */
225 // DEPRECATED // var oSettings = this.table.dataTable().fnSettings();
226 // DEPRECATED // var cols = oSettings.aoColumns;
227 // DEPRECATED // var colnames = cols.map(function(x) {return x.sTitle});
228 // DEPRECATED // colnames = $.grep(colnames, function(value) {return value != "+/-";});
230 // DEPRECATED // if (previous_query == null) {
231 // DEPRECATED // var added_fields = query.fields;
232 // DEPRECATED // var removed_fields = colnames;
233 // DEPRECATED // removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
234 // DEPRECATED // } else {
235 // DEPRECATED // var tmp = previous_query.diff_fields(query);
236 // DEPRECATED // var added_fields = tmp.added;
237 // DEPRECATED // var removed_fields = tmp.removed;
240 // DEPRECATED // /* Hide/unhide columns to match added/removed fields */
241 // DEPRECATED // var object = this;
242 // DEPRECATED // $.each(added_fields, function (index, field) {
243 // DEPRECATED // var index = object.getColIndex(field,cols);
244 // DEPRECATED // if(index != -1)
245 // DEPRECATED // object.table.fnSetColumnVis(index, true);
247 // DEPRECATED // $.each(removed_fields, function (index, field) {
248 // DEPRECATED // var index = object.getColIndex(field,cols);
249 // DEPRECATED // if(index != -1)
250 // DEPRECATED // object.table.fnSetColumnVis(index, false);
255 // DEPRECATED // this.set_resources = function(resources, instance) {
256 // DEPRECATED // if (debug)
257 // DEPRECATED // messages.debug("entering hazelnut.set_resources");
258 // DEPRECATED // var options = this.options;
259 // DEPRECATED // var previous_resources = this.current_resources;
260 // DEPRECATED // this.current_resources = resources;
262 // DEPRECATED // /* We uncheck all checkboxes ... */
263 // DEPRECATED // $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
264 // DEPRECATED // /* ... and check the ones specified in the resource list */
265 // DEPRECATED // $.each(this.current_resources, function(index, urn) {
266 // DEPRECATED // $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
272 * @brief Determine index of key in the table columns
276 this.getColIndex = function(key, cols) {
277 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
278 return (tabIndex.length > 0) ? tabIndex[0] : -1;
282 // DEPRECATED // * @brief
283 // DEPRECATED // * XXX will be removed/replaced
285 // DEPRECATED // this.selected_changed = function(e, change) {
286 // DEPRECATED // if (debug) messages.debug("entering hazelnut.selected_changed");
287 // DEPRECATED // var actions = change.split("/");
288 // DEPRECATED // if (actions.length > 1) {
289 // DEPRECATED // var oNodes = this.table.fnGetNodes();
290 // DEPRECATED // var myNode = $.grep(oNodes, function(value) {
291 // DEPRECATED // if (value.id == actions[1]) { return value; }
293 // DEPRECATED // if( myNode.length>0 ) {
294 // DEPRECATED // if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
295 // DEPRECATED // checked='';
296 // DEPRECATED // else
297 // DEPRECATED // checked="checked='checked' ";
298 // DEPRECATED // var newValue = this.checkbox(actions[1], 'node', checked, false);
299 // DEPRECATED // var columnPos = this.table.fnSettings().aoColumns.length - 1;
300 // DEPRECATED // this.table.fnUpdate(newValue, myNode[0], columnPos);
301 // DEPRECATED // this.table.fnDraw();
306 this.update_plugin = function(e, rows) {
307 // e.data is what we passed in second argument to subscribe
308 // so here it is the jquery object attached to the plugin <div>
309 var $plugindiv=e.data;
311 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
312 // clear the spinning wheel: look up an ancestor that has the need-spin class
313 // do this before we might return
314 $plugindiv.closest('.need-spin').spin(false);
316 var options = this.options;
319 /* if we get no result, or an error, try to make that clear, and exit */
320 if (rows.length==0) {
322 messages.debug("Empty result on hazelnut " + this.options.domid);
323 var placeholder=$(this.table).find("td.dataTables_empty");
324 console.log("placeholder "+placeholder);
325 if (placeholder.length==1)
326 placeholder.html(unfold.warning("Empty result"));
328 this.table.html(unfold.warning("Empty result"));
330 } else if (typeof(rows[0].error) != 'undefined') {
331 // we now should have another means to report errors that this inline/embedded hack
333 messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
334 this.table.html(unfold.error(rows[0].error));
339 * fill the dataTables object
340 * we cannot set html content directly here, need to use fnAddData
342 var lines = new Array();
344 this.current_resources = Array();
346 $.each(rows, function(index, row) {
347 // this models a line in dataTables, each element in the line describes a cell
350 // go through table headers to get column names we want
351 // in order (we have temporarily hack some adjustments in names)
352 var cols = object.table.fnSettings().aoColumns;
353 var colnames = cols.map(function(x) {return x.sTitle})
354 var nb_col = cols.length;
355 /* if we've requested checkboxes, then forget about the checkbox column for now */
356 if (options.checkboxes) nb_col -= 1;
358 /* fill in stuff depending on the column name */
359 for (var j = 0; j < nb_col; j++) {
360 if (typeof colnames[j] == 'undefined') {
362 } else if (colnames[j] == 'hostname') {
363 if (row['type'] == 'resource,link')
364 //TODO: we need to add source/destination for links
367 line.push(row['hostname']);
369 if (row[colnames[j]])
370 line.push(row[colnames[j]]);
376 /* catch up with the last column if checkboxes were requested */
377 if (options.checkboxes) {
379 // xxx problem is, we don't get this 'sliver' thing set apparently
380 if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
381 checked = 'checked ';
382 hazelnut.current_resources.push(row[ELEMENT_KEY]);
384 // Use a key instead of hostname (hard coded...)
385 line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
392 this.table.fnClearTable();
394 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
395 this.table.fnAddData(lines);
399 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str)
404 // Prefix id with plugin_uuid
406 result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
407 result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '') + "'";
408 result += " name='" + unfold.get_value(field) + "'";
409 result += " type='checkbox'";
410 result += selected_str;
411 result += disabled_str;
412 result += " autocomplete='off'";
413 result += " value='" + unfold.get_value(header) + "'";
414 result += "></input>";
418 ////////////////////////////////////////////////////////////////////////
419 // New plugin API (in tests)
421 // TODO : signal empty/non empty table
423 this.new_record = function(record)
425 // this models a line in dataTables, each element in the line describes a cell
428 // go through table headers to get column names we want
429 // in order (we have temporarily hack some adjustments in names)
430 var cols = object.table.fnSettings().aoColumns;
431 var colnames = cols.map(function(x) {return x.sTitle})
432 var nb_col = cols.length;
433 /* if we've requested checkboxes, then forget about the checkbox column for now */
434 if (options.checkboxes) nb_col -= 1;
436 /* fill in stuff depending on the column name */
437 for (var j = 0; j < nb_col; j++) {
438 if (typeof colnames[j] == 'undefined') {
440 } else if (colnames[j] == 'hostname') {
441 if (record['type'] == 'resource,link')
442 //TODO: we need to add source/destination for links
445 line.push(record['hostname']);
447 if (record[colnames[j]])
448 line.push(record[colnames[j]]);
454 /* catch up with the last column if checkboxes were requested */
455 if (options.checkboxes) {
457 // xxx problem is, we don't get this 'sliver' thing set apparently
458 if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
459 checked = 'checked ';
460 hazelnut.current_resources.push(record[ELEMENT_KEY]);
462 // Use a key instead of hostname (hard coded...)
463 line.push(object.checkbox(options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
466 // XXX Is adding an array of lines more efficient ?
467 this.table.fnAddData(line);
471 this.set_checkbox = function(record)
473 // XXX urn should be replaced by the key
474 // XXX we should enforce that both queries have the same key !!
475 checkbox_id = "#hazelnut-checkbox-" + object.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
476 $(checkbox_id, object.table.fnGetNodes()).attr('checked', true);
479 this.record_handler = function(e, event_type, record)
484 /* NOTE in fact we are doing a join here */
485 if (object.received_all)
486 // update checkbox for record
487 object.set_checkbox(record);
489 // store for later update of checkboxes
490 object.in_set_buffer.push(record);
493 // nothing to do here
496 manifold.spin($(this));
499 if (object.received_all)
500 manifold.spin($(this), false);
501 object.received_set = true;
506 this.record_handler_all = function(e, event_type, record)
511 // Add the record to the table
512 object.new_record(record);
515 object.table.fnClearTable();
518 manifold.spin($(this));
521 if (object.received_set) {
522 /* XXX needed ? XXX We uncheck all checkboxes ... */
523 $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
525 /* ... and check the ones specified in the resource list */
526 $.each(object.in_set_buffer, function(i, record) {
527 object.set_checkbox(record);
530 manifold.spin($(this), false);
532 object.received_all = true;
537 this.show_column = function(field)
539 var oSettings = object.table.fnSettings();
540 var cols = oSettings.aoColumns;
541 var index = object.getColIndex(field,cols);
543 object.table.fnSetColumnVis(index, true);
546 this.hide_column = function(field)
548 var oSettings = object.table.fnSettings();
549 var cols = oSettings.aoColumns;
550 var index = object.getColIndex(field,cols);
552 object.table.fnSetColumnVis(index, false);
555 this.query_handler = function(e, event_type, data)
557 // This replaces the complex set_query function
558 // The plugin does not need to remember the query anymore
564 // XXX Here we might need to maintain the list of filters !
565 /* Process updates in filters / current_query must be updated before this call for filtering ! */
566 object.table.fnDraw();
570 /* Hide/unhide columns to match added/removed fields */
572 object.show_column(data);
575 object.hide_column(data);
578 alert('Hazelnut::clear_fields() not implemented');
590 /***************************************************************************
592 * xxx I'm not sure why this should not be methods in the Hazelnut class above
593 ***************************************************************************/
596 * @brief Hazelnut filtering function
598 function hazelnut_filter (oSettings, aData, iDataIndex) {
599 var cur_query = this.current_query;
600 if (!cur_query) return true;
603 /* We have an array of filters : a filter is an array (key op val)
604 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
605 * can we exploit the data property somewhere ?
606 * field values (unless formatting) : aData
607 * formatting should leave original data available in a hidden field
609 * The current line should validate all filters
611 $.each (cur_query.filters, function(index, filter) {
612 /* XXX How to manage checkbox ? */
615 var value = filter[2];
617 /* Determine index of key in the table columns */
618 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
620 /* Unknown key: no filtering */
621 if (typeof(col) == 'undefined')
624 col_value=unfold.get_value(aData[col]);
625 /* Test whether current filter is compatible with the column */
626 if (op == '=' || op == '==') {
627 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
629 }else if (op == '!=') {
630 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
633 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
636 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
638 } else if(op=='<=' || op=='≤') {
639 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
641 } else if(op=='>=' || op=='≥') {
642 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
645 // How to break out of a loop ?
646 alert("filter not supported");
654 function hazelnut_draw_callback() {
655 var options = this.options;
657 * Handle clicks on checkboxes: reassociate checkbox click every time
658 * the table is redrawn
660 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
661 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
666 /* Remove pagination if we show only a few results */
667 var wrapper = this.table; //.parent().parent().parent();
668 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
669 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
670 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
672 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
673 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
675 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
678 if ( rowsToShow <= minRowsPerPage ) {
679 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
681 $('.hazelnut_length', wrapper).css('visibility', 'visible');
685 function check_click (e) {
687 var object = e.data.instance;
689 /* The key of the object to be added */
690 // XXX What about multiple keys ?
691 var value = this.value;
694 manifold.raise_event(object.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, value);
696 // OLD PLUGIN API BELOW
699 object.current_resources.push(value);
701 tmp = $.grep(object.current_resources, function(x) { return x != value; });
702 object.current_resources = tmp;
705 /* inform slice that our selected resources have changed */
706 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
710 function selectAll() {
711 // requires jQuery id
712 var uuid=this.id.split("-");
713 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
714 // Function available in Hazelnut 1.9.x
715 // Filter : displayed data only
716 var filterData = oTable._('tr', {"filter":"applied"});
717 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
718 if(filterData.length<=100){
719 $.each(filterData, function(index, obj) {
720 var last=$(obj).last();
721 var key_value=unfold.get_value(last[0]);
722 if(typeof($(last[0]).attr('checked'))=="undefined"){
723 $.publish('selected', 'add/'+key_value);