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 /* 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'<'col-md-5'l><'col-md-1'r><'col-md-6'f>>t<'row'<'col-md-5'i><'col-md-7'p>>",
84 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
85 // hopefully this would come with dataTables v1.10 ?
86 // in any case, search for 'sPaginationType' all over the code for more comments
87 sPaginationType: 'full_numbers',
88 // Handle the null values & the error : Datatables warning Requested unknown parameter
89 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
90 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
91 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
92 // sScrollX: '100%', /* Horizontal scrolling */
93 bProcessing: true, /* Loading */
94 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
95 // XXX use $.proxy here !
97 // the intention here is that options.datatables_options as coming from the python object take precedence
98 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
99 this.table = this.elmt('table').dataTable(actual_options);
101 /* Setup the SelectAll button in the dataTable header */
102 /* xxx not sure this is still working */
103 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
104 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
106 oSelectAll.css('font-size','11px');
107 oSelectAll.css('float','right');
108 oSelectAll.css('margin-right','15px');
109 oSelectAll.css('margin-bottom','5px');
110 oSelectAll.unbind('click');
111 oSelectAll.click(this._selectAll);
113 /* Add a filtering function to the current table
114 * Note: we use closure to get access to the 'options'
116 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
117 /* No filtering if the table does not match */
118 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
120 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
123 /* Processing hidden_columns */
124 $.each(this.options.hidden_columns, function(i, field) {
125 self.hide_column(field);
127 }, // initialize_table
130 * @brief Determine index of key in the table columns
134 getColIndex: function(key, cols) {
135 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
136 return (tabIndex.length > 0) ? tabIndex[0] : -1;
139 // UNUSED ? // this.update_plugin = function(e, rows) {
140 // UNUSED ? // // e.data is what we passed in second argument to subscribe
141 // UNUSED ? // // so here it is the jquery object attached to the plugin <div>
142 // UNUSED ? // var $plugindiv=e.data;
143 // UNUSED ? // if (debug)
144 // UNUSED ? // messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
145 // UNUSED ? // // clear the spinning wheel: look up an ancestor that has the need-spin class
146 // UNUSED ? // // do this before we might return
147 // UNUSED ? // $plugindiv.closest('.need-spin').spin(false);
149 // UNUSED ? // var options = this.options;
150 // UNUSED ? // var hazelnut = this;
152 // UNUSED ? // /* if we get no result, or an error, try to make that clear, and exit */
153 // UNUSED ? // if (rows.length==0) {
154 // UNUSED ? // if (debug)
155 // UNUSED ? // messages.debug("Empty result on hazelnut " + this.options.domid);
156 // UNUSED ? // var placeholder=$(this.table).find("td.dataTables_empty");
157 // UNUSED ? // console.log("placeholder "+placeholder);
158 // UNUSED ? // if (placeholder.length==1)
159 // UNUSED ? // placeholder.html(unfold.warning("Empty result"));
161 // UNUSED ? // this.table.html(unfold.warning("Empty result"));
162 // UNUSED ? // return;
163 // UNUSED ? // } else if (typeof(rows[0].error) != 'undefined') {
164 // UNUSED ? // // we now should have another means to report errors that this inline/embedded hack
165 // UNUSED ? // if (debug)
166 // UNUSED ? // messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
167 // UNUSED ? // this.table.html(unfold.error(rows[0].error));
168 // UNUSED ? // return;
172 // UNUSED ? // * fill the dataTables object
173 // UNUSED ? // * we cannot set html content directly here, need to use fnAddData
175 // UNUSED ? // var lines = new Array();
177 // UNUSED ? // this.current_resources = Array();
179 // UNUSED ? // $.each(rows, function(index, row) {
180 // UNUSED ? // // this models a line in dataTables, each element in the line describes a cell
181 // UNUSED ? // line = new Array();
183 // UNUSED ? // // go through table headers to get column names we want
184 // UNUSED ? // // in order (we have temporarily hack some adjustments in names)
185 // UNUSED ? // var cols = object.table.fnSettings().aoColumns;
186 // UNUSED ? // var colnames = cols.map(function(x) {return x.sTitle})
187 // UNUSED ? // var nb_col = cols.length;
188 // UNUSED ? // /* if we've requested checkboxes, then forget about the checkbox column for now */
189 // UNUSED ? // if (options.checkboxes) nb_col -= 1;
191 // UNUSED ? // /* fill in stuff depending on the column name */
192 // UNUSED ? // for (var j = 0; j < nb_col; j++) {
193 // UNUSED ? // if (typeof colnames[j] == 'undefined') {
194 // UNUSED ? // line.push('...');
195 // UNUSED ? // } else if (colnames[j] == 'hostname') {
196 // UNUSED ? // if (row['type'] == 'resource,link')
197 // UNUSED ? // //TODO: we need to add source/destination for links
198 // UNUSED ? // line.push('');
200 // UNUSED ? // line.push(row['hostname']);
201 // UNUSED ? // } else {
202 // UNUSED ? // if (row[colnames[j]])
203 // UNUSED ? // line.push(row[colnames[j]]);
205 // UNUSED ? // line.push('');
209 // UNUSED ? // /* catch up with the last column if checkboxes were requested */
210 // UNUSED ? // if (options.checkboxes) {
211 // UNUSED ? // var checked = '';
212 // UNUSED ? // // xxx problem is, we don't get this 'sliver' thing set apparently
213 // UNUSED ? // if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
214 // UNUSED ? // checked = 'checked ';
215 // UNUSED ? // hazelnut.current_resources.push(row[ELEMENT_KEY]);
217 // UNUSED ? // // Use a key instead of hostname (hard coded...)
218 // UNUSED ? // line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
221 // UNUSED ? // lines.push(line);
225 // UNUSED ? // this.table.fnClearTable();
226 // UNUSED ? // if (debug)
227 // UNUSED ? // messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
228 // UNUSED ? // this.table.fnAddData(lines);
230 // UNUSED ? // }, // update_plugin
232 checkbox: function (key, value)
235 // Prefix id with plugin_uuid
237 result += " class='hazelnut-checkbox'";
238 result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
239 result += " name='" + key + "'";
240 result += " type='checkbox'";
241 result += " autocomplete='off'";
242 result += " value='" + value + "'";
243 result += "></input>";
248 new_record: function(record)
250 // this models a line in dataTables, each element in the line describes a cell
253 // go through table headers to get column names we want
254 // in order (we have temporarily hack some adjustments in names)
255 var cols = this.table.fnSettings().aoColumns;
256 var colnames = cols.map(function(x) {return x.sTitle})
257 var nb_col = cols.length;
258 /* if we've requested checkboxes, then forget about the checkbox column for now */
259 if (this.options.checkboxes) nb_col -= 1;
261 /* fill in stuff depending on the column name */
262 for (var j = 0; j < nb_col; j++) {
263 if (typeof colnames[j] == 'undefined') {
265 } else if (colnames[j] == 'hostname') {
266 if (record['type'] == 'resource,link')
267 //TODO: we need to add source/destination for links
270 line.push(record['hostname']);
272 if (record[colnames[j]])
273 line.push(record[colnames[j]]);
279 /* catch up with the last column if checkboxes were requested */
280 if (this.options.checkboxes)
281 // Use a key instead of hostname (hard coded...)
282 // XXX remove the empty checked attribute
283 line.push(this.checkbox(this.key, record[this.key]));
285 // XXX Is adding an array of lines more efficient ?
286 this.table.fnAddData(line);
290 clear_table: function()
292 this.table.fnClearTable();
295 redraw_table: function()
300 show_column: function(field)
302 var oSettings = this.table.fnSettings();
303 var cols = oSettings.aoColumns;
304 var index = this.getColIndex(field,cols);
306 this.table.fnSetColumnVis(index, true);
309 hide_column: function(field)
311 var oSettings = this.table.fnSettings();
312 var cols = oSettings.aoColumns;
313 var index = this.getColIndex(field,cols);
315 this.table.fnSetColumnVis(index, false);
318 set_checkbox: function(record, checked)
320 /* Default: checked = true */
321 if (typeof checked === 'undefined')
325 /* The function accepts both records and their key */
326 switch (manifold.get_type(record)) {
331 /* XXX Test the key before ? */
332 key_value = record[this.key];
335 throw "Not implemented";
340 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
341 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
343 var element = $(checkbox_id, this.table.fnGetNodes());
345 element.attr('checked', checked);
348 /*************************** QUERY HANDLER ****************************/
350 on_filter_added: function(filter)
356 on_filter_removed: function(filter)
362 on_filter_clear: function()
368 on_field_added: function(field)
370 this.show_column(field);
373 on_field_removed: function(field)
375 this.hide_column(field);
378 on_field_clear: function()
380 alert('Hazelnut::clear_fields() not implemented');
383 /*************************** RECORD HANDLER ***************************/
385 on_new_record: function(record)
387 /* NOTE in fact we are doing a join here */
388 if (this.received_all)
389 // update checkbox for record
390 this.set_checkbox(record, true);
392 // store for later update of checkboxes
393 this.in_set_buffer.push(record);
396 on_clear_records: function()
400 // Could be the default in parent
401 on_query_in_progress: function()
406 on_query_done: function()
408 if (this.received_all)
410 this.received_set = true;
413 on_field_state_changed: function(data)
415 switch(data.request) {
416 case FIELD_REQUEST_ADD:
417 case FIELD_REQUEST_ADD_RESET:
418 this.set_checkbox(data.value, true);
420 case FIELD_REQUEST_REMOVE:
421 case FIELD_REQUEST_REMOVE_RESET:
422 this.set_checkbox(data.value, false);
431 on_all_new_record: function(record)
433 this.new_record(record);
436 on_all_clear_records: function()
442 on_all_query_in_progress: function()
446 }, // on_all_query_in_progress
448 on_all_query_done: function()
451 if (this.received_set) {
452 /* XXX needed ? XXX We uncheck all checkboxes ... */
453 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
455 /* ... and check the ones specified in the resource list */
456 $.each(this.in_set_buffer, function(i, record) {
457 self.set_checkbox(record, true);
462 this.received_all = true;
464 }, // on_all_query_done
466 /************************** PRIVATE METHODS ***************************/
469 * @brief Hazelnut filtering function
471 _hazelnut_filter: function(oSettings, aData, iDataIndex)
473 var cur_query = this.current_query;
474 if (!cur_query) return true;
477 /* We have an array of filters : a filter is an array (key op val)
478 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
479 * can we exploit the data property somewhere ?
480 * field values (unless formatting) : aData
481 * formatting should leave original data available in a hidden field
483 * The current line should validate all filters
485 $.each (cur_query.filters, function(index, filter) {
486 /* XXX How to manage checkbox ? */
489 var value = filter[2];
491 /* Determine index of key in the table columns */
492 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
494 /* Unknown key: no filtering */
495 if (typeof(col) == 'undefined')
498 col_value=unfold.get_value(aData[col]);
499 /* Test whether current filter is compatible with the column */
500 if (op == '=' || op == '==') {
501 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
503 }else if (op == '!=') {
504 if ( 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")
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")
515 } else if(op=='>=' || op=='≥') {
516 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
519 // How to break out of a loop ?
520 alert("filter not supported");
528 _hazelnut_draw_callback: function()
531 * Handle clicks on checkboxes: reassociate checkbox click every time
532 * the table is redrawn
534 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
539 /* Remove pagination if we show only a few results */
540 var wrapper = this.table; //.parent().parent().parent();
541 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
542 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
543 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
545 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
546 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
548 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
551 if ( rowsToShow <= minRowsPerPage ) {
552 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
554 $('.hazelnut_length', wrapper).css('visibility', 'visible');
558 _check_click: function(e)
564 // XXX this.value = key of object to be added... what about multiple keys ?
565 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
566 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
570 _selectAll: function()
572 // requires jQuery id
573 var uuid=this.id.split("-");
574 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
575 // Function available in Hazelnut 1.9.x
576 // Filter : displayed data only
577 var filterData = oTable._('tr', {"filter":"applied"});
578 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
579 if(filterData.length<=100){
580 $.each(filterData, function(index, obj) {
581 var last=$(obj).last();
582 var key_value=unfold.get_value(last[0]);
583 if(typeof($(last[0]).attr('checked'))=="undefined"){
584 $.publish('selected', 'add/'+key_value);
592 $.plugin('Hazelnut', Hazelnut);