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.object = query.object;
44 // xxx beware that this.key needs to contain a key that all records will have
45 // in general query_all will return well populated records, but query
46 // returns records with only the fields displayed on startup.
47 this.key = (this.options.id_key);
48 if (typeof(this.key)=='undefined' || (this.key).startsWith("unknown")) {
49 // if not specified by caller, decide from metadata
50 var keys = manifold.metadata.get_key(this.object);
51 this.key = (keys && keys.length == 1) ? keys[0] : null;
53 if (! this.key) messages.warning("querytable.init could not kind valid key");
54 messages.debug("querytable: key="+this.key);
56 /* Setup query and record handlers */
57 this.listen_query(options.query_uuid);
58 this.listen_query(options.query_all_uuid, 'all');
60 /* GUI setup and event binding */
61 this.initialize_table();
70 self.table.fnAdjustColumnSizing()
72 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
73 /* temp disabled... useful ? -- jordan
74 $(this).each(function(i,elt) {
75 if (jQuery(elt).hasClass('dataTables')) {
76 var myDiv=jQuery('#querytable-' + this.id).parent();
77 if(myDiv.height()==0) {
78 var oTable=$('#querytable-' + this.id).dataTable();
88 /* GUI MANIPULATION */
90 initialize_table: function()
92 /* Transforms the table into DataTable, and keep a pointer to it */
94 var actual_options = {
95 // Customize the position of Datatables elements (length,filter,button,...)
96 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
97 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
98 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
99 // hopefully this would come with dataTables v1.10 ?
100 // in any case, search for 'sPaginationType' all over the code for more comments
101 sPaginationType: 'bootstrap',
102 // Handle the null values & the error : Datatables warning Requested unknown parameter
103 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
104 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
105 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
106 // sScrollX: '100%', /* Horizontal scrolling */
107 bProcessing: true, /* Loading */
108 fnDrawCallback: function() { self._querytable_draw_callback.call(self); }
109 // XXX use $.proxy here !
111 // the intention here is that options.datatables_options as coming from the python object take precedence
112 // xxx DISABLED by jordan: was causing errors in datatables.js
113 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
114 // check your datatables_options tag instead
115 // however, we have to accumulate in aoColumnDefs from here (above)
116 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
117 if ( 'aoColumnDefs' in this.options.datatables_options) {
118 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
119 delete this.options.datatables_options['aoColumnDefs'];
121 $.extend(actual_options, this.options.datatables_options );
122 this.table = this.elmt('table').dataTable(actual_options);
124 /* Setup the SelectAll button in the dataTable header */
125 /* xxx not sure this is still working */
126 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
127 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
129 oSelectAll.css('font-size','11px');
130 oSelectAll.css('float','right');
131 oSelectAll.css('margin-right','15px');
132 oSelectAll.css('margin-bottom','5px');
133 oSelectAll.unbind('click');
134 oSelectAll.click(this._selectAll);
136 /* Add a filtering function to the current table
137 * Note: we use closure to get access to the 'options'
139 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
140 /* No filtering if the table does not match */
141 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
143 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
146 /* Processing hidden_columns */
147 $.each(this.options.hidden_columns, function(i, field) {
148 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
149 self.hide_column(field);
151 }, // initialize_table
154 * @brief Determine index of key in the table columns
158 getColIndex: function(key, cols) {
159 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
160 return (tabIndex.length > 0) ? tabIndex[0] : -1;
163 checkbox_html : function (key, value)
165 // if (debug) messages.debug("checkbox_html, value="+value);
167 // Prefix id with plugin_uuid
169 result += " class='querytable-checkbox'";
170 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
171 result += " name='" + key + "'";
172 result += " type='checkbox'";
173 result += " autocomplete='off'";
174 if (value === undefined) {
175 messages.warning("querytable.checkbox_html - undefined value");
177 result += " value='" + value + "'";
179 result += "></input>";
184 new_record: function(record)
186 // this models a line in dataTables, each element in the line describes a cell
189 // go through table headers to get column names we want
190 // in order (we have temporarily hack some adjustments in names)
191 var cols = this.table.fnSettings().aoColumns;
192 var colnames = cols.map(function(x) {return x.sTitle})
193 var nb_col = cols.length;
194 /* if we've requested checkboxes, then forget about the checkbox column for now */
195 if (this.options.checkboxes) nb_col -= 1;
197 /* fill in stuff depending on the column name */
198 for (var j = 0; j < nb_col; j++) {
199 if (typeof colnames[j] == 'undefined') {
201 } else if (colnames[j] == 'hostname') {
202 if (record['type'] == 'resource,link')
203 //TODO: we need to add source/destination for links
206 line.push(record['hostname']);
208 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
209 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
211 if (record[colnames[j]])
212 line.push(record[colnames[j]]);
218 // catch up with the last column if checkboxes were requested
219 if (this.options.checkboxes) {
220 // Use a key instead of hostname (hard coded...)
221 line.push(this.checkbox_html(this.key, record[this.key]));
224 // adding an array in one call is *much* more efficient
225 // this.table.fnAddData(line);
226 this.buffered_lines.push(line);
229 clear_table: function()
231 this.table.fnClearTable();
234 redraw_table: function()
239 show_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, true);
248 hide_column: function(field)
250 var oSettings = this.table.fnSettings();
251 var cols = oSettings.aoColumns;
252 var index = this.getColIndex(field,cols);
254 this.table.fnSetColumnVis(index, false);
257 set_checkbox: function(record, checked)
259 /* Default: checked = true */
260 if (checked === undefined) checked = true;
263 /* The function accepts both records and their key */
264 switch (manifold.get_type(record)) {
269 /* XXX Test the key before ? */
270 id = record[this.key];
273 throw "Not implemented";
278 if (id === undefined) {
279 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
282 // PB TO CHECK THE RIGHT CHECKBOXES IS HERE... flat_id using \ in the key
283 // need to use escape_id when creating the id of the checkboxes
284 var checkbox_id = this.flat_id(this.id('checkbox', id));
285 // function escape_id(myid) is defined in portal/static/js/common.functions.js
286 checkbox_id = escape_id(checkbox_id);
287 // As we are using [id="x"] syntax, we need to remove the # in the checkbox_id
288 checkbox_id = checkbox_id.replace("#","");
289 // using dataTables's $ to search also in nodes that are not currently displayed
290 var element = this.table.$('[id="' + checkbox_id + '"]');
292 messages.debug("set_checkbox checked=" + checked
293 + " id=" + checkbox_id + " matches=" + element.length);
294 element.attr('checked', checked);
297 /*************************** QUERY HANDLER ****************************/
299 on_filter_added: function(filter)
301 this.filters.push(filter);
305 on_filter_removed: function(filter)
307 // Remove corresponding filters
308 this.filters = $.grep(this.filters, function(x) {
314 on_filter_clear: function()
320 on_field_added: function(field)
322 this.show_column(field);
325 on_field_removed: function(field)
327 this.hide_column(field);
330 on_field_clear: function()
332 alert('QueryTable::clear_fields() not implemented');
335 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
336 /*************************** ALL QUERY HANDLER ****************************/
338 on_all_filter_added: function(filter)
344 on_all_filter_removed: function(filter)
350 on_all_filter_clear: function()
356 on_all_field_added: function(field)
358 this.show_column(field);
361 on_all_field_removed: function(field)
363 this.hide_column(field);
366 on_all_field_clear: function()
368 alert('QueryTable::clear_fields() not implemented');
372 /*************************** RECORD HANDLER ***************************/
374 on_new_record: function(record)
376 if (this.received_all_query) {
377 // if the 'all' query has been dealt with already we may turn on the checkbox
378 this.set_checkbox(record, true);
380 // otherwise we need to remember that and do it later on
381 if (debug) messages.debug("Remembering record to check " + record[this.key]);
382 this.buffered_records_to_check.push(record);
386 on_clear_records: function()
390 // Could be the default in parent
391 on_query_in_progress: function()
396 on_query_done: function()
398 this.received_query = true;
399 // unspin once we have received both
400 if (this.received_all_query && this.received_query) this.unspin();
403 on_field_state_changed: function(data)
405 switch(data.request) {
406 case FIELD_REQUEST_ADD:
407 case FIELD_REQUEST_ADD_RESET:
408 this.set_checkbox(data.value, true);
410 case FIELD_REQUEST_REMOVE:
411 case FIELD_REQUEST_REMOVE_RESET:
412 this.set_checkbox(data.value, false);
419 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
421 on_all_field_state_changed: function(data)
423 switch(data.request) {
424 case FIELD_REQUEST_ADD:
425 case FIELD_REQUEST_ADD_RESET:
426 this.set_checkbox(data.value, true);
428 case FIELD_REQUEST_REMOVE:
429 case FIELD_REQUEST_REMOVE_RESET:
430 this.set_checkbox(data.value, false);
437 on_all_new_record: function(record)
439 this.new_record(record);
442 on_all_clear_records: function()
448 on_all_query_in_progress: function()
452 }, // on_all_query_in_progress
454 on_all_query_done: function()
456 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
457 this.table.fnAddData (this.buffered_lines);
458 this.buffered_lines=[];
461 // if we've already received the slice query, we have not been able to set
462 // checkboxes on the fly at that time (dom not yet created)
463 $.each(this.buffered_records_to_check, function(i, record) {
464 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
465 self.set_checkbox(record, true);
467 this.buffered_records_to_check = [];
469 this.received_all_query = true;
470 // unspin once we have received both
471 if (this.received_all_query && this.received_query) this.unspin();
473 }, // on_all_query_done
475 /************************** PRIVATE METHODS ***************************/
478 * @brief QueryTable filtering function
480 _querytable_filter: function(oSettings, aData, iDataIndex)
483 $.each (this.filters, function(index, filter) {
484 /* XXX How to manage checkbox ? */
487 var value = filter[2];
489 /* Determine index of key in the table columns */
490 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
492 /* Unknown key: no filtering */
493 if (typeof(col) == 'undefined')
496 col_value=unfold.get_value(aData[col]);
497 /* Test whether current filter is compatible with the column */
498 if (op == '=' || op == '==') {
499 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
501 }else if (op == '!=') {
502 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
505 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
508 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
510 } else if(op=='<=' || op=='≤') {
511 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
513 } else if(op=='>=' || op=='≥') {
514 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
517 // How to break out of a loop ?
518 alert("filter not supported");
526 _querytable_draw_callback: function()
529 * Handle clicks on checkboxes: reassociate checkbox click every time
530 * the table is redrawn
532 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
537 /* Remove pagination if we show only a few results */
538 var wrapper = this.table; //.parent().parent().parent();
539 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
540 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
541 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
543 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
544 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
546 $('.querytable_paginate', wrapper).css('visibility', 'visible');
549 if ( rowsToShow <= minRowsPerPage ) {
550 $('.querytable_length', wrapper).css('visibility', 'hidden');
552 $('.querytable_length', wrapper).css('visibility', 'visible');
556 _check_click: function(e)
562 // XXX this.value = key of object to be added... what about multiple keys ?
563 if (debug) messages.debug("querytable click handler checked=" + this.checked + " "+this.key+"=" + this.value);
564 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
565 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
569 _selectAll: function()
571 // requires jQuery id
572 var uuid=this.id.split("-");
573 var oTable=$("#querytable-"+uuid[1]).dataTable();
574 // Function available in QueryTable 1.9.x
575 // Filter : displayed data only
576 var filterData = oTable._('tr', {"filter":"applied"});
577 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
578 if(filterData.length<=100){
579 $.each(filterData, function(index, obj) {
580 var last=$(obj).last();
581 var key_value=unfold.get_value(last[0]);
582 if(typeof($(last[0]).attr('checked'))=="undefined"){
583 $.publish('selected', 'add/'+key_value);
591 $.plugin('QueryTable', QueryTable);
593 /* define the 'dom-checkbox' type for sorting in datatables
594 http://datatables.net/examples/plug-ins/dom_sort.html
595 using trial and error I found that the actual column number
596 was in fact given as a third argument, and not second
597 as the various online resources had it - go figure */
598 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
599 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
600 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';