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 checkbox: function (key, value)
145 // Prefix id with plugin_uuid
147 result += " class='hazelnut-checkbox'";
148 result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
149 result += " name='" + key + "'";
150 result += " type='checkbox'";
151 result += " autocomplete='off'";
152 result += " value='" + value + "'";
153 result += "></input>";
158 new_record: function(record)
160 // this models a line in dataTables, each element in the line describes a cell
163 // go through table headers to get column names we want
164 // in order (we have temporarily hack some adjustments in names)
165 var cols = this.table.fnSettings().aoColumns;
166 var colnames = cols.map(function(x) {return x.sTitle})
167 var nb_col = cols.length;
168 /* if we've requested checkboxes, then forget about the checkbox column for now */
169 if (this.options.checkboxes) nb_col -= 1;
171 /* fill in stuff depending on the column name */
172 for (var j = 0; j < nb_col; j++) {
173 if (typeof colnames[j] == 'undefined') {
175 } else if (colnames[j] == 'hostname') {
176 if (record['type'] == 'resource,link')
177 //TODO: we need to add source/destination for links
180 line.push(record['hostname']);
182 if (record[colnames[j]])
183 line.push(record[colnames[j]]);
189 /* catch up with the last column if checkboxes were requested */
190 if (this.options.checkboxes)
191 // Use a key instead of hostname (hard coded...)
192 // XXX remove the empty checked attribute
193 line.push(this.checkbox(this.key, record[this.key]));
195 // adding an array in one call is *much* more efficient
196 // this.table.fnAddData(line);
197 this.buffered_lines.push(line)
201 clear_table: function()
203 this.table.fnClearTable();
206 redraw_table: function()
211 show_column: function(field)
213 var oSettings = this.table.fnSettings();
214 var cols = oSettings.aoColumns;
215 var index = this.getColIndex(field,cols);
217 this.table.fnSetColumnVis(index, true);
220 hide_column: function(field)
222 var oSettings = this.table.fnSettings();
223 var cols = oSettings.aoColumns;
224 var index = this.getColIndex(field,cols);
226 this.table.fnSetColumnVis(index, false);
229 set_checkbox: function(record, checked)
231 /* Default: checked = true */
232 if (typeof checked === 'undefined')
236 /* The function accepts both records and their key */
237 switch (manifold.get_type(record)) {
242 /* XXX Test the key before ? */
243 key_value = record[this.key];
246 throw "Not implemented";
251 var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
252 checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
254 var element = $(checkbox_id, this.table.fnGetNodes());
256 element.attr('checked', checked);
259 /*************************** QUERY HANDLER ****************************/
261 on_filter_added: function(filter)
267 on_filter_removed: function(filter)
273 on_filter_clear: function()
279 on_field_added: function(field)
281 this.show_column(field);
284 on_field_removed: function(field)
286 this.hide_column(field);
289 on_field_clear: function()
291 alert('Hazelnut::clear_fields() not implemented');
294 /*************************** RECORD HANDLER ***************************/
296 on_new_record: function(record)
298 /* NOTE in fact we are doing a join here */
299 if (this.received_all)
300 // update checkbox for record
301 this.set_checkbox(record, true);
303 // store for later update of checkboxes
304 this.in_set_buffer.push(record);
307 on_clear_records: function()
311 // Could be the default in parent
312 on_query_in_progress: function()
317 on_query_done: function()
319 if (this.received_all)
321 this.received_set = true;
324 on_field_state_changed: function(data)
326 switch(data.request) {
327 case FIELD_REQUEST_ADD:
328 case FIELD_REQUEST_ADD_RESET:
329 this.set_checkbox(data.value, true);
331 case FIELD_REQUEST_REMOVE:
332 case FIELD_REQUEST_REMOVE_RESET:
333 this.set_checkbox(data.value, false);
342 on_all_new_record: function(record)
344 this.new_record(record);
347 on_all_clear_records: function()
353 on_all_query_in_progress: function()
357 }, // on_all_query_in_progress
359 on_all_query_done: function()
362 if (this.received_set) {
363 /* XXX needed ? XXX We uncheck all checkboxes ... */
364 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
366 /* ... and check the ones specified in the resource list */
367 $.each(this.in_set_buffer, function(i, record) {
368 self.set_checkbox(record, true);
373 this.table.fnAddData (this.buffered_lines);
374 this.buffered_lines=[];
375 this.received_all = true;
377 }, // on_all_query_done
379 /************************** PRIVATE METHODS ***************************/
382 * @brief Hazelnut filtering function
384 _hazelnut_filter: function(oSettings, aData, iDataIndex)
386 var cur_query = this.current_query;
387 if (!cur_query) return true;
390 /* We have an array of filters : a filter is an array (key op val)
391 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
392 * can we exploit the data property somewhere ?
393 * field values (unless formatting) : aData
394 * formatting should leave original data available in a hidden field
396 * The current line should validate all filters
398 $.each (cur_query.filters, function(index, filter) {
399 /* XXX How to manage checkbox ? */
402 var value = filter[2];
404 /* Determine index of key in the table columns */
405 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
407 /* Unknown key: no filtering */
408 if (typeof(col) == 'undefined')
411 col_value=unfold.get_value(aData[col]);
412 /* Test whether current filter is compatible with the column */
413 if (op == '=' || op == '==') {
414 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
416 }else if (op == '!=') {
417 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
420 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
423 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
425 } else if(op=='<=' || op=='≤') {
426 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
428 } else if(op=='>=' || op=='≥') {
429 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
432 // How to break out of a loop ?
433 alert("filter not supported");
441 _hazelnut_draw_callback: function()
444 * Handle clicks on checkboxes: reassociate checkbox click every time
445 * the table is redrawn
447 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
452 /* Remove pagination if we show only a few results */
453 var wrapper = this.table; //.parent().parent().parent();
454 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
455 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
456 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
458 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
459 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
461 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
464 if ( rowsToShow <= minRowsPerPage ) {
465 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
467 $('.hazelnut_length', wrapper).css('visibility', 'visible');
471 _check_click: function(e)
477 // XXX this.value = key of object to be added... what about multiple keys ?
478 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
479 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
483 _selectAll: function()
485 // requires jQuery id
486 var uuid=this.id.split("-");
487 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
488 // Function available in Hazelnut 1.9.x
489 // Filter : displayed data only
490 var filterData = oTable._('tr', {"filter":"applied"});
491 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
492 if(filterData.length<=100){
493 $.each(filterData, function(index, obj) {
494 var last=$(obj).last();
495 var key_value=unfold.get_value(last[0]);
496 if(typeof($(last[0]).attr('checked'))=="undefined"){
497 $.publish('selected', 'add/'+key_value);
505 $.plugin('Hazelnut', Hazelnut);