2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
13 var Hazelnut = Plugin.extend({
15 init: function(options, element)
17 this._super(options, element);
19 /* Member variables */
20 // in general we expect 2 queries here
21 // query_uuid refers to a single object (typically a slice)
22 // query_all_uuid refers to a list (typically resources or users)
23 // these can return in any order so we keep track of which has been received yet
24 this.received_all_query = false;
25 this.received_query = false;
27 // an internal buffer for records that are 'in' and thus need to be checked
28 this.buffered_records_to_check = [];
29 // an internal buffer for keeping lines and display them in one call to fnAddData
30 this.buffered_lines = [];
33 // this.$element.on('show.Datatables', this.on_show);
34 this.elmt().on('show', this, this.on_show);
35 // Unbind all events using namespacing
37 // $(window).unbind('Hazelnut');
39 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
40 this.method = query.object;
42 var keys = manifold.metadata.get_key(this.method);
43 this.key = (keys && keys.length == 1) ? keys[0] : null;
45 /* Setup query and record handlers */
46 this.listen_query(options.query_uuid);
47 this.listen_query(options.query_all_uuid, 'all');
49 /* GUI setup and event binding */
50 this.initialize_table();
63 self.table.fnAdjustColumnSizing()
65 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
66 /* temp disabled... useful ? -- jordan
67 $(this).each(function(i,elt) {
68 if (jQuery(elt).hasClass('dataTables')) {
69 var myDiv=jQuery('#hazelnut-' + this.id).parent();
70 if(myDiv.height()==0) {
71 var oTable=$('#hazelnut-' + this.id).dataTable();
81 /* GUI MANIPULATION */
83 initialize_table: function()
85 /* Transforms the table into DataTable, and keep a pointer to it */
88 // Customize the position of Datatables elements (length,filter,button,...)
89 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
90 sDom: "<'row'<'col-md-5'l><'col-md-1'r><'col-md-6'f>>t<'row'<'col-md-5'i><'col-md-7'p>>",
91 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
92 // hopefully this would come with dataTables v1.10 ?
93 // in any case, search for 'sPaginationType' all over the code for more comments
94 sPaginationType: 'full_numbers',
95 // Handle the null values & the error : Datatables warning Requested unknown parameter
96 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
97 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
98 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
99 // sScrollX: '100%', /* Horizontal scrolling */
100 bProcessing: true, /* Loading */
101 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
102 // XXX use $.proxy here !
104 // the intention here is that options.datatables_options as coming from the python object take precedence
105 // xxx DISABLED by jordan: was causing errors in datatables.js
106 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
107 // check your datatables_options tag instead
108 $.extend(actual_options, this.options.datatables_options );
109 this.table = this.elmt('table').dataTable(actual_options);
111 /* Setup the SelectAll button in the dataTable header */
112 /* xxx not sure this is still working */
113 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
114 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
116 oSelectAll.css('font-size','11px');
117 oSelectAll.css('float','right');
118 oSelectAll.css('margin-right','15px');
119 oSelectAll.css('margin-bottom','5px');
120 oSelectAll.unbind('click');
121 oSelectAll.click(this._selectAll);
123 /* Add a filtering function to the current table
124 * Note: we use closure to get access to the 'options'
126 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
127 /* No filtering if the table does not match */
128 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
130 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
133 /* Processing hidden_columns */
134 $.each(this.options.hidden_columns, function(i, field) {
135 self.hide_column(field);
137 }, // initialize_table
140 * @brief Determine index of key in the table columns
144 getColIndex: function(key, cols) {
145 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
146 return (tabIndex.length > 0) ? tabIndex[0] : -1;
149 checkbox: function (key, value)
152 // Prefix id with plugin_uuid
154 result += " class='hazelnut-checkbox'";
155 result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
156 result += " name='" + key + "'";
157 result += " type='checkbox'";
158 result += " autocomplete='off'";
159 result += " value='" + value + "'";
160 result += "></input>";
165 new_record: function(record)
167 // this models a line in dataTables, each element in the line describes a cell
170 // go through table headers to get column names we want
171 // in order (we have temporarily hack some adjustments in names)
172 var cols = this.table.fnSettings().aoColumns;
173 var colnames = cols.map(function(x) {return x.sTitle})
174 var nb_col = cols.length;
175 /* if we've requested checkboxes, then forget about the checkbox column for now */
176 if (this.options.checkboxes) nb_col -= 1;
178 /* fill in stuff depending on the column name */
179 for (var j = 0; j < nb_col; j++) {
180 if (typeof colnames[j] == 'undefined') {
182 } else if (colnames[j] == 'hostname') {
183 if (record['type'] == 'resource,link')
184 //TODO: we need to add source/destination for links
187 line.push(record['hostname']);
189 if (record[colnames[j]])
190 line.push(record[colnames[j]]);
196 /* catch up with the last column if checkboxes were requested */
197 if (this.options.checkboxes)
198 // Use a key instead of hostname (hard coded...)
199 // XXX remove the empty checked attribute
200 line.push(this.checkbox(this.key, record[this.key]));
202 // adding an array in one call is *much* more efficient
203 // this.table.fnAddData(line);
204 this.buffered_lines.push(line)
208 clear_table: function()
210 this.table.fnClearTable();
213 redraw_table: function()
218 show_column: function(field)
220 var oSettings = this.table.fnSettings();
221 var cols = oSettings.aoColumns;
222 var index = this.getColIndex(field,cols);
224 this.table.fnSetColumnVis(index, true);
227 hide_column: function(field)
229 var oSettings = this.table.fnSettings();
230 var cols = oSettings.aoColumns;
231 var index = this.getColIndex(field,cols);
233 this.table.fnSetColumnVis(index, false);
236 set_checkbox: function(record, checked)
238 /* Default: checked = true */
239 if (typeof checked === 'undefined')
243 /* The function accepts both records and their key */
244 switch (manifold.get_type(record)) {
249 /* XXX Test the key before ? */
250 key_value = record[this.key];
253 throw "Not implemented";
258 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
259 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
261 var element = $(checkbox_id, this.table.fnGetNodes());
263 element.attr('checked', checked);
266 /*************************** QUERY HANDLER ****************************/
268 on_filter_added: function(filter)
274 on_filter_removed: function(filter)
280 on_filter_clear: function()
286 on_field_added: function(field)
288 this.show_column(field);
291 on_field_removed: function(field)
293 this.hide_column(field);
296 on_field_clear: function()
298 alert('Hazelnut::clear_fields() not implemented');
301 /*************************** RECORD HANDLER ***************************/
303 on_new_record: function(record)
305 if (this.received_all_query) {
306 // if the 'all' query has been dealt with already we may turn on the checkbox
307 this.set_checkbox(record, true);
309 // otherwise we need to remember that and do it later on
310 this.buffered_records_to_check.push(record);
311 console.log ("Remembering record to check " + record);
315 on_clear_records: function()
319 // Could be the default in parent
320 on_query_in_progress: function()
325 on_query_done: function()
327 if (this.received_all_query)
329 this.received_query = true;
332 on_field_state_changed: function(data)
334 switch(data.request) {
335 case FIELD_REQUEST_ADD:
336 case FIELD_REQUEST_ADD_RESET:
337 this.set_checkbox(data.value, true);
339 case FIELD_REQUEST_REMOVE:
340 case FIELD_REQUEST_REMOVE_RESET:
341 this.set_checkbox(data.value, false);
350 on_all_new_record: function(record)
352 this.new_record(record);
355 on_all_clear_records: function()
361 on_all_query_in_progress: function()
365 }, // on_all_query_in_progress
367 on_all_query_done: function()
370 if (this.received_query) {
371 /* XXX needed ? XXX We uncheck all checkboxes ... */
372 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
374 /* ... and check the ones specified in the resource list */
375 $.each(this.buffered_records_to_check, function(i, record) {
376 self.set_checkbox(record, true);
381 this.table.fnAddData (this.buffered_lines);
382 this.buffered_lines=[];
383 this.received_all_query = true;
385 }, // on_all_query_done
387 /************************** PRIVATE METHODS ***************************/
390 * @brief Hazelnut filtering function
392 _hazelnut_filter: function(oSettings, aData, iDataIndex)
394 var cur_query = this.current_query;
395 if (!cur_query) return true;
398 /* We have an array of filters : a filter is an array (key op val)
399 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
400 * can we exploit the data property somewhere ?
401 * field values (unless formatting) : aData
402 * formatting should leave original data available in a hidden field
404 * The current line should validate all filters
406 $.each (cur_query.filters, function(index, filter) {
407 /* XXX How to manage checkbox ? */
410 var value = filter[2];
412 /* Determine index of key in the table columns */
413 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
415 /* Unknown key: no filtering */
416 if (typeof(col) == 'undefined')
419 col_value=unfold.get_value(aData[col]);
420 /* Test whether current filter is compatible with the column */
421 if (op == '=' || op == '==') {
422 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
424 }else if (op == '!=') {
425 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
428 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
431 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
433 } else if(op=='<=' || op=='≤') {
434 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
436 } else if(op=='>=' || op=='≥') {
437 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
440 // How to break out of a loop ?
441 alert("filter not supported");
449 _hazelnut_draw_callback: function()
452 * Handle clicks on checkboxes: reassociate checkbox click every time
453 * the table is redrawn
455 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
460 /* Remove pagination if we show only a few results */
461 var wrapper = this.table; //.parent().parent().parent();
462 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
463 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
464 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
466 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
467 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
469 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
472 if ( rowsToShow <= minRowsPerPage ) {
473 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
475 $('.hazelnut_length', wrapper).css('visibility', 'visible');
479 _check_click: function(e)
485 // XXX this.value = key of object to be added... what about multiple keys ?
486 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
487 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
491 _selectAll: function()
493 // requires jQuery id
494 var uuid=this.id.split("-");
495 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
496 // Function available in Hazelnut 1.9.x
497 // Filter : displayed data only
498 var filterData = oTable._('tr', {"filter":"applied"});
499 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
500 if(filterData.length<=100){
501 $.each(filterData, function(index, obj) {
502 var last=$(obj).last();
503 var key_value=unfold.get_value(last[0]);
504 if(typeof($(last[0]).attr('checked'))=="undefined"){
505 $.publish('selected', 'add/'+key_value);
513 $.plugin('Hazelnut', Hazelnut);
515 /* define the 'dom-checkbox' type for sorting in datatables
516 http://datatables.net/examples/plug-ins/dom_sort.html
517 using trial and error I found that the actual column number
518 was in fact given as a third argument, and not second
519 as the various online resources had it - go figure */
520 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
521 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
522 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';