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 this.el().on('show', this, this.on_show);
29 // Unbind all events using namespacing
31 // $(window).unbind('Hazelnut');
33 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
34 this.method = query.object;
36 var keys = manifold.metadata.get_key(this.method);
37 this.key = (keys && keys.length == 1) ? keys[0] : null;
39 /* Setup query and record handlers */
40 this.listen_query(options.query_uuid);
41 this.listen_query(options.query_all_uuid, 'all');
43 /* GUI setup and event binding */
44 this.initialize_table();
57 self.table.fnAdjustColumnSizing()
59 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
60 /* temp disabled... useful ? -- jordan
61 $(this).each(function(i,elt) {
62 if (jQuery(elt).hasClass('dataTables')) {
63 var myDiv=jQuery('#hazelnut-' + this.id).parent();
64 if(myDiv.height()==0) {
65 var oTable=$('#hazelnut-' + this.id).dataTable();
75 /* GUI MANIPULATION */
77 initialize_table: function()
79 /* Transforms the table into DataTable, and keep a pointer to it */
82 // Customize the position of Datatables elements (length,filter,button,...)
83 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
84 sDom: "<'row-fluid'<'span5'l><'span1'r><'span6'f>>t<'row-fluid'<'span5'i><'span7'p>>",
85 sPaginationType: 'bootstrap',
86 // Handle the null values & the error : Datatables warning Requested unknown parameter
87 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
88 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
89 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
90 // sScrollX: '100%', /* Horizontal scrolling */
91 bProcessing: true, /* Loading */
92 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
93 // XXX use $.proxy here !
95 // the intention here is that options.datatables_options as coming from the python object take precedence
96 // XXX DISABLED by jordan: was causing errors in datatables.js $.extend(actual_options, options.datatables_options );
97 this.table = this.el('table').dataTable(actual_options);
99 /* Setup the SelectAll button in the dataTable header */
100 /* xxx not sure this is still working */
101 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
102 oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
104 oSelectAll.css('font-size','11px');
105 oSelectAll.css('float','right');
106 oSelectAll.css('margin-right','15px');
107 oSelectAll.css('margin-bottom','5px');
108 oSelectAll.unbind('click');
109 oSelectAll.click(this._selectAll);
111 /* Add a filtering function to the current table
112 * Note: we use closure to get access to the 'options'
114 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
115 /* No filtering if the table does not match */
116 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
118 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
121 /* Processing hidden_columns */
122 $.each(this.options.hidden_columns, function(i, field) {
123 self.hide_column(field);
125 }, // initialize_table
128 * @brief Determine index of key in the table columns
132 getColIndex: function(key, cols) {
133 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
134 return (tabIndex.length > 0) ? tabIndex[0] : -1;
137 // UNUSED ? // this.update_plugin = function(e, rows) {
138 // UNUSED ? // // e.data is what we passed in second argument to subscribe
139 // UNUSED ? // // so here it is the jquery object attached to the plugin <div>
140 // UNUSED ? // var $plugindiv=e.data;
141 // UNUSED ? // if (debug)
142 // UNUSED ? // messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
143 // UNUSED ? // // clear the spinning wheel: look up an ancestor that has the need-spin class
144 // UNUSED ? // // do this before we might return
145 // UNUSED ? // $plugindiv.closest('.need-spin').spin(false);
147 // UNUSED ? // var options = this.options;
148 // UNUSED ? // var hazelnut = this;
150 // UNUSED ? // /* if we get no result, or an error, try to make that clear, and exit */
151 // UNUSED ? // if (rows.length==0) {
152 // UNUSED ? // if (debug)
153 // UNUSED ? // messages.debug("Empty result on hazelnut " + this.options.domid);
154 // UNUSED ? // var placeholder=$(this.table).find("td.dataTables_empty");
155 // UNUSED ? // console.log("placeholder "+placeholder);
156 // UNUSED ? // if (placeholder.length==1)
157 // UNUSED ? // placeholder.html(unfold.warning("Empty result"));
159 // UNUSED ? // this.table.html(unfold.warning("Empty result"));
160 // UNUSED ? // return;
161 // UNUSED ? // } else if (typeof(rows[0].error) != 'undefined') {
162 // UNUSED ? // // we now should have another means to report errors that this inline/embedded hack
163 // UNUSED ? // if (debug)
164 // UNUSED ? // messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
165 // UNUSED ? // this.table.html(unfold.error(rows[0].error));
166 // UNUSED ? // return;
170 // UNUSED ? // * fill the dataTables object
171 // UNUSED ? // * we cannot set html content directly here, need to use fnAddData
173 // UNUSED ? // var lines = new Array();
175 // UNUSED ? // this.current_resources = Array();
177 // UNUSED ? // $.each(rows, function(index, row) {
178 // UNUSED ? // // this models a line in dataTables, each element in the line describes a cell
179 // UNUSED ? // line = new Array();
181 // UNUSED ? // // go through table headers to get column names we want
182 // UNUSED ? // // in order (we have temporarily hack some adjustments in names)
183 // UNUSED ? // var cols = object.table.fnSettings().aoColumns;
184 // UNUSED ? // var colnames = cols.map(function(x) {return x.sTitle})
185 // UNUSED ? // var nb_col = cols.length;
186 // UNUSED ? // /* if we've requested checkboxes, then forget about the checkbox column for now */
187 // UNUSED ? // if (options.checkboxes) nb_col -= 1;
189 // UNUSED ? // /* fill in stuff depending on the column name */
190 // UNUSED ? // for (var j = 0; j < nb_col; j++) {
191 // UNUSED ? // if (typeof colnames[j] == 'undefined') {
192 // UNUSED ? // line.push('...');
193 // UNUSED ? // } else if (colnames[j] == 'hostname') {
194 // UNUSED ? // if (row['type'] == 'resource,link')
195 // UNUSED ? // //TODO: we need to add source/destination for links
196 // UNUSED ? // line.push('');
198 // UNUSED ? // line.push(row['hostname']);
199 // UNUSED ? // } else {
200 // UNUSED ? // if (row[colnames[j]])
201 // UNUSED ? // line.push(row[colnames[j]]);
203 // UNUSED ? // line.push('');
207 // UNUSED ? // /* catch up with the last column if checkboxes were requested */
208 // UNUSED ? // if (options.checkboxes) {
209 // UNUSED ? // var checked = '';
210 // UNUSED ? // // xxx problem is, we don't get this 'sliver' thing set apparently
211 // UNUSED ? // if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
212 // UNUSED ? // checked = 'checked ';
213 // UNUSED ? // hazelnut.current_resources.push(row[ELEMENT_KEY]);
215 // UNUSED ? // // Use a key instead of hostname (hard coded...)
216 // UNUSED ? // line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
219 // UNUSED ? // lines.push(line);
223 // UNUSED ? // this.table.fnClearTable();
224 // UNUSED ? // if (debug)
225 // UNUSED ? // messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
226 // UNUSED ? // this.table.fnAddData(lines);
228 // UNUSED ? // }, // update_plugin
230 checkbox: function (plugin_uuid, header, field) //, selected_str, disabled_str)
235 // Prefix id with plugin_uuid
237 result += " class='hazelnut-checkbox'";
238 result += " id='" + this.id('checkbox', this.id_from_key(this.key, unfold.get_value(header))) + "'";
239 //hazelnut-checkbox-" + plugin_uuid + "-" + unfold.get_value(header).replace(/\\/g, '') + "'";
240 result += " name='" + unfold.get_value(field) + "'";
241 result += " type='checkbox'";
242 //result += selected_str;
243 //result += disabled_str;
244 result += " autocomplete='off'";
245 result += " value='" + unfold.get_value(header) + "'";
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.options.plugin_uuid, record[ELEMENT_KEY], record['type']));
288 // XXX Is adding an array of lines more efficient ?
289 this.table.fnAddData(line);
293 clear_table: function()
295 this.table.fnClearTable();
298 redraw_table: function()
303 show_column: function(field)
305 var oSettings = this.table.fnSettings();
306 var cols = oSettings.aoColumns;
307 var index = this.getColIndex(field,cols);
309 this.table.fnSetColumnVis(index, true);
312 hide_column: function(field)
314 var oSettings = this.table.fnSettings();
315 var cols = oSettings.aoColumns;
316 var index = this.getColIndex(field,cols);
318 this.table.fnSetColumnVis(index, false);
321 set_checkbox: function(record, checked)
323 /* Default: checked = true */
324 if (typeof checked === 'undefined')
328 /* The function accepts both records and their key */
329 switch (manifold.get_type(record)) {
334 /* XXX Test the key before ? */
335 key_value = record[this.key];
338 throw "Not implemented";
343 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
344 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
346 var element = $(checkbox_id, this.table.fnGetNodes());
348 element.attr('checked', checked);
351 /*************************** QUERY HANDLER ****************************/
353 on_filter_added: function(filter)
359 on_filter_removed: function(filter)
365 on_filter_clear: function()
371 on_field_added: function(field)
373 this.show_column(field);
376 on_field_removed: function(field)
378 this.hide_column(field);
381 on_field_clear: function()
383 alert('Hazelnut::clear_fields() not implemented');
386 /*************************** RECORD HANDLER ***************************/
388 on_new_record: function(record)
390 /* NOTE in fact we are doing a join here */
391 if (this.received_all)
392 // update checkbox for record
393 this.set_checkbox(record, true);
395 // store for later update of checkboxes
396 this.in_set_buffer.push(record);
399 on_clear_records: function()
403 // Could be the default in parent
404 on_query_in_progress: function()
409 on_query_done: function()
411 if (this.received_all)
413 this.received_set = true;
416 on_field_state_changed: function(data)
418 switch(data.request) {
419 case FIELD_REQUEST_ADD:
420 case FIELD_REQUEST_ADD_RESET:
421 this.set_checkbox(data.value, true);
423 case FIELD_REQUEST_REMOVE:
424 case FIELD_REQUEST_REMOVE_RESET:
425 this.set_checkbox(data.value, false);
434 on_all_new_record: function(record)
436 this.new_record(record);
439 on_all_clear_records: function()
445 on_all_query_in_progress: function()
449 }, // on_all_query_in_progress
451 on_all_query_done: function()
454 if (this.received_set) {
455 /* XXX needed ? XXX We uncheck all checkboxes ... */
456 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
458 /* ... and check the ones specified in the resource list */
459 $.each(this.in_set_buffer, function(i, record) {
460 self.set_checkbox(record, true);
465 this.received_all = true;
467 }, // on_all_query_done
469 /************************** PRIVATE METHODS ***************************/
472 * @brief Hazelnut filtering function
474 _hazelnut_filter: function(oSettings, aData, iDataIndex)
476 var cur_query = this.current_query;
477 if (!cur_query) return true;
480 /* We have an array of filters : a filter is an array (key op val)
481 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
482 * can we exploit the data property somewhere ?
483 * field values (unless formatting) : aData
484 * formatting should leave original data available in a hidden field
486 * The current line should validate all filters
488 $.each (cur_query.filters, function(index, filter) {
489 /* XXX How to manage checkbox ? */
492 var value = filter[2];
494 /* Determine index of key in the table columns */
495 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
497 /* Unknown key: no filtering */
498 if (typeof(col) == 'undefined')
501 col_value=unfold.get_value(aData[col]);
502 /* Test whether current filter is compatible with the column */
503 if (op == '=' || op == '==') {
504 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
506 }else if (op == '!=') {
507 if ( 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")
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")
518 } else if(op=='>=' || op=='≥') {
519 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
522 // How to break out of a loop ?
523 alert("filter not supported");
531 _hazelnut_draw_callback: function()
534 * Handle clicks on checkboxes: reassociate checkbox click every time
535 * the table is redrawn
537 this.els('hazelnut-checkbox').unbind('click').click(this, this._check_click);
542 /* Remove pagination if we show only a few results */
543 var wrapper = this.table; //.parent().parent().parent();
544 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
545 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
546 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
548 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
549 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
551 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
554 if ( rowsToShow <= minRowsPerPage ) {
555 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
557 $('.hazelnut_length', wrapper).css('visibility', 'visible');
561 _check_click: function(e)
567 // XXX this.value = key of object to be added... what about multiple keys ?
568 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
569 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
573 _selectAll: function()
575 // requires jQuery id
576 var uuid=this.id.split("-");
577 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
578 // Function available in Hazelnut 1.9.x
579 // Filter : displayed data only
580 var filterData = oTable._('tr', {"filter":"applied"});
581 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
582 if(filterData.length<=100){
583 $.each(filterData, function(index, obj) {
584 var last=$(obj).last();
585 var key_value=unfold.get_value(last[0]);
586 if(typeof($(last[0]).attr('checked'))=="undefined"){
587 $.publish('selected', 'add/'+key_value);
595 $.plugin('Hazelnut', Hazelnut);