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 'Testbed': 'network_hrn',
16 'Resource name': 'hostname',
23 var QueryTable = Plugin.extend({
25 init: function(options, element) {
26 this.classname="querytable";
27 this._super(options, element);
29 /* Member variables */
30 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
31 this.object = query.object; // XXX
34 this.elmt().on('show', this, this.on_show);
35 this.elmt().on('shown.bs.tab', this, this.on_show);
36 this.elmt().on('resize', this, this.on_resize);
38 //// we need 2 different keys
39 // * canonical_key is the primary key as derived from metadata (typically: urn)
40 // and is used to communicate about a given record with the other plugins
41 // * init_key is a key that both kinds of records
42 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
43 // in general query_all will return well populated records, but query
44 // returns records with only the fields displayed on startup
45 var keys = manifold.metadata.get_key(this.object);
46 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
48 this.init_key = this.options.init_key;
49 // have init_key default to canonical_key
50 this.init_key = this.init_key || this.canonical_key;
53 if ( ! this.init_key )
54 messages.warning ("QueryTable : cannot find init_key");
55 if ( ! this.canonical_key )
56 messages.warning ("QueryTable : cannot find canonical_key");
58 messages.debug("querytable: canonical_key="+this.canonical_key+" init_key="+this.init_key);
60 /* Setup query and record handlers */
61 this.listen_query(options.query_uuid);
63 /* GUI setup and event binding */
64 this.initialize_table();
69 on_show: function(e) {
70 if (debug) messages.debug("querytable.on_show");
72 self.table.fnAdjustColumnSizing();
75 on_resize: function(e) {
76 if (debug) messages.debug("querytable.on_resize");
78 self.table.fnAdjustColumnSizing();
83 /* GUI MANIPULATION */
85 initialize_table: function()
87 /* Transforms the table into DataTable, and keep a pointer to it */
89 var actual_options = {
90 // Customize the position of Datatables elements (length,filter,button,...)
91 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
92 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
93 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>>",
94 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
95 // hopefully this would come with dataTables v1.10 ?
96 // in any case, search for 'sPaginationType' all over the code for more comments
97 sPaginationType: 'bootstrap',
98 // Handle the null values & the error : Datatables warning Requested unknown parameter
99 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
100 aoColumnDefs: [{sDefaultContent: '', aTargets: [ '_all' ]}],
101 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
102 // sScrollX: '100%', /* Horizontal scrolling */
103 bProcessing: true, /* Loading */
104 fnDrawCallback: function() { self._querytable_draw_callback.call(self); },
105 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
106 // This function is called on fnAddData to set the TR id. What about fnUpdate ?
108 // Get the key from the raw data array aData
109 var key = self.canonical_key;
111 // Get the index of the key in the columns
112 var cols = self._get_columns();
113 var index = self.getColIndex(key, cols);
115 // The key is found in the table, set the TR id after the data
116 $(nRow).attr('id', self.id_from_key(key, aData[index]));
119 // That's the usual return value
122 // XXX use $.proxy here !
124 // the intention here is that options.datatables_options as coming from the python object take precedence
125 // xxx DISABLED by jordan: was causing errors in datatables.js
126 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
127 // check your datatables_options tag instead
128 // however, we have to accumulate in aoColumnDefs from here (above)
129 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
130 if ( 'aoColumnDefs' in this.options.datatables_options) {
131 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
132 delete this.options.datatables_options['aoColumnDefs'];
134 $.extend(actual_options, this.options.datatables_options );
135 this.table = this.elmt('table').dataTable(actual_options);
137 /* Setup the SelectAll button in the dataTable header */
138 /* xxx not sure this is still working */
139 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
140 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
142 oSelectAll.css('font-size','11px');
143 oSelectAll.css('float','right');
144 oSelectAll.css('margin-right','15px');
145 oSelectAll.css('margin-bottom','5px');
146 oSelectAll.unbind('click');
147 oSelectAll.click(this._selectAll);
149 /* Add a filtering function to the current table
150 * Note: we use closure to get access to the 'options'
152 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
153 /* No filtering if the table does not match */
154 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
156 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
159 /* Processing hidden_columns */
160 $.each(this.options.hidden_columns, function(i, field) {
161 self.hide_column(field);
163 $(".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>");
164 $(".dataTables_filter input").css("width","100%");
165 }, // initialize_table
168 * @brief Determine index of key in the table columns
172 getColIndex: function(key, cols) {
174 var tabIndex = $.map(cols, function(x, i) { if (self._get_map(x.sTitle) == key) return i; });
175 return (tabIndex.length > 0) ? tabIndex[0] : -1;
178 // create a checkbox <input> tag
179 // computes 'id' attribute from canonical_key
180 // computes 'init_id' from init_key for initialization phase
181 // no need to used convoluted ids with plugin-uuid or others, since
182 // we search using table.$ which looks only in this table
183 checkbox_html : function (record) {
185 // Prefix id with plugin_uuid
187 result += " class='querytable-checkbox'";
188 // compute id from canonical_key
189 var id = record[this.canonical_key]
190 // compute init_id form init_key
191 var init_id=record[this.init_key];
192 // set id - for retrieving from an id, or for posting events upon user's clicks
193 result += " id='"+record[this.canonical_key]+"'";
195 result += "init_id='" + init_id + "'";
197 result += " type='checkbox'";
198 result += " autocomplete='off'";
199 result += "></input>";
204 new_record: function(record)
208 // this models a line in dataTables, each element in the line describes a cell
211 // go through table headers to get column names we want
212 // in order (we have temporarily hack some adjustments in names)
213 var cols = this._get_columns();
214 var colnames = cols.map(function(x) {return self._get_map(x.sTitle)})
215 var nb_col = cols.length;
216 /* if we've requested checkboxes, then forget about the checkbox column for now */
217 //if (this.options.checkboxes) nb_col -= 1;
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(record));
223 line.push('<span id="' + this.id_from_key('status', record[this.init_key]) + '"></span>'); // STATUS
225 /* fill in stuff depending on the column name */
226 for (var j = 2; j < nb_col - 1; j++) { // nb_col includes status
227 if (typeof colnames[j] == 'undefined') {
229 } else if (colnames[j] == 'hostname') {
230 if (record['type'] == 'resource,link')
231 //TODO: we need to add source/destination for links
234 line.push(record['hostname']);
236 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
244 /* XXX TODO: Remove this and have something consistant */
246 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
248 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
250 line.push(record[this.init_key]);
252 if (record[colnames[j]])
253 line.push(record[colnames[j]]);
259 // adding an array in one call is *much* more efficient
260 // this.table.fnAddData(line);
264 clear_table: function()
266 this.table.fnClearTable();
269 redraw_table: function()
274 show_column: function(field)
276 var oSettings = this.table.fnSettings();
277 var cols = oSettings.aoColumns;
278 var index = this.getColIndex(field,cols);
280 this.table.fnSetColumnVis(index, true);
283 hide_column: function(field)
285 var oSettings = this.table.fnSettings();
286 var cols = oSettings.aoColumns;
287 var index = this.getColIndex(field,cols);
289 this.table.fnSetColumnVis(index, false);
292 set_checkbox_from_record_key: function (record_key, checked)
294 if (checked === undefined) checked = true;
296 // using table.$ to search inside elements that are not visible
297 var element = this.table.$('[init_id="'+record_key+'"]');
298 element.attr('checked',checked);
301 // id relates to canonical_key
302 set_checkbox_from_data: function (id, checked)
304 if (checked === undefined) checked = true;
306 // using table.$ to search inside elements that are not visible
307 var element = this.table.$("[id='"+id+"']");
308 element.attr('checked',checked);
314 * key_value: the key from which we deduce the id
315 * request: STATUS_OKAY, etc.
316 * content: some HTML content
318 change_status: function(key_value, warnings)
322 if ($.isEmptyObject(warnings)) {
323 var state = manifold.query_store.get_record_state(this.options.query_uuid, key_value, STATE_SET);
326 case STATE_SET_IN_SUCCESS:
327 case STATE_SET_OUT_FAILURE:
328 case STATE_SET_IN_PENDING:
329 // Checkmark sign if no warning for an object in the set
333 // Nothing is the object is not in the set
338 msg = '<ul class="nav nav-pills">';
339 msg += '<li class="dropdown">'
340 msg += '<a href="#" data-toggle="dropdown" class="dropdown-toggle nopadding"><b>⚠</b></a>';
341 msg += ' <ul class="dropdown-menu dropdown-menu-right" id="menu1">';
342 $.each(warnings, function(i,warning) {
343 msg += '<li><a href="#">' + warning + '</a></li>';
350 $(document.getElementById(this.id_from_key('status', key_value))).html(msg);
351 $('[data-toggle="tooltip"]').tooltip({'placement': 'bottom'});
355 set_bgcolor: function(key_value, class_name)
357 var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
358 if (class_name == QUERYTABLE_BGCOLOR_RESET)
359 elt.removeClass('added removed');
361 elt.addClass((class_name == QUERYTABLE_BGCOLOR_ADDED ? 'added' : 'removed'));
364 populate_table: function()
366 // Let's clear the table and only add lines that are visible
371 var record_keys = [];
372 manifold.query_store.iter_records(this.options.query_uuid, function (record_key, record) {
373 lines.push(self.new_record(record));
374 record_keys.push(record_key);
376 this.table.fnAddData(lines);
377 $.each(record_keys, function(i, record_key) {
378 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
379 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
381 // XXX The row and checkbox still does not exists !!!!
383 case STATE_SET_IN_SUCCESS:
384 case STATE_SET_OUT_FAILURE:
385 self.set_checkbox_from_record_key(record_key, true);
388 case STATE_SET_OUT_SUCCESS:
389 case STATE_SET_IN_FAILURE:
390 //self.set_checkbox_from_record_key(record_key, false);
392 case STATE_SET_IN_PENDING:
393 self.set_checkbox_from_record_key(record_key, true);
394 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_ADDED);
396 case STATE_SET_OUT_PENDING:
397 //self.set_checkbox_from_record_key(record_key, false);
398 self.set_bgcolor(record_key, QUERYTABLE_BGCOLOR_REMOVED);
401 self.change_status(record_key, warnings); // XXX will retrieve status again
405 /*************************** QUERY HANDLER ****************************/
407 on_filter_added: function(filter)
412 on_filter_removed: function(filter)
417 on_filter_clear: function()
422 on_field_added: function(field)
424 this.show_column(field);
427 on_field_removed: function(field)
429 this.hide_column(field);
432 on_field_clear: function()
434 alert('QueryTable::clear_fields() not implemented');
437 /*************************** RECORD HANDLER ***************************/
439 // Could be the default in parent
440 on_query_in_progress: function()
445 on_query_done: function()
447 this.populate_table();
451 on_field_state_changed: function(data)
453 // XXX We could get this from data.value
454 // var state = manifold.query_store.get_record_state(this.options.query_uuid, data.value, data.state);
460 case STATE_SET_IN_SUCCESS:
461 case STATE_SET_OUT_FAILURE:
462 this.set_checkbox_from_data(data.value, true);
463 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
466 case STATE_SET_OUT_SUCCESS:
467 case STATE_SET_IN_FAILURE:
468 this.set_checkbox_from_data(data.value, false);
469 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_RESET);
471 case STATE_SET_IN_PENDING:
472 this.set_checkbox_from_data(data.key, true);
473 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_ADDED);
475 case STATE_SET_OUT_PENDING:
476 this.set_checkbox_from_data(data.key, false);
477 this.set_bgcolor(data.value, QUERYTABLE_BGCOLOR_REMOVED);
483 this.change_status(data.key, data.value);
488 /************************** PRIVATE METHODS ***************************/
490 _get_columns: function()
492 return this.table.fnSettings().aoColumns;
493 // XXX return $.map(table.fnSettings().aoColumns, function(x, i) { return QUERYTABLE_MAP[x]; });
496 _get_map: function(column_title) {
497 return (column_title in QUERYTABLE_MAP) ? QUERYTABLE_MAP[column_title] : column_title;
500 * @brief QueryTable filtering function, called for every line in the datatable.
503 * boolean determining whether the column is visible or not.
505 _querytable_filter: function(oSettings, aData, iDataIndex)
508 var key_col, record_key_value;
510 /* Determine index of key in the table columns */
511 key_col = $.map(oSettings.aoColumns, function(x, i) {if (self._get_map(x.sTitle) == self.canonical_key) return i;})[0];
513 /* Unknown key: no filtering */
514 if (typeof(key_col) == 'undefined') {
515 console.log("Unknown key");
519 record_key_value = unfold.get_value(aData[key_col]);
521 return manifold.query_store.get_record_state(this.options.query_uuid, record_key_value, STATE_VISIBLE);
524 _querytable_draw_callback: function()
527 * Handle clicks on checkboxes: reassociate checkbox click every time
528 * the table is redrawn
530 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
535 /* Remove pagination if we show only a few results */
536 var wrapper = this.table; //.parent().parent().parent();
537 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
538 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
539 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
541 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
542 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
544 $('.querytable_paginate', wrapper).css('visibility', 'visible');
547 if ( rowsToShow <= minRowsPerPage ) {
548 $('.querytable_length', wrapper).css('visibility', 'hidden');
550 $('.querytable_length', wrapper).css('visibility', 'visible');
554 _check_click: function(e)
564 op : this.checked ? STATE_SET_ADD : STATE_SET_REMOVE,
567 manifold.raise_event(self.options.query_uuid, FIELD_STATE_CHANGED, data);
568 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
572 _selectAll: function()
574 // requires jQuery id
575 var uuid=this.id.split("-");
576 var oTable=$("#querytable-"+uuid[1]).dataTable();
577 // Function available in QueryTable 1.9.x
578 // Filter : displayed data only
579 var filterData = oTable._('tr', {"filter":"applied"});
580 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
581 if(filterData.length<=100){
582 $.each(filterData, function(index, obj) {
583 var last=$(obj).last();
584 var key_value=unfold.get_value(last[0]);
585 if(typeof($(last[0]).attr('checked'))=="undefined"){
586 $.publish('selected', 'add/'+key_value);
594 $.plugin('QueryTable', QueryTable);
596 /* define the 'dom-checkbox' type for sorting in datatables
597 http://datatables.net/examples/plug-ins/dom_sort.html
598 using trial and error I found that the actual column number
599 was in fact given as a third argument, and not second
600 as the various online resources had it - go figure */
601 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
602 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
603 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';