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 hazelnut = new Hazelnut (options);
57 $this.data('Hazelnut', hazelnut);
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, hazelnut.query_handler);
64 $this.set_record_handler(options.query_uuid, hazelnut.record_handler);
65 $this.set_record_handler(options.query_all_uuid, hazelnut.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 /* Transforms the table into DataTable, and keep a pointer to it */
151 // Customize the position of Datatables elements (length,filter,button,...)
152 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
153 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
154 sPaginationType: 'bootstrap',
155 // Handle the null values & the error : Datatables warning Requested unknown parameter
156 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
157 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
158 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
159 // sScrollX: '100%', /* Horizontal scrolling */
160 bProcessing: true, /* Loading */
161 fnDrawCallback: function() { hazelnut_draw_callback.call(object, options); }
163 // the intention here is that options.datatables_options as coming from the python object take precedence
164 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
165 this.table = $('#hazelnut-' + options.plugin_uuid).dataTable(actual_options);
167 /* Setup the SelectAll button in the dataTable header */
168 /* xxx not sure this is still working */
169 var oSelectAll = $('#datatableSelectAll-'+ options.plugin_uuid);
170 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
172 oSelectAll.css('font-size','11px');
173 oSelectAll.css('float','right');
174 oSelectAll.css('margin-right','15px');
175 oSelectAll.css('margin-bottom','5px');
176 oSelectAll.unbind('click');
177 oSelectAll.click(selectAll);
179 /* Add a filtering function to the current table
180 * Note: we use closure to get access to the 'options'
182 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
183 /* No filtering if the table does not match */
184 if (oSettings.nTable.id != "hazelnut-" + options.plugin_uuid)
186 return hazelnut_filter.call(object, oSettings, aData, iDataIndex);
191 // DEPRECATED // this.set_query = function(query) {
192 // DEPRECATED // messages.info('hazelnut.set_query');
193 // DEPRECATED // var options = this.options;
194 // DEPRECATED // /* Compare current and advertised query to get added and removed fields */
195 // DEPRECATED // previous_query = this.current_query;
196 // DEPRECATED // /* Save the query as the current query */
197 // DEPRECATED // this.current_query = query;
198 // DEPRECATED // if (debug)
199 // DEPRECATED // messages.debug("hazelnut.set_query, current_query is now -> " + this.current_query);
201 // DEPRECATED // /* We check all necessary fields : in column editor I presume XXX */
202 // DEPRECATED // // XXX ID naming has no plugin_uuid
203 // DEPRECATED // if (typeof(query.fields) != 'undefined') {
204 // DEPRECATED // $.each (query.fields, function(index, value) {
205 // DEPRECATED // if (!$('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked'))
206 // DEPRECATED // $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + value).attr('checked', true);
210 // DEPRECATED // /* Process updates in filters / current_query must be updated before this call for filtering ! */
211 // DEPRECATED // this.table.fnDraw();
214 // DEPRECATED // * Process updates in fields
216 // DEPRECATED // if (typeof(query.fields) != 'undefined') {
217 // DEPRECATED // /* DataTable Settings */
218 // DEPRECATED // var oSettings = this.table.dataTable().fnSettings();
219 // DEPRECATED // var cols = oSettings.aoColumns;
220 // DEPRECATED // var colnames = cols.map(function(x) {return x.sTitle});
221 // DEPRECATED // colnames = $.grep(colnames, function(value) {return value != "+/-";});
223 // DEPRECATED // if (previous_query == null) {
224 // DEPRECATED // var added_fields = query.fields;
225 // DEPRECATED // var removed_fields = colnames;
226 // DEPRECATED // removed_fields = $.grep(colnames, function(x) { return $.inArray(x, added_fields) == -1});
227 // DEPRECATED // } else {
228 // DEPRECATED // var tmp = previous_query.diff_fields(query);
229 // DEPRECATED // var added_fields = tmp.added;
230 // DEPRECATED // var removed_fields = tmp.removed;
233 // DEPRECATED // /* Hide/unhide columns to match added/removed fields */
234 // DEPRECATED // var object = this;
235 // DEPRECATED // $.each(added_fields, function (index, field) {
236 // DEPRECATED // var index = object.getColIndex(field,cols);
237 // DEPRECATED // if(index != -1)
238 // DEPRECATED // object.table.fnSetColumnVis(index, true);
240 // DEPRECATED // $.each(removed_fields, function (index, field) {
241 // DEPRECATED // var index = object.getColIndex(field,cols);
242 // DEPRECATED // if(index != -1)
243 // DEPRECATED // object.table.fnSetColumnVis(index, false);
248 // DEPRECATED // this.set_resources = function(resources, instance) {
249 // DEPRECATED // if (debug)
250 // DEPRECATED // messages.debug("entering hazelnut.set_resources");
251 // DEPRECATED // var options = this.options;
252 // DEPRECATED // var previous_resources = this.current_resources;
253 // DEPRECATED // this.current_resources = resources;
255 // DEPRECATED // /* We uncheck all checkboxes ... */
256 // DEPRECATED // $('hazelnut-checkbox-' + options.plugin_uuid).attr('checked', false);
257 // DEPRECATED // /* ... and check the ones specified in the resource list */
258 // DEPRECATED // $.each(this.current_resources, function(index, urn) {
259 // DEPRECATED // $('#hazelnut-checkbox-' + options.plugin_uuid + "-" + urn).attr('checked', true)
265 * @brief Determine index of key in the table columns
269 this.getColIndex = function(key, cols) {
270 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
271 return (tabIndex.length > 0) ? tabIndex[0] : -1;
275 // DEPRECATED // * @brief
276 // DEPRECATED // * XXX will be removed/replaced
278 // DEPRECATED // this.selected_changed = function(e, change) {
279 // DEPRECATED // if (debug) messages.debug("entering hazelnut.selected_changed");
280 // DEPRECATED // var actions = change.split("/");
281 // DEPRECATED // if (actions.length > 1) {
282 // DEPRECATED // var oNodes = this.table.fnGetNodes();
283 // DEPRECATED // var myNode = $.grep(oNodes, function(value) {
284 // DEPRECATED // if (value.id == actions[1]) { return value; }
286 // DEPRECATED // if( myNode.length>0 ) {
287 // DEPRECATED // if ((actions[2]=="add" && actions[0]=="cancel") || actions[0]=="del")
288 // DEPRECATED // checked='';
289 // DEPRECATED // else
290 // DEPRECATED // checked="checked='checked' ";
291 // DEPRECATED // var newValue = this.checkbox(actions[1], 'node', checked, false);
292 // DEPRECATED // var columnPos = this.table.fnSettings().aoColumns.length - 1;
293 // DEPRECATED // this.table.fnUpdate(newValue, myNode[0], columnPos);
294 // DEPRECATED // this.table.fnDraw();
299 this.update_plugin = function(e, rows) {
300 // e.data is what we passed in second argument to subscribe
301 // so here it is the jquery object attached to the plugin <div>
302 var $plugindiv=e.data;
304 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
305 // clear the spinning wheel: look up an ancestor that has the need-spin class
306 // do this before we might return
307 $plugindiv.closest('.need-spin').spin(false);
309 var options = this.options;
312 /* if we get no result, or an error, try to make that clear, and exit */
313 if (rows.length==0) {
315 messages.debug("Empty result on hazelnut " + this.options.domid);
316 var placeholder=$(this.table).find("td.dataTables_empty");
317 console.log("placeholder "+placeholder);
318 if (placeholder.length==1)
319 placeholder.html(unfold.warning("Empty result"));
321 this.table.html(unfold.warning("Empty result"));
323 } else if (typeof(rows[0].error) != 'undefined') {
324 // we now should have another means to report errors that this inline/embedded hack
326 messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
327 this.table.html(unfold.error(rows[0].error));
332 * fill the dataTables object
333 * we cannot set html content directly here, need to use fnAddData
335 var lines = new Array();
337 this.current_resources = Array();
339 $.each(rows, function(index, row) {
340 // this models a line in dataTables, each element in the line describes a cell
343 // go through table headers to get column names we want
344 // in order (we have temporarily hack some adjustments in names)
345 var cols = object.table.fnSettings().aoColumns;
346 var colnames = cols.map(function(x) {return x.sTitle})
347 var nb_col = cols.length;
348 /* if we've requested checkboxes, then forget about the checkbox column for now */
349 if (options.checkboxes) nb_col -= 1;
351 /* fill in stuff depending on the column name */
352 for (var j = 0; j < nb_col; j++) {
353 if (typeof colnames[j] == 'undefined') {
355 } else if (colnames[j] == 'hostname') {
356 if (row['type'] == 'resource,link')
357 //TODO: we need to add source/destination for links
360 line.push(row['hostname']);
362 if (row[colnames[j]])
363 line.push(row[colnames[j]]);
369 /* catch up with the last column if checkboxes were requested */
370 if (options.checkboxes) {
372 // xxx problem is, we don't get this 'sliver' thing set apparently
373 if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
374 checked = 'checked ';
375 hazelnut.current_resources.push(row[ELEMENT_KEY]);
377 // Use a key instead of hostname (hard coded...)
378 line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
385 this.table.fnClearTable();
387 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
388 this.table.fnAddData(lines);
392 this.checkbox = function (plugin_uuid, header, field, selected_str, disabled_str)
397 // Prefix id with plugin_uuid
399 result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
400 result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '') + "'";
401 result += " name='" + unfold.get_value(field) + "'";
402 result += " type='checkbox'";
403 result += selected_str;
404 result += disabled_str;
405 result += " autocomplete='off'";
406 result += " value='" + unfold.get_value(header) + "'";
407 result += "></input>";
411 ////////////////////////////////////////////////////////////////////////
412 // New plugin API (in tests)
414 // TODO : signal empty/non empty table
416 this.new_record = function(record)
418 // this models a line in dataTables, each element in the line describes a cell
421 // go through table headers to get column names we want
422 // in order (we have temporarily hack some adjustments in names)
423 var cols = object.table.fnSettings().aoColumns;
424 var colnames = cols.map(function(x) {return x.sTitle})
425 var nb_col = cols.length;
426 /* if we've requested checkboxes, then forget about the checkbox column for now */
427 if (options.checkboxes) nb_col -= 1;
429 /* fill in stuff depending on the column name */
430 for (var j = 0; j < nb_col; j++) {
431 if (typeof colnames[j] == 'undefined') {
433 } else if (colnames[j] == 'hostname') {
434 if (record['type'] == 'resource,link')
435 //TODO: we need to add source/destination for links
438 line.push(record['hostname']);
440 if (record[colnames[j]])
441 line.push(record[colnames[j]]);
447 /* catch up with the last column if checkboxes were requested */
448 if (options.checkboxes) {
450 // xxx problem is, we don't get this 'sliver' thing set apparently
451 if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
452 checked = 'checked ';
453 hazelnut.current_resources.push(record[ELEMENT_KEY]);
455 // Use a key instead of hostname (hard coded...)
456 line.push(object.checkbox(options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
459 // XXX Is adding an array of lines more efficient ?
460 this.table.fnAddData(line);
464 this.set_checkbox = function(record)
466 // XXX urn should be replaced by the key
467 // XXX we should enforce that both queries have the same key !!
468 checkbox_id = "#hazelnut-checkbox-" + object.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
469 $(checkbox_id, object.table.fnGetNodes()).attr('checked', true);
472 this.record_handler = function(e, event_type, record)
477 /* NOTE in fact we are doing a join here */
478 if (object.received_all)
479 // update checkbox for record
480 object.set_checkbox(record);
482 // store for later update of checkboxes
483 object.in_set_buffer.push(record);
486 // nothing to do here
489 manifold.spin($(this));
492 if (object.received_all)
493 manifold.spin($(this), false);
494 object.received_set = true;
499 this.record_handler_all = function(e, event_type, record)
504 // Add the record to the table
505 object.new_record(record);
508 object.table.fnClearTable();
511 manifold.spin($(this));
514 if (object.received_set) {
515 /* XXX needed ? XXX We uncheck all checkboxes ... */
516 $("[id^='datatables-checkbox-" + object.options.plugin_uuid +"']").attr('checked', false);
518 /* ... and check the ones specified in the resource list */
519 $.each(object.in_set_buffer, function(i, record) {
520 object.set_checkbox(record);
523 manifold.spin($(this), false);
525 object.received_all = true;
530 this.query_handler = function(e, event_type, query)
532 // This replaces the complex set_query function
533 // The plugin does not need to remember the query anymore
539 // XXX Here we might need to maintain the list of filters !
540 /* Process updates in filters / current_query must be updated before this call for filtering ! */
541 object.table.fnDraw();
545 /* Hide/unhide columns to match added/removed fields */
548 $.each(added_fields, function (index, field) {
549 var index = object.getColIndex(field,cols);
551 object.table.fnSetColumnVis(index, true);
556 $.each(removed_fields, function (index, field) {
557 var index = object.getColIndex(field,cols);
559 object.table.fnSetColumnVis(index, false);
563 alert('Hazelnut::clear_fields() not implemented');
571 /***************************************************************************
573 * xxx I'm not sure why this should not be methods in the Hazelnut class above
574 ***************************************************************************/
577 * @brief Hazelnut filtering function
579 function hazelnut_filter (oSettings, aData, iDataIndex) {
580 var cur_query = this.current_query;
581 if (!cur_query) return true;
584 /* We have an array of filters : a filter is an array (key op val)
585 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
586 * can we exploit the data property somewhere ?
587 * field values (unless formatting) : aData
588 * formatting should leave original data available in a hidden field
590 * The current line should validate all filters
592 $.each (cur_query.filters, function(index, filter) {
593 /* XXX How to manage checkbox ? */
596 var value = filter[2];
598 /* Determine index of key in the table columns */
599 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
601 /* Unknown key: no filtering */
602 if (typeof(col) == 'undefined')
605 col_value=unfold.get_value(aData[col]);
606 /* Test whether current filter is compatible with the column */
607 if (op == '=' || op == '==') {
608 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
610 }else if (op == '!=') {
611 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
614 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
617 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
619 } else if(op=='<=' || op=='≤') {
620 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
622 } else if(op=='>=' || op=='≥') {
623 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
626 // How to break out of a loop ?
627 alert("filter not supported");
635 function hazelnut_draw_callback() {
636 var options = this.options;
638 * Handle clicks on checkboxes: reassociate checkbox click every time
639 * the table is redrawn
641 $('.hazelnut-checkbox-' + options.plugin_uuid).unbind('click');
642 $('.hazelnut-checkbox-' + options.plugin_uuid).click({instance: this}, check_click);
647 /* Remove pagination if we show only a few results */
648 var wrapper = this.table; //.parent().parent().parent();
649 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
650 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
651 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
653 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
654 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
656 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
659 if ( rowsToShow <= minRowsPerPage ) {
660 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
662 $('.hazelnut_length', wrapper).css('visibility', 'visible');
666 function check_click (e) {
668 var object = e.data.instance;
670 /* The key of the object to be added */
671 // XXX What about multiple keys ?
672 var value = this.value;
675 manifold.raise_event(object.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, value);
677 // OLD PLUGIN API BELOW
680 object.current_resources.push(value);
682 tmp = $.grep(object.current_resources, function(x) { return x != value; });
683 object.current_resources = tmp;
686 /* inform slice that our selected resources have changed */
687 $.publish('/update-set/' + object.options.query_uuid, [object.current_resources, true]);
691 function selectAll() {
692 // requires jQuery id
693 var uuid=this.id.split("-");
694 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
695 // Function available in Hazelnut 1.9.x
696 // Filter : displayed data only
697 var filterData = oTable._('tr', {"filter":"applied"});
698 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
699 if(filterData.length<=100){
700 $.each(filterData, function(index, obj) {
701 var last=$(obj).last();
702 var key_value=unfold.get_value(last[0]);
703 if(typeof($(last[0]).attr('checked'))=="undefined"){
704 $.publish('selected', 'add/'+key_value);