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.elmt().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 /* an internal buffer for keeping lines and display them in one call to fnAddData */
43 this.buffered_lines = [];
45 /* GUI setup and event binding */
46 this.initialize_table();
59 self.table.fnAdjustColumnSizing()
61 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
62 /* temp disabled... useful ? -- jordan
63 $(this).each(function(i,elt) {
64 if (jQuery(elt).hasClass('dataTables')) {
65 var myDiv=jQuery('#hazelnut-' + this.id).parent();
66 if(myDiv.height()==0) {
67 var oTable=$('#hazelnut-' + this.id).dataTable();
77 /* GUI MANIPULATION */
79 initialize_table: function()
81 /* Transforms the table into DataTable, and keep a pointer to it */
84 // Customize the position of Datatables elements (length,filter,button,...)
85 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
86 sDom: "<'row'<'col-md-5'l><'col-md-1'r><'col-md-6'f>>t<'row'<'col-md-5'i><'col-md-7'p>>",
87 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
88 // hopefully this would come with dataTables v1.10 ?
89 // in any case, search for 'sPaginationType' all over the code for more comments
90 sPaginationType: 'full_numbers',
91 // Handle the null values & the error : Datatables warning Requested unknown parameter
92 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
93 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
94 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
95 // sScrollX: '100%', /* Horizontal scrolling */
96 bProcessing: true, /* Loading */
97 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
98 // XXX use $.proxy here !
100 // the intention here is that options.datatables_options as coming from the python object take precedence
101 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
102 this.table = this.elmt('table').dataTable(actual_options);
104 /* Setup the SelectAll button in the dataTable header */
105 /* xxx not sure this is still working */
106 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
107 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
109 oSelectAll.css('font-size','11px');
110 oSelectAll.css('float','right');
111 oSelectAll.css('margin-right','15px');
112 oSelectAll.css('margin-bottom','5px');
113 oSelectAll.unbind('click');
114 oSelectAll.click(this._selectAll);
116 /* Add a filtering function to the current table
117 * Note: we use closure to get access to the 'options'
119 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
120 /* No filtering if the table does not match */
121 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
123 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
126 /* Processing hidden_columns */
127 $.each(this.options.hidden_columns, function(i, field) {
128 self.hide_column(field);
130 }, // initialize_table
133 * @brief Determine index of key in the table columns
137 getColIndex: function(key, cols) {
138 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
139 return (tabIndex.length > 0) ? tabIndex[0] : -1;
142 // UNUSED ? // this.update_plugin = function(e, rows) {
143 // UNUSED ? // // e.data is what we passed in second argument to subscribe
144 // UNUSED ? // // so here it is the jquery object attached to the plugin <div>
145 // UNUSED ? // var $plugindiv=e.data;
146 // UNUSED ? // if (debug)
147 // UNUSED ? // messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
148 // UNUSED ? // // clear the spinning wheel: look up an ancestor that has the need-spin class
149 // UNUSED ? // // do this before we might return
150 // UNUSED ? // $plugindiv.closest('.need-spin').spin(false);
152 // UNUSED ? // var options = this.options;
153 // UNUSED ? // var hazelnut = this;
155 // UNUSED ? // /* if we get no result, or an error, try to make that clear, and exit */
156 // UNUSED ? // if (rows.length==0) {
157 // UNUSED ? // if (debug)
158 // UNUSED ? // messages.debug("Empty result on hazelnut " + this.options.domid);
159 // UNUSED ? // var placeholder=$(this.table).find("td.dataTables_empty");
160 // UNUSED ? // console.log("placeholder "+placeholder);
161 // UNUSED ? // if (placeholder.length==1)
162 // UNUSED ? // placeholder.html(unfold.warning("Empty result"));
164 // UNUSED ? // this.table.html(unfold.warning("Empty result"));
165 // UNUSED ? // return;
166 // UNUSED ? // } else if (typeof(rows[0].error) != 'undefined') {
167 // UNUSED ? // // we now should have another means to report errors that this inline/embedded hack
168 // UNUSED ? // if (debug)
169 // UNUSED ? // messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
170 // UNUSED ? // this.table.html(unfold.error(rows[0].error));
171 // UNUSED ? // return;
175 // UNUSED ? // * fill the dataTables object
176 // UNUSED ? // * we cannot set html content directly here, need to use fnAddData
178 // UNUSED ? // var lines = new Array();
180 // UNUSED ? // this.current_resources = Array();
182 // UNUSED ? // $.each(rows, function(index, row) {
183 // UNUSED ? // // this models a line in dataTables, each element in the line describes a cell
184 // UNUSED ? // line = new Array();
186 // UNUSED ? // // go through table headers to get column names we want
187 // UNUSED ? // // in order (we have temporarily hack some adjustments in names)
188 // UNUSED ? // var cols = object.table.fnSettings().aoColumns;
189 // UNUSED ? // var colnames = cols.map(function(x) {return x.sTitle})
190 // UNUSED ? // var nb_col = cols.length;
191 // UNUSED ? // /* if we've requested checkboxes, then forget about the checkbox column for now */
192 // UNUSED ? // if (options.checkboxes) nb_col -= 1;
194 // UNUSED ? // /* fill in stuff depending on the column name */
195 // UNUSED ? // for (var j = 0; j < nb_col; j++) {
196 // UNUSED ? // if (typeof colnames[j] == 'undefined') {
197 // UNUSED ? // line.push('...');
198 // UNUSED ? // } else if (colnames[j] == 'hostname') {
199 // UNUSED ? // if (row['type'] == 'resource,link')
200 // UNUSED ? // //TODO: we need to add source/destination for links
201 // UNUSED ? // line.push('');
203 // UNUSED ? // line.push(row['hostname']);
204 // UNUSED ? // } else {
205 // UNUSED ? // if (row[colnames[j]])
206 // UNUSED ? // line.push(row[colnames[j]]);
208 // UNUSED ? // line.push('');
212 // UNUSED ? // /* catch up with the last column if checkboxes were requested */
213 // UNUSED ? // if (options.checkboxes) {
214 // UNUSED ? // var checked = '';
215 // UNUSED ? // // xxx problem is, we don't get this 'sliver' thing set apparently
216 // UNUSED ? // if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
217 // UNUSED ? // checked = 'checked ';
218 // UNUSED ? // hazelnut.current_resources.push(row[ELEMENT_KEY]);
220 // UNUSED ? // // Use a key instead of hostname (hard coded...)
221 // UNUSED ? // line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
224 // UNUSED ? // lines.push(line);
228 // UNUSED ? // this.table.fnClearTable();
229 // UNUSED ? // if (debug)
230 // UNUSED ? // messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
231 // UNUSED ? // this.table.fnAddData(lines);
233 // UNUSED ? // }, // update_plugin
235 checkbox: function (key, value)
238 // Prefix id with plugin_uuid
240 result += " class='hazelnut-checkbox'";
241 result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
242 result += " name='" + key + "'";
243 result += " type='checkbox'";
244 result += " autocomplete='off'";
245 result += " value='" + value + "'";
246 result += "></input>";
251 new_record: function(record)
253 // this models a line in dataTables, each element in the line describes a cell
256 // go through table headers to get column names we want
257 // in order (we have temporarily hack some adjustments in names)
258 var cols = this.table.fnSettings().aoColumns;
259 var colnames = cols.map(function(x) {return x.sTitle})
260 var nb_col = cols.length;
261 /* if we've requested checkboxes, then forget about the checkbox column for now */
262 if (this.options.checkboxes) nb_col -= 1;
264 /* fill in stuff depending on the column name */
265 for (var j = 0; j < nb_col; j++) {
266 if (typeof colnames[j] == 'undefined') {
268 } else if (colnames[j] == 'hostname') {
269 if (record['type'] == 'resource,link')
270 //TODO: we need to add source/destination for links
273 line.push(record['hostname']);
275 if (record[colnames[j]])
276 line.push(record[colnames[j]]);
282 /* catch up with the last column if checkboxes were requested */
283 if (this.options.checkboxes)
284 // Use a key instead of hostname (hard coded...)
285 // XXX remove the empty checked attribute
286 line.push(this.checkbox(this.key, record[this.key]));
288 // XXX Is adding an array of lines more efficient ?
289 // this.table.fnAddData(line);
290 this.buffered_lines.push(line)
294 clear_table: function()
296 this.table.fnClearTable();
299 redraw_table: function()
304 show_column: function(field)
306 var oSettings = this.table.fnSettings();
307 var cols = oSettings.aoColumns;
308 var index = this.getColIndex(field,cols);
310 this.table.fnSetColumnVis(index, true);
313 hide_column: function(field)
315 var oSettings = this.table.fnSettings();
316 var cols = oSettings.aoColumns;
317 var index = this.getColIndex(field,cols);
319 this.table.fnSetColumnVis(index, false);
322 set_checkbox: function(record, checked)
324 /* Default: checked = true */
325 if (typeof checked === 'undefined')
329 /* The function accepts both records and their key */
330 switch (manifold.get_type(record)) {
335 /* XXX Test the key before ? */
336 key_value = record[this.key];
339 throw "Not implemented";
344 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
345 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
347 var element = $(checkbox_id, this.table.fnGetNodes());
349 element.attr('checked', checked);
352 /*************************** QUERY HANDLER ****************************/
354 on_filter_added: function(filter)
360 on_filter_removed: function(filter)
366 on_filter_clear: function()
372 on_field_added: function(field)
374 this.show_column(field);
377 on_field_removed: function(field)
379 this.hide_column(field);
382 on_field_clear: function()
384 alert('Hazelnut::clear_fields() not implemented');
387 /*************************** RECORD HANDLER ***************************/
389 on_new_record: function(record)
391 /* NOTE in fact we are doing a join here */
392 if (this.received_all)
393 // update checkbox for record
394 this.set_checkbox(record, true);
396 // store for later update of checkboxes
397 this.in_set_buffer.push(record);
400 on_clear_records: function()
404 // Could be the default in parent
405 on_query_in_progress: function()
410 on_query_done: function()
412 if (this.received_all)
414 this.received_set = true;
417 on_field_state_changed: function(data)
419 switch(data.request) {
420 case FIELD_REQUEST_ADD:
421 case FIELD_REQUEST_ADD_RESET:
422 this.set_checkbox(data.value, true);
424 case FIELD_REQUEST_REMOVE:
425 case FIELD_REQUEST_REMOVE_RESET:
426 this.set_checkbox(data.value, false);
435 on_all_new_record: function(record)
437 this.new_record(record);
440 on_all_clear_records: function()
446 on_all_query_in_progress: function()
450 }, // on_all_query_in_progress
452 on_all_query_done: function()
455 if (this.received_set) {
456 /* XXX needed ? XXX We uncheck all checkboxes ... */
457 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
459 /* ... and check the ones specified in the resource list */
460 $.each(this.in_set_buffer, function(i, record) {
461 self.set_checkbox(record, true);
466 this.table.fnAddData (this.buffered_lines);
467 this.buffered_lines=[];
468 this.received_all = true;
470 }, // on_all_query_done
472 /************************** PRIVATE METHODS ***************************/
475 * @brief Hazelnut filtering function
477 _hazelnut_filter: function(oSettings, aData, iDataIndex)
479 var cur_query = this.current_query;
480 if (!cur_query) return true;
483 /* We have an array of filters : a filter is an array (key op val)
484 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
485 * can we exploit the data property somewhere ?
486 * field values (unless formatting) : aData
487 * formatting should leave original data available in a hidden field
489 * The current line should validate all filters
491 $.each (cur_query.filters, function(index, filter) {
492 /* XXX How to manage checkbox ? */
495 var value = filter[2];
497 /* Determine index of key in the table columns */
498 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
500 /* Unknown key: no filtering */
501 if (typeof(col) == 'undefined')
504 col_value=unfold.get_value(aData[col]);
505 /* Test whether current filter is compatible with the column */
506 if (op == '=' || op == '==') {
507 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
509 }else if (op == '!=') {
510 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
513 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
516 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
518 } else if(op=='<=' || op=='≤') {
519 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
521 } else if(op=='>=' || op=='≥') {
522 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
525 // How to break out of a loop ?
526 alert("filter not supported");
534 _hazelnut_draw_callback: function()
537 * Handle clicks on checkboxes: reassociate checkbox click every time
538 * the table is redrawn
540 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
545 /* Remove pagination if we show only a few results */
546 var wrapper = this.table; //.parent().parent().parent();
547 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
548 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
549 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
551 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
552 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
554 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
557 if ( rowsToShow <= minRowsPerPage ) {
558 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
560 $('.hazelnut_length', wrapper).css('visibility', 'visible');
564 _check_click: function(e)
570 // XXX this.value = key of object to be added... what about multiple keys ?
571 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
572 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
576 _selectAll: function()
578 // requires jQuery id
579 var uuid=this.id.split("-");
580 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
581 // Function available in Hazelnut 1.9.x
582 // Filter : displayed data only
583 var filterData = oTable._('tr', {"filter":"applied"});
584 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
585 if(filterData.length<=100){
586 $.each(filterData, function(index, obj) {
587 var last=$(obj).last();
588 var key_value=unfold.get_value(last[0]);
589 if(typeof($(last[0]).attr('checked'))=="undefined"){
590 $.publish('selected', 'add/'+key_value);
598 $.plugin('Hazelnut', Hazelnut);