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;
14 var QUERYTABLE_MAP = {
15 'Facility': 'facility_name',
16 'Testbed': 'testbed_name',
17 'Resource name': 'hostname',
24 var QueryTable = Plugin.extend({
26 init: function(options, element) {
27 this.classname="querytable";
28 this._super(options, element);
30 /* Member variables */
31 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
32 this.object = query.object; // XXX
35 this.elmt().on('show', this, this.on_show);
36 this.elmt().on('shown.bs.tab', this, this.on_show);
37 this.elmt().on('resize', this, this.on_resize);
39 //// we need 2 different keys
40 // * canonical_key is the primary key as derived from metadata (typically: urn)
41 // and is used to communicate about a given record with the other plugins
42 // * init_key is a key that both kinds of records
43 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
44 // in general query_all will return well populated records, but query
45 // returns records with only the fields displayed on startup
46 var keys = manifold.metadata.get_key(this.object);
47 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
49 this.init_key = this.options.init_key;
50 // have init_key default to canonical_key
51 this.init_key = this.init_key || this.canonical_key;
54 if ( ! this.init_key )
55 messages.warning ("QueryTable : cannot find init_key");
56 if ( ! this.canonical_key )
57 messages.warning ("QueryTable : cannot find canonical_key");
59 messages.debug("querytable: canonical_key="+this.canonical_key+" init_key="+this.init_key);
61 /* Setup query and record handlers */
62 this.listen_query(options.query_uuid);
64 /* GUI setup and event binding */
65 this.initialize_table();
70 on_show: function(e) {
71 if (debug) messages.debug("querytable.on_show");
73 self.table.fnAdjustColumnSizing();
76 on_resize: function(e) {
77 if (debug) messages.debug("querytable.on_resize");
79 self.table.fnAdjustColumnSizing();
84 /* GUI MANIPULATION */
86 initialize_table: function()
88 /* Transforms the table into DataTable, and keep a pointer to it */
90 var actual_options = {
91 // Customize the position of Datatables elements (length,filter,button,...)
92 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
93 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
94 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>>",
95 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
96 // hopefully this would come with dataTables v1.10 ?
97 // in any case, search for 'sPaginationType' all over the code for more comments
98 sPaginationType: 'bootstrap',
99 // Handle the null values & the error : Datatables warning Requested unknown parameter
100 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
101 aoColumnDefs: [{sDefaultContent: '', aTargets: [ '_all' ]}],
102 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
103 // sScrollX: '100%', /* Horizontal scrolling */
104 bProcessing: true, /* Loading */
105 fnDrawCallback: function() { self._querytable_draw_callback.call(self); },
106 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
107 // This function is called on fnAddData to set the TR id. What about fnUpdate ?
109 // Get the key from the raw data array aData
110 var key = self.canonical_key;
112 // Get the index of the key in the columns
113 var cols = self._get_columns();
114 var index = self.getColIndex(key, cols);
116 // The key is found in the table, set the TR id after the data
117 $(nRow).attr('id', self.id_from_key(key, aData[index]));
120 // That's the usual return value
123 // XXX use $.proxy here !
125 // the intention here is that options.datatables_options as coming from the python object take precedence
126 // xxx DISABLED by jordan: was causing errors in datatables.js
127 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
128 // check your datatables_options tag instead
129 // however, we have to accumulate in aoColumnDefs from here (above)
130 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
131 if ( 'aoColumnDefs' in this.options.datatables_options) {
132 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
133 delete this.options.datatables_options['aoColumnDefs'];
135 $.extend(actual_options, this.options.datatables_options );
136 this.table = this.elmt('table').dataTable(actual_options);
138 /* Setup the SelectAll button in the dataTable header */
139 /* xxx not sure this is still working */
140 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
141 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
143 oSelectAll.css('font-size','11px');
144 oSelectAll.css('float','right');
145 oSelectAll.css('margin-right','15px');
146 oSelectAll.css('margin-bottom','5px');
147 oSelectAll.unbind('click');
148 oSelectAll.click(this._selectAll);
150 /* Add a filtering function to the current table
151 * Note: we use closure to get access to the 'options'
153 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
154 /* No filtering if the table does not match */
155 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
157 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
160 /* Processing hidden_columns */
161 $.each(this.options.hidden_columns, function(i, field) {
162 self.hide_column(field);
164 $(".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>");
165 $(".dataTables_filter input").css("width","100%");
168 var sTable = this.table;
169 $('table.dataTable').delegate('a.resource-info','click',function() {
170 var aPos = sTable.fnGetPosition( this.parentNode );
171 var aData = sTable.fnGetData( aPos[0] );
172 //console.log(aData);
174 var network_hrn = aData[18];
176 'hostname' : strip(aData[2]),
179 'status' : aData[10],
180 'testbed' : aData[4],
181 'facility' : aData[5],
185 console.log(network_hrn);
186 //Greece: 37.6687092,22.2282404
187 if (network_hrn == 'omf.nitos') {
189 var resourceLocation = {
190 'longitude' : '22.2282404',
191 'latitude' : '37.6687092',
193 var coordinates = resourceLocation['latitude']+','+resourceLocation['longitude'];
194 } else if (network_hrn == 'iotlab') {
195 var logo = network_hrn;
196 var s = resourceData['hostname'].split(".");
197 var n = s[0].split("-");
198 resourceData['type'] = 'node ( Hardware: <a target="_blank" href="https://www.iot-lab.info/hardware/'+n[0]+'/">'+n[0]+'</a> )';
199 var coordinates = resourceData['testbed'];
201 var logo = network_hrn;
202 var resourceLocation = {
203 'longitude' : aData[13],
204 'latitude' : aData[23],
206 var coordinates = resourceLocation['latitude']+','+resourceLocation['longitude'];
209 var modal = $('#resource-info-modal');
210 modal.find('.modal-title').text(resourceData['testbed'] + ': ' +resourceData['hostname']);
211 table = modal.find('.modal-resource-info');
212 table.html('<tr><td colspan="2"><img class="img-responsive" src="/static/img/testbeds/'+logo+'.png" alt="'+resourceData['facility']+' - '+resourceData['testbed']+'" /></td></tr>');
213 for (var j in resourceData) {
214 table.append('<tr><td>' + j + '</td><td>' + resourceData[j] + '</td></tr>');
216 if (coordinates != '') {
217 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>');
222 }, // initialize_table
225 * @brief Determine index of key in the table columns
229 getColIndex: function(key, cols) {
231 var tabIndex = $.map(cols, function(x, i) { if (self._get_map(x.sTitle) == key) return i; });
232 return (tabIndex.length > 0) ? tabIndex[0] : -1;
235 // create a checkbox <input> tag
236 // computes 'id' attribute from canonical_key
237 // computes 'init_id' from init_key for initialization phase
238 // no need to used convoluted ids with plugin-uuid or others, since
239 // we search using table.$ which looks only in this table
240 checkbox_html : function (record) {
242 // Prefix id with plugin_uuid
244 result += " class='querytable-checkbox'";
245 // compute id from canonical_key
246 var id = record[this.canonical_key]
247 // compute init_id form init_key
248 var init_id=record[this.init_key];
249 // set id - for retrieving from an id, or for posting events upon user's clicks
250 result += " id='"+record[this.canonical_key]+"'";
252 result += "init_id='" + init_id + "'";
254 result += " type='checkbox'";
255 result += " autocomplete='off'";
256 result += "></input>";
261 new_record: function(record)
265 // this models a line in dataTables, each element in the line describes a cell
268 // go through table headers to get column names we want
269 // in order (we have temporarily hack some adjustments in names)
270 var cols = this._get_columns();
271 var colnames = cols.map(function(x) {return self._get_map(x.sTitle)})
272 var nb_col = cols.length;
273 /* if we've requested checkboxes, then forget about the checkbox column for now */
274 //if (this.options.checkboxes) nb_col -= 1;
275 // catch up with the last column if checkboxes were requested
276 if (this.options.checkboxes) {
277 // Use a key instead of hostname (hard coded...)
278 line.push(this.checkbox_html(record));
280 line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
282 /* fill in stuff depending on the column name */
283 for (var j = 2; j < nb_col - 1; j++) { // nb_col includes status
284 if (typeof colnames[j] == 'undefined') {
286 } else if (colnames[j] == 'hostname') {
287 if (record['type'] == 'resource,link')
288 //TODO: we need to add source/destination for links
291 //line.push(record['hostname']);
292 line.push('<a class="resource-info" data-network_hrn="'+record['network_hrn']+'">' + record['hostname'] + '</a>');
294 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
302 /* XXX TODO: Remove this and have something consistant */
304 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
306 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
308 line.push(record[this.init_key]);
310 if (record[colnames[j]])
311 line.push(record[colnames[j]]);
317 // adding an array in one call is *much* more efficient
318 // this.table.fnAddData(line);
322 clear_table: function()
324 this.table.fnClearTable();
327 redraw_table: function()
332 show_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, true);
341 hide_column: function(field)
343 var oSettings = this.table.fnSettings();
344 var cols = oSettings.aoColumns;
345 var index = this.getColIndex(field,cols);
347 this.table.fnSetColumnVis(index, false);
350 set_checkbox_from_record_key: function (record_key, checked)
352 if (checked === undefined) checked = true;
354 // using table.$ to search inside elements that are not visible
355 var element = this.table.$('[init_id="'+record_key+'"]');
356 element.attr('checked',checked);
359 // id relates to canonical_key
360 set_checkbox_from_data: function (id, checked)
362 if (checked === undefined) checked = true;
364 // using table.$ to search inside elements that are not visible
365 var element = this.table.$("[id='"+id+"']");
366 element.attr('checked',checked);
372 * key_value: the key from which we deduce the id
373 * request: STATUS_OKAY, etc.
374 * content: some HTML content
376 change_status: function(key_value, warnings)
380 if ($.isEmptyObject(warnings)) {
381 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
384 case STATE_SET_IN_SUCCESS:
385 case STATE_SET_OUT_FAILURE:
386 case STATE_SET_IN_PENDING:
387 // Checkmark sign if no warning for an object in the set
391 // Nothing is the object is not in the set
396 msg = '<ul class="nav nav-pills">';
397 msg += '<li class="dropdown">';
398 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>⚠</b></a>';
399 msg += ' <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
400 $.each(warnings, function(i,warning) {
401 msg += '<li><a href="#">' + warning + '</a></li>';
408 $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
409 $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
413 set_bgcolor: function(key_value, class_name)
415 var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
416 if (class_name == QUERYTABLE_BGCOLOR_RESET)
417 elt.removeClass('added removed');
419 elt.addClass((class_name == QUERYTABLE_BGCOLOR_ADDED ? 'added' : 'removed'));
422 populate_table: function()
424 // Let's clear the table and only add lines that are visible
429 var record_keys = [];
430 manifold.query_store.iter_records(this.options.query_uuid, function (record_key, record) {
431 lines.push(self.new_record(record));
432 record_keys.push(record_key);
434 this.table.fnAddData(lines);
435 $.each(record_keys, function(i, record_key) {
436 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
437 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
439 // XXX The row and checkbox still does not exists !!!!
441 case STATE_SET_IN_SUCCESS:
442 case STATE_SET_OUT_FAILURE:
443 self.set_checkbox_from_record_key(record_key, true);
446 case STATE_SET_OUT_SUCCESS:
447 case STATE_SET_IN_FAILURE:
448 //self.set_checkbox_from_record_key(record_key, false);
450 case STATE_SET_IN_PENDING:
451 self.set_checkbox_from_record_key(record_key, true);
452 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_ADDED);
454 case STATE_SET_OUT_PENDING:
455 //self.set_checkbox_from_record_key(record_key, false);
456 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_REMOVED);
459 self.change_status(record_key, warnings); // XXX will retrieve status again
463 /*************************** QUERY HANDLER ****************************/
465 on_filter_added: function(filter)
470 on_filter_removed: function(filter)
475 on_filter_clear: function()
480 on_field_added: function(field)
482 this.show_column(field);
485 on_field_removed: function(field)
487 this.hide_column(field);
490 on_field_clear: function()
492 alert('QueryTable::clear_fields() not implemented');
495 /*************************** RECORD HANDLER ***************************/
497 // Could be the default in parent
498 on_query_in_progress: function()
503 on_query_done: function()
505 this.populate_table();
509 on_field_state_changed: function(data)
511 // XXX We could get this from data.value
512 // var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.state);
518 case STATE_SET_IN_SUCCESS:
519 case STATE_SET_OUT_FAILURE:
520 this.set_checkbox_from_data(data.value, true);
521 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
524 case STATE_SET_OUT_SUCCESS:
525 case STATE_SET_IN_FAILURE:
526 this.set_checkbox_from_data(data.value, false);
527 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
529 case STATE_SET_IN_PENDING:
530 this.set_checkbox_from_data(data.key, true);
531 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_ADDED);
533 case STATE_SET_OUT_PENDING:
534 this.set_checkbox_from_data(data.key, false);
535 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_REMOVED);
541 this.change_status(data.key, data.value);
546 /************************** PRIVATE METHODS ***************************/
548 _get_columns: function()
550 return this.table.fnSettings().aoColumns;
551 // XXX return $.map(table.fnSettings().aoColumns, function(x, i) { return QUERYTABLE_MAP[x]; });
554 _get_map: function(column_title) {
555 return (column_title in QUERYTABLE_MAP) ? QUERYTABLE_MAP[column_title] : column_title;
558 * @brief QueryTable filtering function, called for every line in the datatable.
561 * boolean determining whether the column is visible or not.
563 _querytable_filter: function(oSettings, aData, iDataIndex)
566 var key_col, record_key_value;
568 /* Determine index of key in the table columns */
569 key_col = $.map(oSettings.aoColumns, function(x, i) {if (self._get_map(x.sTitle) == self.canonical_key) return i;})[0];
571 /* Unknown key: no filtering */
572 if (typeof(key_col) == 'undefined') {
573 console.log("Unknown key");
577 record_key_value = unfold.get_value(aData[key_col]);
579 return manifold.query_store.get_record_state(this.options.query_uuid, record_key_value, STATE_VISIBLE);
582 _querytable_draw_callback: function()
585 * Handle clicks on checkboxes: reassociate checkbox click every time
586 * the table is redrawn
588 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
593 /* Remove pagination if we show only a few results */
594 var wrapper = this.table; //.parent().parent().parent();
595 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
596 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
597 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
599 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
600 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
602 $('.querytable_paginate', wrapper).css('visibility', 'visible');
605 if ( rowsToShow <= minRowsPerPage ) {
606 $('.querytable_length', wrapper).css('visibility', 'hidden');
608 $('.querytable_length', wrapper).css('visibility', 'visible');
612 _check_click: function(e)
622 op : this.checked ? STATE_SET_ADD : STATE_SET_REMOVE,
625 manifold.raise_event(self.options.query_uuid, FIELD_STATE_CHANGED, data);
626 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
630 _selectAll: function()
632 // requires jQuery id
633 var uuid=this.id.split("-");
634 var oTable=$("#querytable-"+uuid[1]).dataTable();
635 // Function available in QueryTable 1.9.x
636 // Filter : displayed data only
637 var filterData = oTable._('tr', {"filter":"applied"});
638 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
639 if(filterData.length<=100){
640 $.each(filterData, function(index, obj) {
641 var last=$(obj).last();
642 var key_value=unfold.get_value(last[0]);
643 if(typeof($(last[0]).attr('checked'))=="undefined"){
644 $.publish('selected', 'add/'+key_value);
651 $.plugin('QueryTable', QueryTable);
653 /* define the 'dom-checkbox' type for sorting in datatables
654 http://datatables.net/examples/plug-ins/dom_sort.html
655 using trial and error I found that the actual column number
656 was in fact given as a third argument, and not second
657 as the various online resources had it - go figure */
658 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
659 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
660 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
670 var tmp = document.createElement("DIV");
671 tmp.innerHTML = html;
672 return tmp.textContent || tmp.innerText || "";