2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
16 var QueryTable = Plugin.extend({
18 init: function(options, element) {
19 this.classname="querytable";
20 this._super(options, element);
22 /* Member variables */
23 // in general we expect 2 queries here
24 // query_uuid refers to a single object (typically a slice)
25 // query_all_uuid refers to a list (typically resources or users)
26 // these can return in any order so we keep track of which has been received yet
27 this.received_all_query = false;
28 this.received_query = false;
30 // We need to remember the active filter for datatables filtering
31 this.filters = Array();
33 // an internal buffer for records that are 'in' and thus need to be checked
34 this.buffered_records_to_check = [];
35 // an internal buffer for keeping lines and display them in one call to fnAddData
36 this.buffered_lines = [];
39 // xx somehow non of these triggers at all for now
40 this.elmt().on('show', this, this.on_show);
41 this.elmt().on('shown.bs.tab', this, this.on_show);
42 this.elmt().on('resize', this, this.on_resize);
44 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
45 this.object = query.object;
47 //// we need 2 different keys
48 // * canonical_key is the primary key as derived from metadata (typically: urn)
49 // and is used to communicate about a given record with the other plugins
50 // * init_key is a key that both kinds of records
51 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
52 // in general query_all will return well populated records, but query
53 // returns records with only the fields displayed on startup
54 var keys = manifold.metadata.get_key(this.object);
55 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
57 this.init_key = this.options.init_key;
58 // have init_key default to canonical_key
59 this.init_key = this.init_key || this.canonical_key;
61 if ( ! this.init_key ) messages.warning ("QueryTable : cannot find init_key");
62 if ( ! this.canonical_key ) messages.warning ("QueryTable : cannot find canonical_key");
63 if (debug) messages.debug("querytable: canonical_key="+this.canonical_key+" init_key="+this.init_key);
65 /* Setup query and record handlers */
66 this.listen_query(options.query_uuid);
67 //this.listen_query(options.query_all_uuid, 'all');
69 /* GUI setup and event binding */
70 this.initialize_table();
75 on_show: function(e) {
76 if (debug) messages.debug("querytable.on_show");
78 self.table.fnAdjustColumnSizing();
81 on_resize: function(e) {
82 if (debug) messages.debug("querytable.on_resize");
84 self.table.fnAdjustColumnSizing();
89 /* GUI MANIPULATION */
91 initialize_table: function()
93 /* Transforms the table into DataTable, and keep a pointer to it */
95 var actual_options = {
96 // Customize the position of Datatables elements (length,filter,button,...)
97 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
98 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
99 sDom: "<'row'<'col-xs-5'f><'col-xs-1'r><'col-xs-6 columns_selector'>>t<'row'<'col-xs-5'l><'col-xs-7'p>>",
100 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
101 // hopefully this would come with dataTables v1.10 ?
102 // in any case, search for 'sPaginationType' all over the code for more comments
103 sPaginationType: 'bootstrap',
104 // Handle the null values & the error : Datatables warning Requested unknown parameter
105 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
106 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
107 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
108 // sScrollX: '100%', /* Horizontal scrolling */
109 bProcessing: true, /* Loading */
110 fnDrawCallback: function() { self._querytable_draw_callback.call(self); },
111 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
112 // This function is called on fnAddData to set the TR id. What about fnUpdate ?
114 // Get the key from the raw data array aData
115 var key = self.canonical_key;
117 // Get the index of the key in the columns
118 var cols = self.table.fnSettings().aoColumns;
119 var index = self.getColIndex(key, cols);
121 // The key is found in the table, set the TR id after the data
122 $(nRow).attr('id', self.id_from_key(key, aData[index]));
125 // That's the usual return value
128 // XXX use $.proxy here !
130 // the intention here is that options.datatables_options as coming from the python object take precedence
131 // xxx DISABLED by jordan: was causing errors in datatables.js
132 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
133 // check your datatables_options tag instead
134 // however, we have to accumulate in aoColumnDefs from here (above)
135 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
136 if ( 'aoColumnDefs' in this.options.datatables_options) {
137 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
138 delete this.options.datatables_options['aoColumnDefs'];
140 $.extend(actual_options, this.options.datatables_options );
141 this.table = this.elmt('table').dataTable(actual_options);
143 /* Setup the SelectAll button in the dataTable header */
144 /* xxx not sure this is still working */
145 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
146 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
148 oSelectAll.css('font-size','11px');
149 oSelectAll.css('float','right');
150 oSelectAll.css('margin-right','15px');
151 oSelectAll.css('margin-bottom','5px');
152 oSelectAll.unbind('click');
153 oSelectAll.click(this._selectAll);
155 /* Add a filtering function to the current table
156 * Note: we use closure to get access to the 'options'
158 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
159 /* No filtering if the table does not match */
160 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
162 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
165 /* Processing hidden_columns */
166 $.each(this.options.hidden_columns, function(i, field) {
167 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
168 self.hide_column(field);
170 $(".dataTables_filter").append("<div style='display:inline-block;height:27px;width:27px;padding-left:6px;padding-top:4px;'><span class='glyphicon glyphicon-search'></span></div>");
171 $(".dataTables_filter input").css("width","100%");
172 }, // initialize_table
175 * @brief Determine index of key in the table columns
179 getColIndex: function(key, cols) {
180 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
181 return (tabIndex.length > 0) ? tabIndex[0] : -1;
184 // create a checkbox <input> tag
185 // computes 'id' attribute from canonical_key
186 // computes 'init_id' from init_key for initialization phase
187 // no need to used convoluted ids with plugin-uuid or others, since
188 // we search using table.$ which looks only in this table
189 checkbox_html : function (record) {
191 // Prefix id with plugin_uuid
193 result += " class='querytable-checkbox'";
194 // compute id from canonical_key
195 var id = record[this.canonical_key]
196 // compute init_id form init_key
197 var init_id=record[this.init_key];
198 // set id - for retrieving from an id, or for posting events upon user's clicks
199 result += " id='"+record[this.canonical_key]+"'";
201 result += "init_id='" + init_id + "'";
203 result += " type='checkbox'";
204 result += " autocomplete='off'";
205 result += "></input>";
210 new_record: function(record)
212 // this models a line in dataTables, each element in the line describes a cell
215 // go through table headers to get column names we want
216 // in order (we have temporarily hack some adjustments in names)
217 var cols = this.table.fnSettings().aoColumns;
218 var colnames = cols.map(function(x) {return x.sTitle})
219 var nb_col = cols.length;
220 /* if we've requested checkboxes, then forget about the checkbox column for now */
221 //if (this.options.checkboxes) nb_col -= 1;
222 // catch up with the last column if checkboxes were requested
223 if (this.options.checkboxes) {
224 // Use a key instead of hostname (hard coded...)
225 line.push(this.checkbox_html(record));
228 /* fill in stuff depending on the column name */
229 for (var j = 1; j < nb_col - 1; j++) { // nb_col includes status
230 if (typeof colnames[j] == 'undefined') {
232 } else if (colnames[j] == 'hostname') {
233 if (record['type'] == 'resource,link')
234 //TODO: we need to add source/destination for links
237 line.push(record['hostname']);
239 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
247 /* XXX TODO: Remove this and have something consistant */
249 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
251 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
253 line.push(record[this.init_key]);
255 if (record[colnames[j]])
256 line.push(record[colnames[j]]);
261 line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
263 // adding an array in one call is *much* more efficient
264 // this.table.fnAddData(line);
268 clear_table: function()
270 this.table.fnClearTable();
273 redraw_table: function()
278 show_column: function(field)
280 var oSettings = this.table.fnSettings();
281 var cols = oSettings.aoColumns;
282 var index = this.getColIndex(field,cols);
284 this.table.fnSetColumnVis(index, true);
287 hide_column: function(field)
289 var oSettings = this.table.fnSettings();
290 var cols = oSettings.aoColumns;
291 var index = this.getColIndex(field,cols);
293 this.table.fnSetColumnVis(index, false);
296 // this is used at init-time, at which point only init_key can make sense
297 // (because the argument record, if it comes from query, might not have canonical_key set
298 set_checkbox_from_record: function (record, checked) {
299 if (checked === undefined) checked = true;
300 var init_id = record[this.init_key];
301 this.set_checkbox_from_record_key(init_id, checked);
304 set_checkbox_from_record_key: function (record_key, checked) {
305 if (checked === undefined) checked = true;
306 if (debug) messages.debug("querytable.set_checkbox_from_record, record_key="+record_key);
307 // using table.$ to search inside elements that are not visible
308 var element = this.table.$('[init_id="'+record_key+'"]');
309 element.attr('checked',checked);
312 // id relates to canonical_key
313 set_checkbox_from_data: function (id, checked) {
314 if (checked === undefined) checked = true;
315 if (debug) messages.debug("querytable.set_checkbox_from_data, id="+id);
316 // using table.$ to search inside elements that are not visible
317 var element = this.table.$("[id='"+id+"']");
318 element.attr('checked',checked);
324 * key_value: the key from which we deduce the id
325 * request: STATUS_OKAY, etc.
326 * content: some HTML content
328 change_status: function(key_value, warnings)
332 if ($.isEmptyObject(warnings)) {
333 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
336 case STATE_SET_IN_SUCCESS:
337 case STATE_SET_OUT_FAILURE:
338 case STATE_SET_IN_PENDING:
339 // Checkmark sign if no warning for an object in the set
343 // Nothing is the object is not in the set
348 msg = '<ul class="nav nav-pills">';
349 msg += '<li class="dropdown">'
350 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>⚠</b></a>';
351 msg += ' <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
352 $.each(warnings, function(i,warning) {
353 msg += '<li><a href="#">' + warning + '</a></li>';
360 $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
361 $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
365 set_bgcolor: function(key_value, class_name)
367 var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
368 if (class_name == BGCOLOR_RESET)
369 elt.removeClass('added removed');
371 elt.addClass((class_name == BGCOLOR_ADDED ? 'added' : 'removed'));
374 do_filter: function()
376 // Let's clear the table and only add lines that are visible
380 // XXX Here we have lost checkboxes
381 // set checkbox from record.
382 // only the current plugin known that we have an element in a set
385 var record_keys = [];
386 manifold.query_store.iter_visible_records(this.options.query_uuid, function (record_key, record) {
387 lines.push(self.new_record(record));
388 record_keys.push(record_key);
390 this.table.fnAddData(lines);
391 $.each(record_keys, function(i, record_key) {
392 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
393 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
395 // XXX The row and checkbox still does not exists !!!!
397 case STATE_SET_IN_SUCCESS:
398 case STATE_SET_OUT_FAILURE:
399 self.set_checkbox_from_record_key(record_key, true);
402 case STATE_SET_OUT_SUCCESS:
403 case STATE_SET_IN_FAILURE:
404 //self.set_checkbox_from_record_key(record_key, false);
406 case STATE_SET_IN_PENDING:
407 self.set_checkbox_from_record_key(record_key, true);
408 self.set_bgcolor(record_key, BGCOLOR_ADDED);
410 case STATE_SET_OUT_PENDING:
411 //self.set_checkbox_from_record_key(record_key, false);
412 self.set_bgcolor(record_key, BGCOLOR_REMOVED);
415 self.change_status(record_key, warnings); // XXX will retrieve status again
419 /*************************** QUERY HANDLER ****************************/
421 on_filter_added: function(filter)
426 this.filters.push(filter);
431 on_filter_removed: function(filter)
435 // Remove corresponding filters
436 this.filters = $.grep(this.filters, function(x) {
443 on_filter_clear: function()
448 on_field_added: function(field)
450 this.show_column(field);
453 on_field_removed: function(field)
455 this.hide_column(field);
458 on_field_clear: function()
460 alert('QueryTable::clear_fields() not implemented');
463 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
464 /*************************** ALL QUERY HANDLER ****************************/
466 on_all_filter_added: function(filter)
471 on_all_filter_removed: function(filter)
476 on_all_filter_clear: function()
481 on_all_field_added: function(field)
483 this.show_column(field);
486 on_all_field_removed: function(field)
488 this.hide_column(field);
491 on_all_field_clear: function()
493 alert('QueryTable::clear_fields() not implemented');
497 /*************************** RECORD HANDLER ***************************/
499 on_new_record: function(record)
501 if (this.received_all_query) {
502 // if the 'all' query has been dealt with already we may turn on the checkbox
503 this.set_checkbox_from_record(record, true);
505 this.buffered_records_to_check.push(record);
509 on_clear_records: function()
513 // Could be the default in parent
514 on_query_in_progress: function()
519 on_query_done: function()
523 this.received_query = true;
524 // unspin once we have received both
525 if (this.received_all_query && this.received_query) this.unspin();
529 on_field_state_changed: function(data)
531 var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.status);
532 switch(data.status) {
536 case STATE_SET_IN_SUCCESS:
537 case STATE_SET_OUT_FAILURE:
538 this.set_checkbox_from_data(data.value, true);
539 this.set_bgcolor(data.value, BGCOLOR_RESET);
542 case STATE_SET_OUT_SUCCESS:
543 case STATE_SET_IN_FAILURE:
544 this.set_checkbox_from_data(data.value, false);
545 this.set_bgcolor(data.value, BGCOLOR_RESET);
547 case STATE_SET_IN_PENDING:
548 this.set_checkbox_from_data(data.value, true);
549 this.set_bgcolor(data.value, BGCOLOR_ADDED);
551 case STATE_SET_OUT_PENDING:
552 this.set_checkbox_from_data(data.value, false);
553 this.set_bgcolor(data.value, BGCOLOR_REMOVED);
559 this.change_status(data.value, state);
564 /************************** PRIVATE METHODS ***************************/
567 * @brief QueryTable filtering function
569 _querytable_filter: function(oSettings, aData, iDataIndex)
572 $.each (this.filters, function(index, filter) {
573 /* XXX How to manage checkbox ? */
576 var value = filter[2];
578 /* Determine index of key in the table columns */
579 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
581 /* Unknown key: no filtering */
582 if (typeof(col) == 'undefined')
585 col_value=unfold.get_value(aData[col]);
586 /* Test whether current filter is compatible with the column */
587 if (op == '=' || op == '==') {
588 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
590 }else if (op == 'included') {
591 $.each(value, function(i,x) {
599 }else if (op == '!=') {
600 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
603 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
606 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
608 } else if(op=='<=' || op=='≤') {
609 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
611 } else if(op=='>=' || op=='≥') {
612 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
615 // How to break out of a loop ?
616 alert("filter not supported");
624 _querytable_draw_callback: function()
627 * Handle clicks on checkboxes: reassociate checkbox click every time
628 * the table is redrawn
630 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
635 /* Remove pagination if we show only a few results */
636 var wrapper = this.table; //.parent().parent().parent();
637 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
638 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
639 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
641 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
642 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
644 $('.querytable_paginate', wrapper).css('visibility', 'visible');
647 if ( rowsToShow <= minRowsPerPage ) {
648 $('.querytable_length', wrapper).css('visibility', 'hidden');
650 $('.querytable_length', wrapper).css('visibility', 'visible');
654 _check_click: function(e)
661 // this.id = key of object to be added... what about multiple keys ?
662 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
663 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
664 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
668 _selectAll: function()
670 // requires jQuery id
671 var uuid=this.id.split("-");
672 var oTable=$("#querytable-"+uuid[1]).dataTable();
673 // Function available in QueryTable 1.9.x
674 // Filter : displayed data only
675 var filterData = oTable._('tr', {"filter":"applied"});
676 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
677 if(filterData.length<=100){
678 $.each(filterData, function(index, obj) {
679 var last=$(obj).last();
680 var key_value=unfold.get_value(last[0]);
681 if(typeof($(last[0]).attr('checked'))=="undefined"){
682 $.publish('selected', 'add/'+key_value);
690 $.plugin('QueryTable', QueryTable);
692 /* define the 'dom-checkbox' type for sorting in datatables
693 http://datatables.net/examples/plug-ins/dom_sort.html
694 using trial and error I found that the actual column number
695 was in fact given as a third argument, and not second
696 as the various online resources had it - go figure */
697 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
698 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
699 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';