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)
156 // if (debug) messages.debug("checkbox_html, value="+value);
158 // Prefix id with plugin_uuid
160 result += " class='querytable-checkbox'";
161 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
162 result += " name='" + key + "'";
163 result += " type='checkbox'";
164 result += " autocomplete='off'";
165 if (value === undefined) {
166 messages.warning("querytable.checkbox_html - undefined value");
168 result += " value='" + value + "'";
170 result += "></input>";
175 new_record: function(record)
177 // this models a line in dataTables, each element in the line describes a cell
180 // go through table headers to get column names we want
181 // in order (we have temporarily hack some adjustments in names)
182 var cols = this.table.fnSettings().aoColumns;
183 var colnames = cols.map(function(x) {return x.sTitle})
184 var nb_col = cols.length;
185 /* if we've requested checkboxes, then forget about the checkbox column for now */
186 if (this.options.checkboxes) nb_col -= 1;
188 /* fill in stuff depending on the column name */
189 for (var j = 0; j < nb_col; j++) {
190 if (typeof colnames[j] == 'undefined') {
192 } else if (colnames[j] == 'hostname') {
193 if (record['type'] == 'resource,link')
194 //TODO: we need to add source/destination for links
197 line.push(record['hostname']);
199 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
200 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
202 if (record[colnames[j]])
203 line.push(record[colnames[j]]);
209 // catch up with the last column if checkboxes were requested
210 if (this.options.checkboxes) {
211 // Use a key instead of hostname (hard coded...)
212 line.push(this.checkbox_html(this.key, record[this.key]));
215 // adding an array in one call is *much* more efficient
216 // this.table.fnAddData(line);
217 this.buffered_lines.push(line);
220 clear_table: function()
222 this.table.fnClearTable();
225 redraw_table: function()
230 show_column: function(field)
232 var oSettings = this.table.fnSettings();
233 var cols = oSettings.aoColumns;
234 var index = this.getColIndex(field,cols);
236 this.table.fnSetColumnVis(index, true);
239 hide_column: function(field)
241 var oSettings = this.table.fnSettings();
242 var cols = oSettings.aoColumns;
243 var index = this.getColIndex(field,cols);
245 this.table.fnSetColumnVis(index, false);
248 set_checkbox: function(record, checked)
250 /* Default: checked = true */
251 if (checked === undefined) checked = true;
254 /* The function accepts both records and their key */
255 switch (manifold.get_type(record)) {
260 /* XXX Test the key before ? */
261 id = record[this.key];
264 throw "Not implemented";
269 if (id === undefined) {
270 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
273 var checkbox_id = this.flat_id(this.id('checkbox', id));
274 // function escape_id(myid) is defined in portal/static/js/common.functions.js
275 checkbox_id = escape_id(checkbox_id);
276 // using dataTables's $ to search also in nodes that are not currently displayed
277 var element = this.table.$(checkbox_id);
279 messages.debug("set_checkbox checked=" + checked
280 + " id=" + checkbox_id + " matches=" + element.length);
281 element.attr('checked', checked);
284 /*************************** QUERY HANDLER ****************************/
286 on_filter_added: function(filter)
288 this.filters.push(filter);
292 on_filter_removed: function(filter)
294 // Remove corresponding filters
295 this.filters = $.grep(this.filters, function(x) {
301 on_filter_clear: function()
307 on_field_added: function(field)
309 this.show_column(field);
312 on_field_removed: function(field)
314 this.hide_column(field);
317 on_field_clear: function()
319 alert('QueryTable::clear_fields() not implemented');
322 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
323 /*************************** ALL QUERY HANDLER ****************************/
325 on_all_filter_added: function(filter)
331 on_all_filter_removed: function(filter)
337 on_all_filter_clear: function()
343 on_all_field_added: function(field)
345 this.show_column(field);
348 on_all_field_removed: function(field)
350 this.hide_column(field);
353 on_all_field_clear: function()
355 alert('QueryTable::clear_fields() not implemented');
359 /*************************** RECORD HANDLER ***************************/
361 on_new_record: function(record)
363 if (this.received_all_query) {
364 // if the 'all' query has been dealt with already we may turn on the checkbox
365 this.set_checkbox(record, true);
367 // otherwise we need to remember that and do it later on
368 if (debug) messages.debug("Remembering record to check " + record[this.key]);
369 this.buffered_records_to_check.push(record);
373 on_clear_records: function()
377 // Could be the default in parent
378 on_query_in_progress: function()
383 on_query_done: function()
385 this.received_query = true;
386 // unspin once we have received both
387 if (this.received_all_query && this.received_query) this.unspin();
390 on_field_state_changed: function(data)
392 switch(data.request) {
393 case FIELD_REQUEST_ADD:
394 case FIELD_REQUEST_ADD_RESET:
395 this.set_checkbox(data.value, true);
397 case FIELD_REQUEST_REMOVE:
398 case FIELD_REQUEST_REMOVE_RESET:
399 this.set_checkbox(data.value, false);
406 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
408 on_all_field_state_changed: function(data)
410 switch(data.request) {
411 case FIELD_REQUEST_ADD:
412 case FIELD_REQUEST_ADD_RESET:
413 this.set_checkbox(data.value, true);
415 case FIELD_REQUEST_REMOVE:
416 case FIELD_REQUEST_REMOVE_RESET:
417 this.set_checkbox(data.value, false);
424 on_all_new_record: function(record)
426 this.new_record(record);
429 on_all_clear_records: function()
435 on_all_query_in_progress: function()
439 }, // on_all_query_in_progress
441 on_all_query_done: function()
443 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
444 this.table.fnAddData (this.buffered_lines);
445 this.buffered_lines=[];
448 // if we've already received the slice query, we have not been able to set
449 // checkboxes on the fly at that time (dom not yet created)
450 $.each(this.buffered_records_to_check, function(i, record) {
451 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
452 self.set_checkbox(record, true);
454 this.buffered_records_to_check = [];
456 this.received_all_query = true;
457 // unspin once we have received both
458 if (this.received_all_query && this.received_query) this.unspin();
460 }, // on_all_query_done
462 /************************** PRIVATE METHODS ***************************/
465 * @brief QueryTable filtering function
467 _querytable_filter: function(oSettings, aData, iDataIndex)
470 $.each (this.filters, function(index, filter) {
471 /* XXX How to manage checkbox ? */
474 var value = filter[2];
476 /* Determine index of key in the table columns */
477 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
479 /* Unknown key: no filtering */
480 if (typeof(col) == 'undefined')
483 col_value=unfold.get_value(aData[col]);
484 /* Test whether current filter is compatible with the column */
485 if (op == '=' || op == '==') {
486 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
488 }else if (op == '!=') {
489 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
492 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
495 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
497 } else if(op=='<=' || op=='≤') {
498 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
500 } else if(op=='>=' || op=='≥') {
501 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
504 // How to break out of a loop ?
505 alert("filter not supported");
513 _querytable_draw_callback: function()
516 * Handle clicks on checkboxes: reassociate checkbox click every time
517 * the table is redrawn
519 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
524 /* Remove pagination if we show only a few results */
525 var wrapper = this.table; //.parent().parent().parent();
526 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
527 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
528 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
530 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
531 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
533 $('.querytable_paginate', wrapper).css('visibility', 'visible');
536 if ( rowsToShow <= minRowsPerPage ) {
537 $('.querytable_length', wrapper).css('visibility', 'hidden');
539 $('.querytable_length', wrapper).css('visibility', 'visible');
543 _check_click: function(e)
549 // XXX this.value = key of object to be added... what about multiple keys ?
550 if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
551 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
552 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
556 _selectAll: function()
558 // requires jQuery id
559 var uuid=this.id.split("-");
560 var oTable=$("#querytable-"+uuid[1]).dataTable();
561 // Function available in QueryTable 1.9.x
562 // Filter : displayed data only
563 var filterData = oTable._('tr', {"filter":"applied"});
564 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
565 if(filterData.length<=100){
566 $.each(filterData, function(index, obj) {
567 var last=$(obj).last();
568 var key_value=unfold.get_value(last[0]);
569 if(typeof($(last[0]).attr('checked'))=="undefined"){
570 $.publish('selected', 'add/'+key_value);
578 $.plugin('QueryTable', QueryTable);
580 /* define the 'dom-checkbox' type for sorting in datatables
581 http://datatables.net/examples/plug-ins/dom_sort.html
582 using trial and error I found that the actual column number
583 was in fact given as a third argument, and not second
584 as the various online resources had it - go figure */
585 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
586 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
587 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';