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 */
21 this.received_all = false;
22 this.received_set = false;
23 this.in_set_buffer = Array();
26 // this.$element.on('show.Datatables', this.on_show);
27 this.el().on('show', this, this.on_show);
28 // Unbind all events using namespacing
30 // $(window).unbind('Hazelnut');
32 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
33 this.method = query.object;
35 var keys = manifold.metadata.get_key(this.method);
36 this.key = (keys && keys.length == 1) ? keys[0] : null;
38 /* Setup query and record handlers */
39 this.listen_query(options.query_uuid);
40 this.listen_query(options.query_all_uuid, 'all');
42 /* GUI setup and event binding */
43 this.initialize_table();
56 self.table.fnAdjustColumnSizing()
58 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
59 /* temp disabled... useful ? -- jordan
60 $(this).each(function(i,elt) {
61 if (jQuery(elt).hasClass('dataTables')) {
62 var myDiv=jQuery('#hazelnut-' + this.id).parent();
63 if(myDiv.height()==0) {
64 var oTable=$('#hazelnut-' + this.id).dataTable();
74 /* GUI MANIPULATION */
76 initialize_table: function()
78 /* Transforms the table into DataTable, and keep a pointer to it */
81 // Customize the position of Datatables elements (length,filter,button,...)
82 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
83 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
84 sPaginationType: 'bootstrap',
85 // Handle the null values & the error : Datatables warning Requested unknown parameter
86 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
87 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
88 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
89 // sScrollX: '100%', /* Horizontal scrolling */
90 bProcessing: true, /* Loading */
91 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
92 // XXX use $.proxy here !
94 // the intention here is that options.datatables_options as coming from the python object take precedence
95 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
96 this.table = this.el('table').dataTable(actual_options);
98 /* Setup the SelectAll button in the dataTable header */
99 /* xxx not sure this is still working */
100 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
101 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
103 oSelectAll.css('font-size','11px');
104 oSelectAll.css('float','right');
105 oSelectAll.css('margin-right','15px');
106 oSelectAll.css('margin-bottom','5px');
107 oSelectAll.unbind('click');
108 oSelectAll.click(this._selectAll);
110 /* Add a filtering function to the current table
111 * Note: we use closure to get access to the 'options'
113 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
114 /* No filtering if the table does not match */
115 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
117 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
120 /* Processing hidden_columns */
121 $.each(this.options.hidden_columns, function(i, field) {
122 self.hide_column(field);
124 }, // initialize_table
127 * @brief Determine index of key in the table columns
131 getColIndex: function(key, cols) {
132 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
133 return (tabIndex.length > 0) ? tabIndex[0] : -1;
136 // UNUSED ? // this.update_plugin = function(e, rows) {
137 // UNUSED ? // // e.data is what we passed in second argument to subscribe
138 // UNUSED ? // // so here it is the jquery object attached to the plugin <div>
139 // UNUSED ? // var $plugindiv=e.data;
140 // UNUSED ? // if (debug)
141 // UNUSED ? // messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
142 // UNUSED ? // // clear the spinning wheel: look up an ancestor that has the need-spin class
143 // UNUSED ? // // do this before we might return
144 // UNUSED ? // $plugindiv.closest('.need-spin').spin(false);
146 // UNUSED ? // var options = this.options;
147 // UNUSED ? // var hazelnut = this;
149 // UNUSED ? // /* if we get no result, or an error, try to make that clear, and exit */
150 // UNUSED ? // if (rows.length==0) {
151 // UNUSED ? // if (debug)
152 // UNUSED ? // messages.debug("Empty result on hazelnut " + this.options.domid);
153 // UNUSED ? // var placeholder=$(this.table).find("td.dataTables_empty");
154 // UNUSED ? // console.log("placeholder "+placeholder);
155 // UNUSED ? // if (placeholder.length==1)
156 // UNUSED ? // placeholder.html(unfold.warning("Empty result"));
158 // UNUSED ? // this.table.html(unfold.warning("Empty result"));
159 // UNUSED ? // return;
160 // UNUSED ? // } else if (typeof(rows[0].error) != 'undefined') {
161 // UNUSED ? // // we now should have another means to report errors that this inline/embedded hack
162 // UNUSED ? // if (debug)
163 // UNUSED ? // messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
164 // UNUSED ? // this.table.html(unfold.error(rows[0].error));
165 // UNUSED ? // return;
169 // UNUSED ? // * fill the dataTables object
170 // UNUSED ? // * we cannot set html content directly here, need to use fnAddData
172 // UNUSED ? // var lines = new Array();
174 // UNUSED ? // this.current_resources = Array();
176 // UNUSED ? // $.each(rows, function(index, row) {
177 // UNUSED ? // // this models a line in dataTables, each element in the line describes a cell
178 // UNUSED ? // line = new Array();
180 // UNUSED ? // // go through table headers to get column names we want
181 // UNUSED ? // // in order (we have temporarily hack some adjustments in names)
182 // UNUSED ? // var cols = object.table.fnSettings().aoColumns;
183 // UNUSED ? // var colnames = cols.map(function(x) {return x.sTitle})
184 // UNUSED ? // var nb_col = cols.length;
185 // UNUSED ? // /* if we've requested checkboxes, then forget about the checkbox column for now */
186 // UNUSED ? // if (options.checkboxes) nb_col -= 1;
188 // UNUSED ? // /* fill in stuff depending on the column name */
189 // UNUSED ? // for (var j = 0; j < nb_col; j++) {
190 // UNUSED ? // if (typeof colnames[j] == 'undefined') {
191 // UNUSED ? // line.push('...');
192 // UNUSED ? // } else if (colnames[j] == 'hostname') {
193 // UNUSED ? // if (row['type'] == 'resource,link')
194 // UNUSED ? // //TODO: we need to add source/destination for links
195 // UNUSED ? // line.push('');
197 // UNUSED ? // line.push(row['hostname']);
198 // UNUSED ? // } else {
199 // UNUSED ? // if (row[colnames[j]])
200 // UNUSED ? // line.push(row[colnames[j]]);
202 // UNUSED ? // line.push('');
206 // UNUSED ? // /* catch up with the last column if checkboxes were requested */
207 // UNUSED ? // if (options.checkboxes) {
208 // UNUSED ? // var checked = '';
209 // UNUSED ? // // xxx problem is, we don't get this 'sliver' thing set apparently
210 // UNUSED ? // if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
211 // UNUSED ? // checked = 'checked ';
212 // UNUSED ? // hazelnut.current_resources.push(row[ELEMENT_KEY]);
214 // UNUSED ? // // Use a key instead of hostname (hard coded...)
215 // UNUSED ? // line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
218 // UNUSED ? // lines.push(line);
222 // UNUSED ? // this.table.fnClearTable();
223 // UNUSED ? // if (debug)
224 // UNUSED ? // messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
225 // UNUSED ? // this.table.fnAddData(lines);
227 // UNUSED ? // }, // update_plugin
229 checkbox: function (key, value)
232 // Prefix id with plugin_uuid
234 result += " class='hazelnut-checkbox'";
235 result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
236 result += " name='" + key + "'";
237 result += " type='checkbox'";
238 result += " autocomplete='off'";
239 result += " value='" + value + "'";
240 result += "></input>";
245 new_record: function(record)
247 // this models a line in dataTables, each element in the line describes a cell
250 // go through table headers to get column names we want
251 // in order (we have temporarily hack some adjustments in names)
252 var cols = this.table.fnSettings().aoColumns;
253 var colnames = cols.map(function(x) {return x.sTitle})
254 var nb_col = cols.length;
255 /* if we've requested checkboxes, then forget about the checkbox column for now */
256 if (this.options.checkboxes) nb_col -= 1;
258 /* fill in stuff depending on the column name */
259 for (var j = 0; j < nb_col; j++) {
260 if (typeof colnames[j] == 'undefined') {
262 } else if (colnames[j] == 'hostname') {
263 if (record['type'] == 'resource,link')
264 //TODO: we need to add source/destination for links
267 line.push(record['hostname']);
269 if (record[colnames[j]])
270 line.push(record[colnames[j]]);
276 /* catch up with the last column if checkboxes were requested */
277 if (this.options.checkboxes)
278 // Use a key instead of hostname (hard coded...)
279 // XXX remove the empty checked attribute
280 line.push(this.checkbox(this.key, record[this.key]));
282 // XXX Is adding an array of lines more efficient ?
283 this.table.fnAddData(line);
287 clear_table: function()
289 this.table.fnClearTable();
292 redraw_table: function()
297 show_column: function(field)
299 var oSettings = this.table.fnSettings();
300 var cols = oSettings.aoColumns;
301 var index = this.getColIndex(field,cols);
303 this.table.fnSetColumnVis(index, true);
306 hide_column: function(field)
308 var oSettings = this.table.fnSettings();
309 var cols = oSettings.aoColumns;
310 var index = this.getColIndex(field,cols);
312 this.table.fnSetColumnVis(index, false);
315 set_checkbox: function(record, checked)
317 /* Default: checked = true */
318 if (typeof checked === 'undefined')
322 /* The function accepts both records and their key */
323 switch (manifold.get_type(record)) {
328 /* XXX Test the key before ? */
329 key_value = record[this.key];
332 throw "Not implemented";
337 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
338 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
340 var element = $(checkbox_id, this.table.fnGetNodes());
342 element.attr('checked', checked);
345 /*************************** QUERY HANDLER ****************************/
347 on_filter_added: function(filter)
353 on_filter_removed: function(filter)
359 on_filter_clear: function()
365 on_field_added: function(field)
367 this.show_column(field);
370 on_field_removed: function(field)
372 this.hide_column(field);
375 on_field_clear: function()
377 alert('Hazelnut::clear_fields() not implemented');
380 /*************************** RECORD HANDLER ***************************/
382 on_new_record: function(record)
384 /* NOTE in fact we are doing a join here */
385 if (this.received_all)
386 // update checkbox for record
387 this.set_checkbox(record, true);
389 // store for later update of checkboxes
390 this.in_set_buffer.push(record);
393 on_clear_records: function()
397 // Could be the default in parent
398 on_query_in_progress: function()
403 on_query_done: function()
405 if (this.received_all)
407 this.received_set = true;
410 on_field_state_changed: function(data)
412 switch(data.request) {
413 case FIELD_REQUEST_ADD:
414 case FIELD_REQUEST_ADD_RESET:
415 this.set_checkbox(data.value, true);
417 case FIELD_REQUEST_REMOVE:
418 case FIELD_REQUEST_REMOVE_RESET:
419 this.set_checkbox(data.value, false);
428 on_all_new_record: function(record)
430 this.new_record(record);
433 on_all_clear_records: function()
439 on_all_query_in_progress: function()
443 }, // on_all_query_in_progress
445 on_all_query_done: function()
448 if (this.received_set) {
449 /* XXX needed ? XXX We uncheck all checkboxes ... */
450 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
452 /* ... and check the ones specified in the resource list */
453 $.each(this.in_set_buffer, function(i, record) {
454 self.set_checkbox(record, true);
459 this.received_all = true;
461 }, // on_all_query_done
463 /************************** PRIVATE METHODS ***************************/
466 * @brief Hazelnut filtering function
468 _hazelnut_filter: function(oSettings, aData, iDataIndex)
470 var cur_query = this.current_query;
471 if (!cur_query) return true;
474 /* We have an array of filters : a filter is an array (key op val)
475 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
476 * can we exploit the data property somewhere ?
477 * field values (unless formatting) : aData
478 * formatting should leave original data available in a hidden field
480 * The current line should validate all filters
482 $.each (cur_query.filters, function(index, filter) {
483 /* XXX How to manage checkbox ? */
486 var value = filter[2];
488 /* Determine index of key in the table columns */
489 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
491 /* Unknown key: no filtering */
492 if (typeof(col) == 'undefined')
495 col_value=unfold.get_value(aData[col]);
496 /* Test whether current filter is compatible with the column */
497 if (op == '=' || op == '==') {
498 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
500 }else if (op == '!=') {
501 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
504 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
507 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
509 } else if(op=='<=' || op=='≤') {
510 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
512 } else if(op=='>=' || op=='≥') {
513 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
516 // How to break out of a loop ?
517 alert("filter not supported");
525 _hazelnut_draw_callback: function()
528 * Handle clicks on checkboxes: reassociate checkbox click every time
529 * the table is redrawn
531 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
536 /* Remove pagination if we show only a few results */
537 var wrapper = this.table; //.parent().parent().parent();
538 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
539 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
540 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
542 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
543 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
545 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
548 if ( rowsToShow <= minRowsPerPage ) {
549 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
551 $('.hazelnut_length', wrapper).css('visibility', 'visible');
555 _check_click: function(e)
561 // XXX this.value = key of object to be added... what about multiple keys ?
562 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
563 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
567 _selectAll: function()
569 // requires jQuery id
570 var uuid=this.id.split("-");
571 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
572 // Function available in Hazelnut 1.9.x
573 // Filter : displayed data only
574 var filterData = oTable._('tr', {"filter":"applied"});
575 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
576 if(filterData.length<=100){
577 $.each(filterData, function(index, obj) {
578 var last=$(obj).last();
579 var key_value=unfold.get_value(last[0]);
580 if(typeof($(last[0]).attr('checked'))=="undefined"){
581 $.publish('selected', 'add/'+key_value);
589 $.plugin('Hazelnut', Hazelnut);