2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
7 //debug_table = function (table,message) {
8 // messages.debug ( message + ": " + table.fnSettings().aoColumns.length + " columns");
9 // messages.debug ( message + ":..." + table.fnGetNodes().length + " lines");
18 var Hazelnut = Plugin.extend({
20 init: function(options, element)
22 this._super(options, element);
24 /* Member variables */
25 // in general we expect 2 queries here
26 // query_uuid refers to a single object (typically a slice)
27 // query_all_uuid refers to a list (typically resources or users)
28 // these can return in any order so we keep track of which has been received yet
29 this.received_all_query = false;
30 this.received_query = false;
32 // an internal buffer for records that are 'in' and thus need to be checked
33 this.buffered_records_to_check = [];
34 // an internal buffer for keeping lines and display them in one call to fnAddData
35 this.buffered_lines = [];
38 // this.$element.on('show.Datatables', this.on_show);
39 this.elmt().on('show', this, this.on_show);
40 // Unbind all events using namespacing
42 // $(window).unbind('Hazelnut');
44 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
45 this.method = query.object;
47 var keys = manifold.metadata.get_key(this.method);
48 this.key = (keys && keys.length == 1) ? keys[0] : null;
50 /* Setup query and record handlers */
51 this.listen_query(options.query_uuid);
52 this.listen_query(options.query_all_uuid, 'all');
54 /* GUI setup and event binding */
55 this.initialize_table();
64 self.table.fnAdjustColumnSizing()
66 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
67 /* temp disabled... useful ? -- jordan
68 $(this).each(function(i,elt) {
69 if (jQuery(elt).hasClass('dataTables')) {
70 var myDiv=jQuery('#hazelnut-' + this.id).parent();
71 if(myDiv.height()==0) {
72 var oTable=$('#hazelnut-' + this.id).dataTable();
82 /* GUI MANIPULATION */
84 initialize_table: function()
86 /* Transforms the table into DataTable, and keep a pointer to it */
88 var actual_options = {
89 // Customize the position of Datatables elements (length,filter,button,...)
90 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
91 sDom: "<'row'<'col-md-5'l><'col-md-1'r><'col-md-6'f>>t<'row'<'col-md-5'i><'col-md-7'p>>",
92 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
93 // hopefully this would come with dataTables v1.10 ?
94 // in any case, search for 'sPaginationType' all over the code for more comments
95 sPaginationType: 'full_numbers',
96 // Handle the null values & the error : Datatables warning Requested unknown parameter
97 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
98 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
99 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
100 // sScrollX: '100%', /* Horizontal scrolling */
101 bProcessing: true, /* Loading */
102 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
103 // XXX use $.proxy here !
105 // the intention here is that options.datatables_options as coming from the python object take precedence
106 // xxx DISABLED by jordan: was causing errors in datatables.js
107 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
108 // check your datatables_options tag instead
109 // however, we have to accumulate in aoColumnDefs from here (above)
110 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
111 if ( 'aoColumnDefs' in this.options.datatables_options) {
112 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
113 delete this.options.datatables_options['aoColumnDefs'];
115 $.extend(actual_options, this.options.datatables_options );
116 this.table = this.elmt('table').dataTable(actual_options);
118 /* Setup the SelectAll button in the dataTable header */
119 /* xxx not sure this is still working */
120 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
121 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
123 oSelectAll.css('font-size','11px');
124 oSelectAll.css('float','right');
125 oSelectAll.css('margin-right','15px');
126 oSelectAll.css('margin-bottom','5px');
127 oSelectAll.unbind('click');
128 oSelectAll.click(this._selectAll);
130 /* Add a filtering function to the current table
131 * Note: we use closure to get access to the 'options'
133 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
134 /* No filtering if the table does not match */
135 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
137 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
140 /* Processing hidden_columns */
141 $.each(this.options.hidden_columns, function(i, field) {
142 self.hide_column(field);
144 }, // initialize_table
147 * @brief Determine index of key in the table columns
151 getColIndex: function(key, cols) {
152 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
153 return (tabIndex.length > 0) ? tabIndex[0] : -1;
156 checkbox_html : function (key, value)
159 // Prefix id with plugin_uuid
161 result += " class='hazelnut-checkbox'";
162 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
163 result += " name='" + key + "'";
164 result += " type='checkbox'";
165 result += " autocomplete='off'";
166 result += " value='" + value + "'";
167 result += "></input>";
172 new_record: function(record)
174 // this models a line in dataTables, each element in the line describes a cell
177 // go through table headers to get column names we want
178 // in order (we have temporarily hack some adjustments in names)
179 var cols = this.table.fnSettings().aoColumns;
180 var colnames = cols.map(function(x) {return x.sTitle})
181 var nb_col = cols.length;
182 /* if we've requested checkboxes, then forget about the checkbox column for now */
183 if (this.options.checkboxes) nb_col -= 1;
185 /* fill in stuff depending on the column name */
186 for (var j = 0; j < nb_col; j++) {
187 if (typeof colnames[j] == 'undefined') {
189 } else if (colnames[j] == 'hostname') {
190 if (record['type'] == 'resource,link')
191 //TODO: we need to add source/destination for links
194 line.push(record['hostname']);
196 if (record[colnames[j]])
197 line.push(record[colnames[j]]);
203 // catch up with the last column if checkboxes were requested
204 if (this.options.checkboxes) {
205 // Use a key instead of hostname (hard coded...)
206 line.push(this.checkbox_html(this.key, record[this.key]));
209 // adding an array in one call is *much* more efficient
210 // this.table.fnAddData(line);
211 this.buffered_lines.push(line);
215 clear_table: function()
217 this.table.fnClearTable();
220 redraw_table: function()
225 show_column: function(field)
227 var oSettings = this.table.fnSettings();
228 var cols = oSettings.aoColumns;
229 var index = this.getColIndex(field,cols);
231 this.table.fnSetColumnVis(index, true);
234 hide_column: function(field)
236 var oSettings = this.table.fnSettings();
237 var cols = oSettings.aoColumns;
238 var index = this.getColIndex(field,cols);
240 this.table.fnSetColumnVis(index, false);
243 set_checkbox: function(record, checked)
245 /* Default: checked = true */
246 if (checked === undefined) checked = true;
249 /* The function accepts both records and their key */
250 switch (manifold.get_type(record)) {
255 /* XXX Test the key before ? */
256 key_value = record[this.key];
259 throw "Not implemented";
264 var checkbox_id = this.flat_id(this.id('checkbox', key_value));
265 checkbox_id = '#' + checkbox_id;
266 // using dataTables's $ to search also in nodes that are not currently displayed
267 var element = this.table.$(checkbox_id);
268 if (debug) messages.debug("set_checkbox checked=" + checked + " id=" + checkbox_id + " matches=" + element.length);
269 element.attr('checked', checked);
272 /*************************** QUERY HANDLER ****************************/
274 on_filter_added: function(filter)
280 on_filter_removed: function(filter)
286 on_filter_clear: function()
292 on_field_added: function(field)
294 this.show_column(field);
297 on_field_removed: function(field)
299 this.hide_column(field);
302 on_field_clear: function()
304 alert('Hazelnut::clear_fields() not implemented');
307 /*************************** RECORD HANDLER ***************************/
309 on_new_record: function(record)
311 if (this.received_all_query) {
312 // if the 'all' query has been dealt with already we may turn on the checkbox
313 if (debug) messages.debug("turning on checkbox for record "+record[this.key]);
314 this.set_checkbox(record, true);
316 // otherwise we need to remember that and do it later on
317 if (debug) messages.debug ("Remembering record to check " + record[this.key]);
318 this.buffered_records_to_check.push(record);
322 on_clear_records: function()
326 // Could be the default in parent
327 on_query_in_progress: function()
332 on_query_done: function()
334 this.received_query = true;
335 // unspin once we have received both
336 if (this.received_all_query && this.received_query) this.unspin();
339 on_field_state_changed: function(data)
341 switch(data.request) {
342 case FIELD_REQUEST_ADD:
343 case FIELD_REQUEST_ADD_RESET:
344 this.set_checkbox(data.value, true);
346 case FIELD_REQUEST_REMOVE:
347 case FIELD_REQUEST_REMOVE_RESET:
348 this.set_checkbox(data.value, false);
357 on_all_new_record: function(record)
359 this.new_record(record);
362 on_all_clear_records: function()
368 on_all_query_in_progress: function()
372 }, // on_all_query_in_progress
374 on_all_query_done: function()
376 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
377 this.table.fnAddData (this.buffered_lines);
378 this.buffered_lines=[];
381 // if we've already received the slice query, we have not been able to set
382 // checkboxes on the fly at that time (dom not yet created)
383 $.each(this.buffered_records_to_check, function(i, record) {
384 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
385 self.set_checkbox(record, true);
387 this.buffered_records_to_check = [];
389 this.received_all_query = true;
390 // unspin once we have received both
391 if (this.received_all_query && this.received_query) this.unspin();
393 }, // on_all_query_done
395 /************************** PRIVATE METHODS ***************************/
398 * @brief Hazelnut filtering function
400 _hazelnut_filter: function(oSettings, aData, iDataIndex)
402 var cur_query = this.current_query;
403 if (!cur_query) return true;
406 /* We have an array of filters : a filter is an array (key op val)
407 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
408 * can we exploit the data property somewhere ?
409 * field values (unless formatting) : aData
410 * formatting should leave original data available in a hidden field
412 * The current line should validate all filters
414 $.each (cur_query.filters, function(index, filter) {
415 /* XXX How to manage checkbox ? */
418 var value = filter[2];
420 /* Determine index of key in the table columns */
421 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
423 /* Unknown key: no filtering */
424 if (typeof(col) == 'undefined')
427 col_value=unfold.get_value(aData[col]);
428 /* Test whether current filter is compatible with the column */
429 if (op == '=' || op == '==') {
430 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
432 }else if (op == '!=') {
433 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
436 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
439 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
441 } else if(op=='<=' || op=='≤') {
442 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
444 } else if(op=='>=' || op=='≥') {
445 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
448 // How to break out of a loop ?
449 alert("filter not supported");
457 _hazelnut_draw_callback: function()
460 * Handle clicks on checkboxes: reassociate checkbox click every time
461 * the table is redrawn
463 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
468 /* Remove pagination if we show only a few results */
469 var wrapper = this.table; //.parent().parent().parent();
470 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
471 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
472 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
474 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
475 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
477 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
480 if ( rowsToShow <= minRowsPerPage ) {
481 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
483 $('.hazelnut_length', wrapper).css('visibility', 'visible');
487 _check_click: function(e)
493 // XXX this.value = key of object to be added... what about multiple keys ?
494 if (debug) messages.debug("hazelnut click handler checked=" + this.checked + " hrn=" + this.value);
495 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
496 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
500 _selectAll: function()
502 // requires jQuery id
503 var uuid=this.id.split("-");
504 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
505 // Function available in Hazelnut 1.9.x
506 // Filter : displayed data only
507 var filterData = oTable._('tr', {"filter":"applied"});
508 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
509 if(filterData.length<=100){
510 $.each(filterData, function(index, obj) {
511 var last=$(obj).last();
512 var key_value=unfold.get_value(last[0]);
513 if(typeof($(last[0]).attr('checked'))=="undefined"){
514 $.publish('selected', 'add/'+key_value);
522 $.plugin('Hazelnut', Hazelnut);
524 /* define the 'dom-checkbox' type for sorting in datatables
525 http://datatables.net/examples/plug-ins/dom_sort.html
526 using trial and error I found that the actual column number
527 was in fact given as a third argument, and not second
528 as the various online resources had it - go figure */
529 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
530 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
531 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';