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') {
187 if (network_hrn == 'iotlab') {
188 var logo = network_hrn;
189 var s = resourceData['hostname'].split(".");
190 var n = s[0].split("-");
191 resourceData['type'] = 'node ( Hardware: <a target="_blank" href="https://www.iot-lab.info/hardware/'+n[0]+'/">'+n[0]+'</a> )';
192 var coordinates = resourceData['testbed'];
194 var logo = network_hrn;
195 var resourceLocation = {
196 'longitude' : aData[13],
197 'latitude' : aData[23],
199 var coordinates = resourceLocation['latitude']+','+resourceLocation['longitude'];
202 var modal = $('#resource-info-modal');
203 modal.find('.modal-title').text(resourceData['testbed'] + ': ' +resourceData['hostname']);
204 table = modal.find('.modal-resource-info');
205 table.html('<tr><td colspan="2"><img class="img-responsive" src="/static/img/testbeds/'+logo+'.png" alt="'+resourceData['facility']+' - '+resourceData['testbed']+'" /></td></tr>');
206 for (var j in resourceData) {
207 table.append('<tr><td>' + j + '</td><td>' + resourceData[j] + '</td></tr>');
209 if (coordinates != '') {
210 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>');
215 }, // initialize_table
218 * @brief Determine index of key in the table columns
222 getColIndex: function(key, cols) {
224 var tabIndex = $.map(cols, function(x, i) { if (self._get_map(x.sTitle) == key) return i; });
225 return (tabIndex.length > 0) ? tabIndex[0] : -1;
228 // create a checkbox <input> tag
229 // computes 'id' attribute from canonical_key
230 // computes 'init_id' from init_key for initialization phase
231 // no need to used convoluted ids with plugin-uuid or others, since
232 // we search using table.$ which looks only in this table
233 checkbox_html : function (record) {
235 // Prefix id with plugin_uuid
237 result += " class='querytable-checkbox'";
238 // compute id from canonical_key
239 var id = record[this.canonical_key]
240 // compute init_id form init_key
241 var init_id=record[this.init_key];
242 // set id - for retrieving from an id, or for posting events upon user's clicks
243 result += " id='"+record[this.canonical_key]+"'";
245 result += "init_id='" + init_id + "'";
247 result += " type='checkbox'";
248 result += " autocomplete='off'";
249 result += "></input>";
254 new_record: function(record)
258 // this models a line in dataTables, each element in the line describes a cell
261 // go through table headers to get column names we want
262 // in order (we have temporarily hack some adjustments in names)
263 var cols = this._get_columns();
264 var colnames = cols.map(function(x) {return self._get_map(x.sTitle)})
265 var nb_col = cols.length;
266 /* if we've requested checkboxes, then forget about the checkbox column for now */
267 //if (this.options.checkboxes) nb_col -= 1;
268 // catch up with the last column if checkboxes were requested
269 if (this.options.checkboxes) {
270 // Use a key instead of hostname (hard coded...)
271 line.push(this.checkbox_html(record));
273 line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
275 /* fill in stuff depending on the column name */
276 for (var j = 2; j < nb_col - 1; j++) { // nb_col includes status
277 if (typeof colnames[j] == 'undefined') {
279 } else if (colnames[j] == 'hostname') {
280 if (record['type'] == 'resource,link')
281 //TODO: we need to add source/destination for links
284 //line.push(record['hostname']);
285 line.push('<a class="resource-info" data-network_hrn="'+record['network_hrn']+'">' + record['hostname'] + '</a>');
287 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
295 /* XXX TODO: Remove this and have something consistant */
297 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
299 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
301 line.push(record[this.init_key]);
303 if (record[colnames[j]])
304 line.push(record[colnames[j]]);
310 // adding an array in one call is *much* more efficient
311 // this.table.fnAddData(line);
315 clear_table: function()
317 this.table.fnClearTable();
320 redraw_table: function()
325 show_column: function(field)
327 var oSettings = this.table.fnSettings();
328 var cols = oSettings.aoColumns;
329 var index = this.getColIndex(field,cols);
331 this.table.fnSetColumnVis(index, true);
334 hide_column: function(field)
336 var oSettings = this.table.fnSettings();
337 var cols = oSettings.aoColumns;
338 var index = this.getColIndex(field,cols);
340 this.table.fnSetColumnVis(index, false);
343 set_checkbox_from_record_key: function (record_key, checked)
345 if (checked === undefined) checked = true;
347 // using table.$ to search inside elements that are not visible
348 var element = this.table.$('[init_id="'+record_key+'"]');
349 element.attr('checked',checked);
352 // id relates to canonical_key
353 set_checkbox_from_data: function (id, checked)
355 if (checked === undefined) checked = true;
357 // using table.$ to search inside elements that are not visible
358 var element = this.table.$("[id='"+id+"']");
359 element.attr('checked',checked);
365 * key_value: the key from which we deduce the id
366 * request: STATUS_OKAY, etc.
367 * content: some HTML content
369 change_status: function(key_value, warnings)
373 if ($.isEmptyObject(warnings)) {
374 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
377 case STATE_SET_IN_SUCCESS:
378 case STATE_SET_OUT_FAILURE:
379 case STATE_SET_IN_PENDING:
380 // Checkmark sign if no warning for an object in the set
384 // Nothing is the object is not in the set
389 msg = '<ul class="nav nav-pills">';
390 msg += '<li class="dropdown">';
391 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>⚠</b></a>';
392 msg += ' <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
393 $.each(warnings, function(i,warning) {
394 msg += '<li><a href="#">' + warning + '</a></li>';
401 $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
402 $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
406 set_bgcolor: function(key_value, class_name)
408 var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
409 if (class_name == QUERYTABLE_BGCOLOR_RESET)
410 elt.removeClass('added removed');
412 elt.addClass((class_name == QUERYTABLE_BGCOLOR_ADDED ? 'added' : 'removed'));
415 populate_table: function()
417 // Let's clear the table and only add lines that are visible
422 var record_keys = [];
423 manifold.query_store.iter_records(this.options.query_uuid, function (record_key, record) {
424 lines.push(self.new_record(record));
425 record_keys.push(record_key);
427 this.table.fnAddData(lines);
428 $.each(record_keys, function(i, record_key) {
429 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
430 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
432 // XXX The row and checkbox still does not exists !!!!
434 case STATE_SET_IN_SUCCESS:
435 case STATE_SET_OUT_FAILURE:
436 self.set_checkbox_from_record_key(record_key, true);
439 case STATE_SET_OUT_SUCCESS:
440 case STATE_SET_IN_FAILURE:
441 //self.set_checkbox_from_record_key(record_key, false);
443 case STATE_SET_IN_PENDING:
444 self.set_checkbox_from_record_key(record_key, true);
445 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_ADDED);
447 case STATE_SET_OUT_PENDING:
448 //self.set_checkbox_from_record_key(record_key, false);
449 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_REMOVED);
452 self.change_status(record_key, warnings); // XXX will retrieve status again
456 /*************************** QUERY HANDLER ****************************/
458 on_filter_added: function(filter)
463 on_filter_removed: function(filter)
468 on_filter_clear: function()
473 on_field_added: function(field)
475 this.show_column(field);
478 on_field_removed: function(field)
480 this.hide_column(field);
483 on_field_clear: function()
485 alert('QueryTable::clear_fields() not implemented');
488 /*************************** RECORD HANDLER ***************************/
490 // Could be the default in parent
491 on_query_in_progress: function()
496 on_query_done: function()
498 this.populate_table();
502 on_field_state_changed: function(data)
504 // XXX We could get this from data.value
505 // var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.state);
511 case STATE_SET_IN_SUCCESS:
512 case STATE_SET_OUT_FAILURE:
513 this.set_checkbox_from_data(data.value, true);
514 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
517 case STATE_SET_OUT_SUCCESS:
518 case STATE_SET_IN_FAILURE:
519 this.set_checkbox_from_data(data.value, false);
520 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
522 case STATE_SET_IN_PENDING:
523 this.set_checkbox_from_data(data.key, true);
524 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_ADDED);
526 case STATE_SET_OUT_PENDING:
527 this.set_checkbox_from_data(data.key, false);
528 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_REMOVED);
534 this.change_status(data.key, data.value);
539 /************************** PRIVATE METHODS ***************************/
541 _get_columns: function()
543 return this.table.fnSettings().aoColumns;
544 // XXX return $.map(table.fnSettings().aoColumns, function(x, i) { return QUERYTABLE_MAP[x]; });
547 _get_map: function(column_title) {
548 return (column_title in QUERYTABLE_MAP) ? QUERYTABLE_MAP[column_title] : column_title;
551 * @brief QueryTable filtering function, called for every line in the datatable.
554 * boolean determining whether the column is visible or not.
556 _querytable_filter: function(oSettings, aData, iDataIndex)
559 var key_col, record_key_value;
561 /* Determine index of key in the table columns */
562 key_col = $.map(oSettings.aoColumns, function(x, i) {if (self._get_map(x.sTitle) == self.canonical_key) return i;})[0];
564 /* Unknown key: no filtering */
565 if (typeof(key_col) == 'undefined') {
566 console.log("Unknown key");
570 record_key_value = unfold.get_value(aData[key_col]);
572 return manifold.query_store.get_record_state(this.options.query_uuid, record_key_value, STATE_VISIBLE);
575 _querytable_draw_callback: function()
578 * Handle clicks on checkboxes: reassociate checkbox click every time
579 * the table is redrawn
581 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
586 /* Remove pagination if we show only a few results */
587 var wrapper = this.table; //.parent().parent().parent();
588 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
589 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
590 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
592 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
593 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
595 $('.querytable_paginate', wrapper).css('visibility', 'visible');
598 if ( rowsToShow <= minRowsPerPage ) {
599 $('.querytable_length', wrapper).css('visibility', 'hidden');
601 $('.querytable_length', wrapper).css('visibility', 'visible');
605 _check_click: function(e)
615 op : this.checked ? STATE_SET_ADD : STATE_SET_REMOVE,
618 manifold.raise_event(self.options.query_uuid, FIELD_STATE_CHANGED, data);
619 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
623 _selectAll: function()
625 // requires jQuery id
626 var uuid=this.id.split("-");
627 var oTable=$("#querytable-"+uuid[1]).dataTable();
628 // Function available in QueryTable 1.9.x
629 // Filter : displayed data only
630 var filterData = oTable._('tr', {"filter":"applied"});
631 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
632 if(filterData.length<=100){
633 $.each(filterData, function(index, obj) {
634 var last=$(obj).last();
635 var key_value=unfold.get_value(last[0]);
636 if(typeof($(last[0]).attr('checked'))=="undefined"){
637 $.publish('selected', 'add/'+key_value);
644 $.plugin('QueryTable', QueryTable);
646 /* define the 'dom-checkbox' type for sorting in datatables
647 http://datatables.net/examples/plug-ins/dom_sort.html
648 using trial and error I found that the actual column number
649 was in fact given as a third argument, and not second
650 as the various online resources had it - go figure */
651 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
652 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
653 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
663 var tmp = document.createElement("DIV");
664 tmp.innerHTML = html;
665 return tmp.textContent || tmp.innerText || "";