2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
10 var ELEMENT_KEY = 'resource_hrn';
14 var Hazelnut = Plugin.extend({
16 init: function(options, element)
18 this._super(options, element);
20 /* Member variables */
22 this.received_all = false;
23 this.received_set = false;
24 this.in_set_buffer = Array();
27 this.$element.on('show.Datatables', this.on_show);
28 // Unbind all events using namespacing
30 // $(window).unbind('Hazelnut');
32 /* Setup query and record handlers */
33 this.listen_query(options.query_uuid);
34 this.listen_query(options.query_all_uuid, 'all');
36 /* GUI setup and event binding */
37 this.initialize_table();
50 // xxx wtf. why [1] ? would expect 0...
52 messages.debug("Hitting suspicious line in hazelnut.show");
53 var oTable = $($('.dataTable', $this)[1]).dataTable();
54 oTable.fnAdjustColumnSizing()
56 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
57 $(this).each(function(i,elt) {
58 if (jQuery(elt).hasClass('dataTables')) {
59 var myDiv=jQuery('#hazelnut-' + this.id).parent();
60 if(myDiv.height()==0) {
61 var oTable=$('#hazelnut-' + this.id).dataTable();
70 /* GUI MANIPULATION */
72 initialize_table: function() {
73 /* Transforms the table into DataTable, and keep a pointer to it */
76 // Customize the position of Datatables elements (length,filter,button,...)
77 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
78 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
79 sPaginationType: 'bootstrap',
80 // Handle the null values & the error : Datatables warning Requested unknown parameter
81 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
82 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
83 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
84 // sScrollX: '100%', /* Horizontal scrolling */
85 bProcessing: true, /* Loading */
86 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
87 // XXX use $.proxy here !
89 // the intention here is that options.datatables_options as coming from the python object take precedence
90 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
91 this.table = this.el('table').dataTable(actual_options);
93 /* Setup the SelectAll button in the dataTable header */
94 /* xxx not sure this is still working */
95 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
96 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
98 oSelectAll.css('font-size','11px');
99 oSelectAll.css('float','right');
100 oSelectAll.css('margin-right','15px');
101 oSelectAll.css('margin-bottom','5px');
102 oSelectAll.unbind('click');
103 oSelectAll.click(this._selectAll);
105 /* Add a filtering function to the current table
106 * Note: we use closure to get access to the 'options'
108 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
109 /* No filtering if the table does not match */
110 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
112 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
115 /* Processing hidden_columns */
116 $.each(this.options.hidden_columns, function(i, field) {
117 self.hide_column(field);
119 }, // initialize_table
122 * @brief Determine index of key in the table columns
126 getColIndex: function(key, cols) {
127 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
128 return (tabIndex.length > 0) ? tabIndex[0] : -1;
131 // UNUSED ? // this.update_plugin = function(e, rows) {
132 // UNUSED ? // // e.data is what we passed in second argument to subscribe
133 // UNUSED ? // // so here it is the jquery object attached to the plugin <div>
134 // UNUSED ? // var $plugindiv=e.data;
135 // UNUSED ? // if (debug)
136 // UNUSED ? // messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
137 // UNUSED ? // // clear the spinning wheel: look up an ancestor that has the need-spin class
138 // UNUSED ? // // do this before we might return
139 // UNUSED ? // $plugindiv.closest('.need-spin').spin(false);
141 // UNUSED ? // var options = this.options;
142 // UNUSED ? // var hazelnut = this;
144 // UNUSED ? // /* if we get no result, or an error, try to make that clear, and exit */
145 // UNUSED ? // if (rows.length==0) {
146 // UNUSED ? // if (debug)
147 // UNUSED ? // messages.debug("Empty result on hazelnut " + this.options.domid);
148 // UNUSED ? // var placeholder=$(this.table).find("td.dataTables_empty");
149 // UNUSED ? // console.log("placeholder "+placeholder);
150 // UNUSED ? // if (placeholder.length==1)
151 // UNUSED ? // placeholder.html(unfold.warning("Empty result"));
153 // UNUSED ? // this.table.html(unfold.warning("Empty result"));
154 // UNUSED ? // return;
155 // UNUSED ? // } else if (typeof(rows[0].error) != 'undefined') {
156 // UNUSED ? // // we now should have another means to report errors that this inline/embedded hack
157 // UNUSED ? // if (debug)
158 // UNUSED ? // messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
159 // UNUSED ? // this.table.html(unfold.error(rows[0].error));
160 // UNUSED ? // return;
164 // UNUSED ? // * fill the dataTables object
165 // UNUSED ? // * we cannot set html content directly here, need to use fnAddData
167 // UNUSED ? // var lines = new Array();
169 // UNUSED ? // this.current_resources = Array();
171 // UNUSED ? // $.each(rows, function(index, row) {
172 // UNUSED ? // // this models a line in dataTables, each element in the line describes a cell
173 // UNUSED ? // line = new Array();
175 // UNUSED ? // // go through table headers to get column names we want
176 // UNUSED ? // // in order (we have temporarily hack some adjustments in names)
177 // UNUSED ? // var cols = object.table.fnSettings().aoColumns;
178 // UNUSED ? // var colnames = cols.map(function(x) {return x.sTitle})
179 // UNUSED ? // var nb_col = cols.length;
180 // UNUSED ? // /* if we've requested checkboxes, then forget about the checkbox column for now */
181 // UNUSED ? // if (options.checkboxes) nb_col -= 1;
183 // UNUSED ? // /* fill in stuff depending on the column name */
184 // UNUSED ? // for (var j = 0; j < nb_col; j++) {
185 // UNUSED ? // if (typeof colnames[j] == 'undefined') {
186 // UNUSED ? // line.push('...');
187 // UNUSED ? // } else if (colnames[j] == 'hostname') {
188 // UNUSED ? // if (row['type'] == 'resource,link')
189 // UNUSED ? // //TODO: we need to add source/destination for links
190 // UNUSED ? // line.push('');
192 // UNUSED ? // line.push(row['hostname']);
193 // UNUSED ? // } else {
194 // UNUSED ? // if (row[colnames[j]])
195 // UNUSED ? // line.push(row[colnames[j]]);
197 // UNUSED ? // line.push('');
201 // UNUSED ? // /* catch up with the last column if checkboxes were requested */
202 // UNUSED ? // if (options.checkboxes) {
203 // UNUSED ? // var checked = '';
204 // UNUSED ? // // xxx problem is, we don't get this 'sliver' thing set apparently
205 // UNUSED ? // if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
206 // UNUSED ? // checked = 'checked ';
207 // UNUSED ? // hazelnut.current_resources.push(row[ELEMENT_KEY]);
209 // UNUSED ? // // Use a key instead of hostname (hard coded...)
210 // UNUSED ? // line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
213 // UNUSED ? // lines.push(line);
217 // UNUSED ? // this.table.fnClearTable();
218 // UNUSED ? // if (debug)
219 // UNUSED ? // messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
220 // UNUSED ? // this.table.fnAddData(lines);
222 // UNUSED ? // }, // update_plugin
224 checkbox: function (plugin_uuid, header, field, selected_str, disabled_str)
229 // Prefix id with plugin_uuid
231 result += " class='hazelnut-checkbox-" + plugin_uuid + "'";
232 result += " id='hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '') + "'";
233 result += " name='" + unfold.get_value(field) + "'";
234 result += " type='checkbox'";
235 result += selected_str;
236 result += disabled_str;
237 result += " autocomplete='off'";
238 result += " value='" + unfold.get_value(header) + "'";
239 result += "></input>";
244 new_record: function(record)
246 // this models a line in dataTables, each element in the line describes a cell
249 // go through table headers to get column names we want
250 // in order (we have temporarily hack some adjustments in names)
251 var cols = this.table.fnSettings().aoColumns;
252 var colnames = cols.map(function(x) {return x.sTitle})
253 var nb_col = cols.length;
254 /* if we've requested checkboxes, then forget about the checkbox column for now */
255 if (this.options.checkboxes) nb_col -= 1;
257 /* fill in stuff depending on the column name */
258 for (var j = 0; j < nb_col; j++) {
259 if (typeof colnames[j] == 'undefined') {
261 } else if (colnames[j] == 'hostname') {
262 if (record['type'] == 'resource,link')
263 //TODO: we need to add source/destination for links
266 line.push(record['hostname']);
268 if (record[colnames[j]])
269 line.push(record[colnames[j]]);
275 /* catch up with the last column if checkboxes were requested */
276 if (this.options.checkboxes) {
278 // xxx problem is, we don't get this 'sliver' thing set apparently
279 if (typeof(record['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
280 checked = 'checked ';
281 hazelnut.current_resources.push(record[ELEMENT_KEY]);
283 // Use a key instead of hostname (hard coded...)
284 line.push(this.checkbox(this.options.plugin_uuid, record[ELEMENT_KEY], record['type'], checked, false));
287 // XXX Is adding an array of lines more efficient ?
288 this.table.fnAddData(line);
292 clear_table: function()
294 this.table.fnClearTable();
297 redraw_table: function()
302 show_column: function(field)
304 var oSettings = this.table.fnSettings();
305 var cols = oSettings.aoColumns;
306 var index = this.getColIndex(field,cols);
308 this.table.fnSetColumnVis(index, true);
311 hide_column: function(field)
313 var oSettings = this.table.fnSettings();
314 var cols = oSettings.aoColumns;
315 var index = this.getColIndex(field,cols);
317 this.table.fnSetColumnVis(index, false);
320 set_checkbox: function(record)
322 // XXX urn should be replaced by the key
323 // XXX we should enforce that both queries have the same key !!
324 checkbox_id = "#hazelnut-checkbox-" + this.options.plugin_uuid + "-" + unfold.escape_id(record[ELEMENT_KEY].replace(/\\/g, ''))
325 $(checkbox_id, this.table.fnGetNodes()).attr('checked', true);
328 /*************************** QUERY HANDLER ****************************/
330 on_filter_added: function(filter)
336 on_filter_removed: function(filter)
342 on_filter_clear: function()
348 on_field_added: function(field)
350 this.show_column(field);
353 on_field_removed: function(field)
355 this.hide_column(field);
358 on_field_clear: function()
360 alert('Hazelnut::clear_fields() not implemented');
363 /* RECORD HANDLERS */
365 on_new_record: function(record)
367 /* NOTE in fact we are doing a join here */
368 if (this.received_all)
369 // update checkbox for record
370 this.set_checkbox(record);
372 // store for later update of checkboxes
373 this.in_set_buffer.push(record);
376 on_clear_records: function()
380 // Could be the default in parent
381 on_query_in_progress: function()
386 on_query_done: function()
388 if (this.received_all)
390 this.received_set = true;
395 on_all_new_record: function(record)
397 this.new_record(record);
400 on_all_clear_records: function()
406 on_all_query_in_progress: function()
410 }, // on_all_query_in_progress
412 on_all_query_done: function()
415 if (this.received_set) {
416 /* XXX needed ? XXX We uncheck all checkboxes ... */
417 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
419 /* ... and check the ones specified in the resource list */
420 $.each(this.in_set_buffer, function(i, record) {
421 self.set_checkbox(record);
426 this.received_all = true;
428 }, // on_all_query_done
430 /************************** PRIVATE METHODS ***************************/
433 * @brief Hazelnut filtering function
435 _hazelnut_filter: function(oSettings, aData, iDataIndex)
437 var cur_query = this.current_query;
438 if (!cur_query) return true;
441 /* We have an array of filters : a filter is an array (key op val)
442 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
443 * can we exploit the data property somewhere ?
444 * field values (unless formatting) : aData
445 * formatting should leave original data available in a hidden field
447 * The current line should validate all filters
449 $.each (cur_query.filters, function(index, filter) {
450 /* XXX How to manage checkbox ? */
453 var value = filter[2];
455 /* Determine index of key in the table columns */
456 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
458 /* Unknown key: no filtering */
459 if (typeof(col) == 'undefined')
462 col_value=unfold.get_value(aData[col]);
463 /* Test whether current filter is compatible with the column */
464 if (op == '=' || op == '==') {
465 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
467 }else if (op == '!=') {
468 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
471 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
474 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
476 } else if(op=='<=' || op=='≤') {
477 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
479 } else if(op=='>=' || op=='≥') {
480 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
483 // How to break out of a loop ?
484 alert("filter not supported");
492 _hazelnut_draw_callback: function()
495 * Handle clicks on checkboxes: reassociate checkbox click every time
496 * the table is redrawn
498 $('.hazelnut-checkbox-' + this.options.plugin_uuid).unbind('click');
499 $('.hazelnut-checkbox-' + this.options.plugin_uuid).click({instance: this}, this._check_click);
504 /* Remove pagination if we show only a few results */
505 var wrapper = this.table; //.parent().parent().parent();
506 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
507 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
508 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
510 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
511 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
513 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
516 if ( rowsToShow <= minRowsPerPage ) {
517 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
519 $('.hazelnut_length', wrapper).css('visibility', 'visible');
523 _check_click: function(e)
526 var self = e.data.instance;
528 // XXX this.value = key of object to be added... what about multiple keys ?
529 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
533 _selectAll: function()
535 // requires jQuery id
536 var uuid=this.id.split("-");
537 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
538 // Function available in Hazelnut 1.9.x
539 // Filter : displayed data only
540 var filterData = oTable._('tr', {"filter":"applied"});
541 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
542 if(filterData.length<=100){
543 $.each(filterData, function(index, obj) {
544 var last=$(obj).last();
545 var key_value=unfold.get_value(last[0]);
546 if(typeof($(last[0]).attr('checked'))=="undefined"){
547 $.publish('selected', 'add/'+key_value);
555 $.plugin('Hazelnut', Hazelnut);