2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
12 var QueryTable = Plugin.extend({
14 init: function(options, element)
16 this._super(options, element);
18 /* Member variables */
19 // in general we expect 2 queries here
20 // query_uuid refers to a single object (typically a slice)
21 // query_all_uuid refers to a list (typically resources or users)
22 // these can return in any order so we keep track of which has been received yet
23 this.received_all_query = false;
24 this.received_query = false;
26 // We need to remember the active filter for datatables filtering
27 this.filters = Array();
29 // an internal buffer for records that are 'in' and thus need to be checked
30 this.buffered_records_to_check = [];
31 // an internal buffer for keeping lines and display them in one call to fnAddData
32 this.buffered_lines = [];
35 // this.$element.on('show.Datatables', this.on_show);
36 this.elmt().on('show', this, this.on_show);
37 // Unbind all events using namespacing
39 // $(window).unbind('QueryTable');
41 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
42 this.method = query.object;
44 var keys = manifold.metadata.get_key(this.method);
45 this.key = (keys && keys.length == 1) ? keys[0] : null;
47 /* Setup query and record handlers */
48 this.listen_query(options.query_uuid);
49 this.listen_query(options.query_all_uuid, 'all');
51 /* GUI setup and event binding */
52 this.initialize_table();
61 self.table.fnAdjustColumnSizing()
63 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
64 /* temp disabled... useful ? -- jordan
65 $(this).each(function(i,elt) {
66 if (jQuery(elt).hasClass('dataTables')) {
67 var myDiv=jQuery('#querytable-' + this.id).parent();
68 if(myDiv.height()==0) {
69 var oTable=$('#querytable-' + this.id).dataTable();
79 /* GUI MANIPULATION */
81 initialize_table: function()
83 /* Transforms the table into DataTable, and keep a pointer to it */
85 var actual_options = {
86 // Customize the position of Datatables elements (length,filter,button,...)
87 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
88 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
89 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
90 // hopefully this would come with dataTables v1.10 ?
91 // in any case, search for 'sPaginationType' all over the code for more comments
92 sPaginationType: 'bootstrap',
93 // Handle the null values & the error : Datatables warning Requested unknown parameter
94 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
95 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
96 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
97 // sScrollX: '100%', /* Horizontal scrolling */
98 bProcessing: true, /* Loading */
99 fnDrawCallback: function() { self._querytable_draw_callback.call(self); }
100 // XXX use $.proxy here !
102 // the intention here is that options.datatables_options as coming from the python object take precedence
103 // xxx DISABLED by jordan: was causing errors in datatables.js
104 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
105 // check your datatables_options tag instead
106 // however, we have to accumulate in aoColumnDefs from here (above)
107 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
108 if ( 'aoColumnDefs' in this.options.datatables_options) {
109 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
110 delete this.options.datatables_options['aoColumnDefs'];
112 $.extend(actual_options, this.options.datatables_options );
113 this.table = this.elmt('table').dataTable(actual_options);
115 /* Setup the SelectAll button in the dataTable header */
116 /* xxx not sure this is still working */
117 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
118 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
120 oSelectAll.css('font-size','11px');
121 oSelectAll.css('float','right');
122 oSelectAll.css('margin-right','15px');
123 oSelectAll.css('margin-bottom','5px');
124 oSelectAll.unbind('click');
125 oSelectAll.click(this._selectAll);
127 /* Add a filtering function to the current table
128 * Note: we use closure to get access to the 'options'
130 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
131 /* No filtering if the table does not match */
132 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
134 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
137 /* Processing hidden_columns */
138 $.each(this.options.hidden_columns, function(i, field) {
139 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
140 self.hide_column(field);
142 }, // initialize_table
145 * @brief Determine index of key in the table columns
149 getColIndex: function(key, cols) {
150 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
151 return (tabIndex.length > 0) ? tabIndex[0] : -1;
154 checkbox_html : function (key, value)
157 // Prefix id with plugin_uuid
159 result += " class='querytable-checkbox'";
160 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
161 result += " name='" + key + "'";
162 result += " type='checkbox'";
163 result += " autocomplete='off'";
164 result += " value='" + value + "'";
165 result += "></input>";
170 new_record: function(record)
172 // this models a line in dataTables, each element in the line describes a cell
175 // go through table headers to get column names we want
176 // in order (we have temporarily hack some adjustments in names)
177 var cols = this.table.fnSettings().aoColumns;
178 var colnames = cols.map(function(x) {return x.sTitle})
179 var nb_col = cols.length;
180 /* if we've requested checkboxes, then forget about the checkbox column for now */
181 if (this.options.checkboxes) nb_col -= 1;
183 /* fill in stuff depending on the column name */
184 for (var j = 0; j < nb_col; j++) {
185 if (typeof colnames[j] == 'undefined') {
187 } else if (colnames[j] == 'hostname') {
188 if (record['type'] == 'resource,link')
189 //TODO: we need to add source/destination for links
192 line.push(record['hostname']);
194 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
195 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
197 if (record[colnames[j]])
198 line.push(record[colnames[j]]);
204 // catch up with the last column if checkboxes were requested
205 if (this.options.checkboxes) {
206 // Use a key instead of hostname (hard coded...)
207 line.push(this.checkbox_html(this.key, record[this.key]));
210 // adding an array in one call is *much* more efficient
211 // this.table.fnAddData(line);
212 this.buffered_lines.push(line);
215 clear_table: function()
217 this.table.fnClearTable();
220 redraw_table: function()
225 show_column: function(field)
227 var oSettings = this.table.fnSettings();
228 var cols = oSettings.aoColumns;
229 var index = this.getColIndex(field,cols);
231 this.table.fnSetColumnVis(index, true);
234 hide_column: function(field)
236 var oSettings = this.table.fnSettings();
237 var cols = oSettings.aoColumns;
238 var index = this.getColIndex(field,cols);
240 this.table.fnSetColumnVis(index, false);
243 set_checkbox: function(record, checked)
245 /* Default: checked = true */
246 if (checked === undefined) checked = true;
249 /* The function accepts both records and their key */
250 switch (manifold.get_type(record)) {
255 /* XXX Test the key before ? */
256 key_value = record[this.key];
259 throw "Not implemented";
264 var checkbox_id = this.flat_id(this.id('checkbox', key_value));
265 // function escape_id(myid) is defined in portal/static/js/common.functions.js
266 checkbox_id = escape_id(checkbox_id);
267 // using dataTables's $ to search also in nodes that are not currently displayed
268 var element = this.table.$(checkbox_id);
269 if (debug) messages.debug("set_checkbox checked=" + checked + " id=" + checkbox_id + " matches=" + element.length);
270 element.attr('checked', checked);
273 /*************************** QUERY HANDLER ****************************/
275 on_filter_added: function(filter)
277 this.filters.push(filter);
281 on_filter_removed: function(filter)
283 // Remove corresponding filters
284 this.filters = $.grep(this.filters, function(x) {
290 on_filter_clear: function()
296 on_field_added: function(field)
298 this.show_column(field);
301 on_field_removed: function(field)
303 this.hide_column(field);
306 on_field_clear: function()
308 alert('QueryTable::clear_fields() not implemented');
311 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
312 /*************************** ALL QUERY HANDLER ****************************/
314 on_all_filter_added: function(filter)
320 on_all_filter_removed: function(filter)
326 on_all_filter_clear: function()
332 on_all_field_added: function(field)
334 this.show_column(field);
337 on_all_field_removed: function(field)
339 this.hide_column(field);
342 on_all_field_clear: function()
344 alert('QueryTable::clear_fields() not implemented');
348 /*************************** RECORD HANDLER ***************************/
350 on_new_record: function(record)
352 if (this.received_all_query) {
353 // if the 'all' query has been dealt with already we may turn on the checkbox
354 if (debug) messages.debug("turning on checkbox for record "+record[this.key]);
355 this.set_checkbox(record, true);
357 // otherwise we need to remember that and do it later on
358 if (debug) messages.debug("Remembering record to check " + record[this.key]);
359 this.buffered_records_to_check.push(record);
363 on_clear_records: function()
367 // Could be the default in parent
368 on_query_in_progress: function()
373 on_query_done: function()
375 this.received_query = true;
376 // unspin once we have received both
377 if (this.received_all_query && this.received_query) this.unspin();
380 on_field_state_changed: function(data)
382 switch(data.request) {
383 case FIELD_REQUEST_ADD:
384 case FIELD_REQUEST_ADD_RESET:
385 this.set_checkbox(data.value, true);
387 case FIELD_REQUEST_REMOVE:
388 case FIELD_REQUEST_REMOVE_RESET:
389 this.set_checkbox(data.value, false);
396 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
398 on_all_field_state_changed: function(data)
400 switch(data.request) {
401 case FIELD_REQUEST_ADD:
402 case FIELD_REQUEST_ADD_RESET:
403 this.set_checkbox(data.value, true);
405 case FIELD_REQUEST_REMOVE:
406 case FIELD_REQUEST_REMOVE_RESET:
407 this.set_checkbox(data.value, false);
414 on_all_new_record: function(record)
416 this.new_record(record);
419 on_all_clear_records: function()
425 on_all_query_in_progress: function()
429 }, // on_all_query_in_progress
431 on_all_query_done: function()
433 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
434 this.table.fnAddData (this.buffered_lines);
435 this.buffered_lines=[];
438 // if we've already received the slice query, we have not been able to set
439 // checkboxes on the fly at that time (dom not yet created)
440 $.each(this.buffered_records_to_check, function(i, record) {
441 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
442 self.set_checkbox(record, true);
444 this.buffered_records_to_check = [];
446 this.received_all_query = true;
447 // unspin once we have received both
448 if (this.received_all_query && this.received_query) this.unspin();
450 }, // on_all_query_done
452 /************************** PRIVATE METHODS ***************************/
455 * @brief QueryTable filtering function
457 _querytable_filter: function(oSettings, aData, iDataIndex)
460 $.each (this.filters, function(index, filter) {
461 /* XXX How to manage checkbox ? */
464 var value = filter[2];
466 /* Determine index of key in the table columns */
467 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
469 /* Unknown key: no filtering */
470 if (typeof(col) == 'undefined')
473 col_value=unfold.get_value(aData[col]);
474 /* Test whether current filter is compatible with the column */
475 if (op == '=' || op == '==') {
476 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
478 }else if (op == '!=') {
479 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
482 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
485 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
487 } else if(op=='<=' || op=='≤') {
488 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
490 } else if(op=='>=' || op=='≥') {
491 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
494 // How to break out of a loop ?
495 alert("filter not supported");
503 _querytable_draw_callback: function()
506 * Handle clicks on checkboxes: reassociate checkbox click every time
507 * the table is redrawn
509 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
514 /* Remove pagination if we show only a few results */
515 var wrapper = this.table; //.parent().parent().parent();
516 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
517 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
518 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
520 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
521 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
523 $('.querytable_paginate', wrapper).css('visibility', 'visible');
526 if ( rowsToShow <= minRowsPerPage ) {
527 $('.querytable_length', wrapper).css('visibility', 'hidden');
529 $('.querytable_length', wrapper).css('visibility', 'visible');
533 _check_click: function(e)
539 // XXX this.value = key of object to be added... what about multiple keys ?
540 if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
541 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
542 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
546 _selectAll: function()
548 // requires jQuery id
549 var uuid=this.id.split("-");
550 var oTable=$("#querytable-"+uuid[1]).dataTable();
551 // Function available in QueryTable 1.9.x
552 // Filter : displayed data only
553 var filterData = oTable._('tr', {"filter":"applied"});
554 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
555 if(filterData.length<=100){
556 $.each(filterData, function(index, obj) {
557 var last=$(obj).last();
558 var key_value=unfold.get_value(last[0]);
559 if(typeof($(last[0]).attr('checked'))=="undefined"){
560 $.publish('selected', 'add/'+key_value);
568 $.plugin('QueryTable', QueryTable);
570 /* define the 'dom-checkbox' type for sorting in datatables
571 http://datatables.net/examples/plug-ins/dom_sort.html
572 using trial and error I found that the actual column number
573 was in fact given as a third argument, and not second
574 as the various online resources had it - go figure */
575 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
576 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
577 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';