2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
7 QUERYTABLE_BGCOLOR_RESET = 0;
8 QUERYTABLE_BGCOLOR_ADDED = 1;
9 QUERYTABLE_BGCOLOR_REMOVED = 2;
16 var QueryTable = Plugin.extend({
18 init: function(options, element) {
19 this.classname="querytable";
20 this._super(options, element);
22 /* Member variables */
23 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
24 this.object = query.object; // XXX
27 this.elmt().on('show', this, this.on_show);
28 this.elmt().on('shown.bs.tab', this, this.on_show);
29 this.elmt().on('resize', this, this.on_resize);
31 //// we need 2 different keys
32 // * canonical_key is the primary key as derived from metadata (typically: urn)
33 // and is used to communicate about a given record with the other plugins
34 // * init_key is a key that both kinds of records
35 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
36 // in general query_all will return well populated records, but query
37 // returns records with only the fields displayed on startup
38 var keys = manifold.metadata.get_key(this.object);
39 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
41 this.init_key = this.options.init_key;
42 // have init_key default to canonical_key
43 this.init_key = this.init_key || this.canonical_key;
46 if ( ! this.init_key )
47 messages.warning ("QueryTable : cannot find init_key");
48 if ( ! this.canonical_key )
49 messages.warning ("QueryTable : cannot find canonical_key");
51 messages.debug("querytable: canonical_key="+this.canonical_key+" init_key="+this.init_key);
53 /* Setup query and record handlers */
54 this.listen_query(options.query_uuid);
56 /* GUI setup and event binding */
57 this.initialize_table();
62 on_show: function(e) {
63 if (debug) messages.debug("querytable.on_show");
65 self.table.fnAdjustColumnSizing();
68 on_resize: function(e) {
69 if (debug) messages.debug("querytable.on_resize");
71 self.table.fnAdjustColumnSizing();
76 /* GUI MANIPULATION */
78 initialize_table: function()
80 /* Transforms the table into DataTable, and keep a pointer to it */
82 var actual_options = {
83 // Customize the position of Datatables elements (length,filter,button,...)
84 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
85 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
86 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>>",
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: 'bootstrap',
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._querytable_draw_callback.call(self); },
98 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
99 // This function is called on fnAddData to set the TR id. What about fnUpdate ?
101 // Get the key from the raw data array aData
102 var key = self.canonical_key;
104 // Get the index of the key in the columns
105 var cols = self._get_columns();
106 var index = self.getColIndex(key, cols);
108 // The key is found in the table, set the TR id after the data
109 $(nRow).attr('id', self.id_from_key(key, aData[index]));
112 // That's the usual return value
115 // XXX use $.proxy here !
117 // the intention here is that options.datatables_options as coming from the python object take precedence
118 // xxx DISABLED by jordan: was causing errors in datatables.js
119 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
120 // check your datatables_options tag instead
121 // however, we have to accumulate in aoColumnDefs from here (above)
122 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
123 if ( 'aoColumnDefs' in this.options.datatables_options) {
124 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
125 delete this.options.datatables_options['aoColumnDefs'];
127 $.extend(actual_options, this.options.datatables_options );
128 this.table = this.elmt('table').dataTable(actual_options);
130 /* Setup the SelectAll button in the dataTable header */
131 /* xxx not sure this is still working */
132 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
133 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
135 oSelectAll.css('font-size','11px');
136 oSelectAll.css('float','right');
137 oSelectAll.css('margin-right','15px');
138 oSelectAll.css('margin-bottom','5px');
139 oSelectAll.unbind('click');
140 oSelectAll.click(this._selectAll);
142 /* Add a filtering function to the current table
143 * Note: we use closure to get access to the 'options'
145 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
146 /* No filtering if the table does not match */
147 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
149 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
152 /* Processing hidden_columns */
153 $.each(this.options.hidden_columns, function(i, field) {
154 self.hide_column(field);
156 $(".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>");
157 $(".dataTables_filter input").css("width","100%");
160 var sTable = this.table;
161 $('table.dataTable').delegate('a.resource-info','click',function() {
162 var aPos = sTable.fnGetPosition( this.parentNode );
163 var aData = sTable.fnGetData( aPos[0] );
164 //console.log(aData);
166 var network_hrn = aData[18];
168 'hostname' : strip(aData[2]),
171 'status' : aData[10],
172 'testbed' : aData[4],
173 'facility' : aData[5],
177 //Greece: 37.6687092,22.2282404
178 if (network_hrn == 'omf.nitos') {
180 var resourceLocation = {
181 'longitude' : '22.2282404',
182 'latitude' : '37.6687092',
184 var coordinates = resourceLocation['latitude']+','+resourceLocation['longitude'];
185 } else if (network_hrn == 'iotlab') {
186 var logo = network_hrn;
187 var s = resourceData['hostname'].split(".");
188 var n = s[0].split("-");
189 resourceData['type'] = 'node ( Hardware: <a target="_blank" href="https://www.iot-lab.info/hardware/'+n[0]+'/">'+n[0]+'</a> )';
190 var coordinates = resourceData['testbed'];
192 var logo = network_hrn;
193 var resourceLocation = {
194 'longitude' : aData[13],
195 'latitude' : aData[23],
197 var coordinates = resourceLocation['latitude']+','+resourceLocation['longitude'];
200 var modal = $('#resource-info-modal');
201 modal.find('.modal-title').text(resourceData['testbed'] + ': ' +resourceData['hostname']);
202 table = modal.find('.modal-resource-info');
203 table.html('<tr><td colspan="2"><img class="img-responsive" src="/static/img/testbeds/'+logo+'.png" alt="'+resourceData['facility']+' - '+resourceData['testbed']+'" /></td></tr>');
204 for (var j in resourceData) {
205 table.append('<tr><td>' + j + '</td><td>' + resourceData[j] + '</td></tr>');
207 if (coordinates != '') {
208 table.append('<tr><td colspan="2"><img src="http://maps.google.com/maps/api/staticmap?center='+coordinates+'&zoom=6&size=400x400&sensor=false&markers=color:red%7C'+coordinates+'" style="width:400px; height:400px;" /></td></tr>');
213 }, // initialize_table
216 * @brief Determine index of key in the table columns
220 getColIndex: function(key, cols) {
222 var tabIndex = $.map(cols, function(x, i) { if (self._get_map(x.sTitle) == key) return i; });
223 return (tabIndex.length > 0) ? tabIndex[0] : -1;
226 // create a checkbox <input> tag
227 // computes 'id' attribute from canonical_key
228 // computes 'init_id' from init_key for initialization phase
229 // no need to used convoluted ids with plugin-uuid or others, since
230 // we search using table.$ which looks only in this table
231 checkbox_html : function (record) {
233 // Prefix id with plugin_uuid
235 result += " class='querytable-checkbox'";
236 // compute id from canonical_key
237 var id = record[this.canonical_key]
238 // compute init_id form init_key
239 var init_id=record[this.init_key];
240 // set id - for retrieving from an id, or for posting events upon user's clicks
241 result += " id='"+record[this.canonical_key]+"'";
243 result += "init_id='" + init_id + "'";
245 result += " type='checkbox'";
246 result += " autocomplete='off'";
247 result += "></input>";
252 new_record: function(record)
256 // this models a line in dataTables, each element in the line describes a cell
259 // go through table headers to get column names we want
260 // in order (we have temporarily hack some adjustments in names)
261 var cols = this._get_columns();
262 var colnames = cols.map(function(x) {return self._get_map(x.sTitle)})
263 var nb_col = cols.length;
264 /* if we've requested checkboxes, then forget about the checkbox column for now */
265 //if (this.options.checkboxes) nb_col -= 1;
266 // catch up with the last column if checkboxes were requested
267 if (this.options.checkboxes) {
268 // Use a key instead of hostname (hard coded...)
269 line.push(this.checkbox_html(record));
271 line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
273 /* fill in stuff depending on the column name */
274 for (var j = 2; j < nb_col - 1; j++) { // nb_col includes status
275 if (typeof colnames[j] == 'undefined') {
277 } else if (colnames[j] == 'hostname') {
278 if (record['type'] == 'resource,link')
279 //TODO: we need to add source/destination for links
282 //line.push(record['hostname']);
283 line.push('<a class="resource-info" data-network_hrn="'+record['network_hrn']+'">' + record['hostname'] + '</a>');
285 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
293 /* XXX TODO: Remove this and have something consistant */
295 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
297 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
299 line.push(record[this.init_key]);
301 if (record[colnames[j]])
302 line.push(record[colnames[j]]);
308 // adding an array in one call is *much* more efficient
309 // this.table.fnAddData(line);
313 clear_table: function()
315 this.table.fnClearTable();
318 redraw_table: function()
323 show_column: function(field)
325 var oSettings = this.table.fnSettings();
326 var cols = oSettings.aoColumns;
327 var index = this.getColIndex(field,cols);
329 this.table.fnSetColumnVis(index, true);
332 hide_column: function(field)
334 var oSettings = this.table.fnSettings();
335 var cols = oSettings.aoColumns;
336 var index = this.getColIndex(field,cols);
338 this.table.fnSetColumnVis(index, false);
341 set_checkbox_from_record_key: function (record_key, checked)
343 if (checked === undefined) checked = true;
345 // using table.$ to search inside elements that are not visible
346 var element = this.table.$('[init_id="'+record_key+'"]');
347 element.attr('checked',checked);
350 // id relates to canonical_key
351 set_checkbox_from_data: function (id, checked)
353 if (checked === undefined) checked = true;
355 // using table.$ to search inside elements that are not visible
356 var element = this.table.$("[id='"+id+"']");
357 element.attr('checked',checked);
363 * key_value: the key from which we deduce the id
364 * request: STATUS_OKAY, etc.
365 * content: some HTML content
367 change_status: function(key_value, warnings)
371 if ($.isEmptyObject(warnings)) {
372 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
375 case STATE_SET_IN_SUCCESS:
376 case STATE_SET_OUT_FAILURE:
377 case STATE_SET_IN_PENDING:
378 // Checkmark sign if no warning for an object in the set
382 // Nothing is the object is not in the set
387 msg = '<ul class="nav nav-pills">';
388 msg += '<li class="dropdown">';
389 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>⚠</b></a>';
390 msg += ' <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
391 $.each(warnings, function(i,warning) {
392 msg += '<li><a href="#">' + warning + '</a></li>';
399 $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
400 $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
404 set_bgcolor: function(key_value, class_name)
406 var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
407 if (class_name == QUERYTABLE_BGCOLOR_RESET)
408 elt.removeClass('added removed');
410 elt.addClass((class_name == QUERYTABLE_BGCOLOR_ADDED ? 'added' : 'removed'));
413 populate_table: function()
415 // Let's clear the table and only add lines that are visible
420 var record_keys = [];
421 manifold.query_store.iter_records(this.options.query_uuid, function (record_key, record) {
422 lines.push(self.new_record(record));
423 record_keys.push(record_key);
425 this.table.fnAddData(lines);
426 $.each(record_keys, function(i, record_key) {
427 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
428 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
430 // XXX The row and checkbox still does not exists !!!!
432 case STATE_SET_IN_SUCCESS:
433 case STATE_SET_OUT_FAILURE:
434 self.set_checkbox_from_record_key(record_key, true);
437 case STATE_SET_OUT_SUCCESS:
438 case STATE_SET_IN_FAILURE:
439 //self.set_checkbox_from_record_key(record_key, false);
441 case STATE_SET_IN_PENDING:
442 self.set_checkbox_from_record_key(record_key, true);
443 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_ADDED);
445 case STATE_SET_OUT_PENDING:
446 //self.set_checkbox_from_record_key(record_key, false);
447 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_REMOVED);
450 self.change_status(record_key, warnings); // XXX will retrieve status again
454 /*************************** QUERY HANDLER ****************************/
456 on_filter_added: function(filter)
461 on_filter_removed: function(filter)
466 on_filter_clear: function()
471 on_field_added: function(field)
473 this.show_column(field);
476 on_field_removed: function(field)
478 this.hide_column(field);
481 on_field_clear: function()
483 alert('QueryTable::clear_fields() not implemented');
486 /*************************** RECORD HANDLER ***************************/
488 // Could be the default in parent
489 on_query_in_progress: function()
494 on_query_done: function()
496 this.populate_table();
500 on_field_state_changed: function(data)
502 // XXX We could get this from data.value
503 // var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.state);
509 case STATE_SET_IN_SUCCESS:
510 case STATE_SET_OUT_FAILURE:
511 this.set_checkbox_from_data(data.value, true);
512 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
515 case STATE_SET_OUT_SUCCESS:
516 case STATE_SET_IN_FAILURE:
517 this.set_checkbox_from_data(data.value, false);
518 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
520 case STATE_SET_IN_PENDING:
521 this.set_checkbox_from_data(data.key, true);
522 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_ADDED);
524 case STATE_SET_OUT_PENDING:
525 this.set_checkbox_from_data(data.key, false);
526 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_REMOVED);
532 this.change_status(data.key, data.value);
537 /************************** PRIVATE METHODS ***************************/
539 _get_columns: function()
541 return this.table.fnSettings().aoColumns;
542 // XXX return $.map(table.fnSettings().aoColumns, function(x, i) { return QUERYTABLE_MAP[x]; });
545 _get_map: function(column_title) {
546 return (column_title in QUERYTABLE_MAP) ? QUERYTABLE_MAP[column_title] : column_title;
549 * @brief QueryTable filtering function, called for every line in the datatable.
552 * boolean determining whether the column is visible or not.
554 _querytable_filter: function(oSettings, aData, iDataIndex)
557 var key_col, record_key_value;
559 /* Determine index of key in the table columns */
560 key_col = $.map(oSettings.aoColumns, function(x, i) {if (self._get_map(x.sTitle) == self.canonical_key) return i;})[0];
562 /* Unknown key: no filtering */
563 if (typeof(key_col) == 'undefined') {
564 console.log("Unknown key");
568 record_key_value = unfold.get_value(aData[key_col]);
570 return manifold.query_store.get_record_state(this.options.query_uuid, record_key_value, STATE_VISIBLE);
573 _querytable_draw_callback: function()
576 * Handle clicks on checkboxes: reassociate checkbox click every time
577 * the table is redrawn
579 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
584 /* Remove pagination if we show only a few results */
585 var wrapper = this.table; //.parent().parent().parent();
586 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
587 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
588 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
590 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
591 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
593 $('.querytable_paginate', wrapper).css('visibility', 'visible');
596 if ( rowsToShow <= minRowsPerPage ) {
597 $('.querytable_length', wrapper).css('visibility', 'hidden');
599 $('.querytable_length', wrapper).css('visibility', 'visible');
603 _check_click: function(e)
613 op : this.checked ? STATE_SET_ADD : STATE_SET_REMOVE,
616 manifold.raise_event(self.options.query_uuid, FIELD_STATE_CHANGED, data);
617 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
621 _selectAll: function()
623 // requires jQuery id
624 var uuid=this.id.split("-");
625 var oTable=$("#querytable-"+uuid[1]).dataTable();
626 // Function available in QueryTable 1.9.x
627 // Filter : displayed data only
628 var filterData = oTable._('tr', {"filter":"applied"});
629 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
630 if(filterData.length<=100){
631 $.each(filterData, function(index, obj) {
632 var last=$(obj).last();
633 var key_value=unfold.get_value(last[0]);
634 if(typeof($(last[0]).attr('checked'))=="undefined"){
635 $.publish('selected', 'add/'+key_value);
642 $.plugin('QueryTable', QueryTable);
644 /* define the 'dom-checkbox' type for sorting in datatables
645 http://datatables.net/examples/plug-ins/dom_sort.html
646 using trial and error I found that the actual column number
647 was in fact given as a third argument, and not second
648 as the various online resources had it - go figure */
649 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
650 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
651 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
661 var tmp = document.createElement("DIV");
662 tmp.innerHTML = html;
663 return tmp.textContent || tmp.innerText || "";