2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
12 var QueryTable = Plugin.extend({
14 init: function(options, element) {
15 this.classname="querytable";
16 this._super(options, element);
18 /* Member variables */
19 // in general we expect 2 queries here
20 // query_uuid refers to a single object (typically a slice)
21 // query_all_uuid refers to a list (typically resources or users)
22 // these can return in any order so we keep track of which has been received yet
23 this.received_all_query = false;
24 this.received_query = false;
26 // We need to remember the active filter for datatables filtering
27 this.filters = Array();
29 // an internal buffer for records that are 'in' and thus need to be checked
30 this.buffered_records_to_check = [];
31 // an internal buffer for keeping lines and display them in one call to fnAddData
32 this.buffered_lines = [];
35 // xx somehow non of these triggers at all for now
36 this.elmt().on('show', this, this.on_show);
37 this.elmt().on('shown.bs.tab', this, this.on_show);
38 this.elmt().on('resize', this, this.on_resize);
40 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
41 this.object = query.object;
43 //// we need 2 different keys
44 // * canonical_key is the primary key as derived from metadata (typically: urn)
45 // and is used to communicate about a given record with the other plugins
46 // * init_key is a key that both kinds of records
47 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
48 // in general query_all will return well populated records, but query
49 // returns records with only the fields displayed on startup
50 var keys = manifold.metadata.get_key(this.object);
51 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
53 this.init_key = this.options.init_key;
54 // have init_key default to canonical_key
55 this.init_key = this.init_key || this.canonical_key;
57 if ( ! this.init_key ) messages.warning ("QueryTable : cannot find init_key");
58 if ( ! this.canonical_key ) messages.warning ("QueryTable : cannot find canonical_key");
59 if (debug) 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);
63 this.listen_query(options.query_all_uuid, 'all');
65 /* GUI setup and event binding */
66 this.initialize_table();
71 on_show: function(e) {
72 if (debug) messages.debug("querytable.on_show");
74 self.table.fnAdjustColumnSizing();
77 on_resize: function(e) {
78 if (debug) messages.debug("querytable.on_resize");
80 self.table.fnAdjustColumnSizing();
85 /* GUI MANIPULATION */
87 initialize_table: function()
89 /* Transforms the table into DataTable, and keep a pointer to it */
91 var actual_options = {
92 // Customize the position of Datatables elements (length,filter,button,...)
93 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
94 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
95 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>>",
96 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
97 // hopefully this would come with dataTables v1.10 ?
98 // in any case, search for 'sPaginationType' all over the code for more comments
99 sPaginationType: 'bootstrap',
100 // Handle the null values & the error : Datatables warning Requested unknown parameter
101 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
102 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
103 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
104 // sScrollX: '100%', /* Horizontal scrolling */
105 bProcessing: true, /* Loading */
106 fnDrawCallback: function() { self._querytable_draw_callback.call(self); },
107 fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
108 // This function is called on fnAddData to set the TR id. What about fnUpdate ?
110 // Get the key from the raw data array aData
111 var key = self.canonical_key;
113 // Get the index of the key in the columns
114 var cols = self.table.fnSettings().aoColumns;
115 var index = self.getColIndex(key, cols);
117 // The key is found in the table, set the TR id after the data
118 $(nRow).attr('id', self.id_from_key(key, aData[index]));
121 // That's the usual return value
124 // XXX use $.proxy here !
126 // the intention here is that options.datatables_options as coming from the python object take precedence
127 // xxx DISABLED by jordan: was causing errors in datatables.js
128 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
129 // check your datatables_options tag instead
130 // however, we have to accumulate in aoColumnDefs from here (above)
131 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
132 if ( 'aoColumnDefs' in this.options.datatables_options) {
133 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
134 delete this.options.datatables_options['aoColumnDefs'];
136 $.extend(actual_options, this.options.datatables_options );
137 this.table = this.elmt('table').dataTable(actual_options);
139 /* Setup the SelectAll button in the dataTable header */
140 /* xxx not sure this is still working */
141 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
142 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
144 oSelectAll.css('font-size','11px');
145 oSelectAll.css('float','right');
146 oSelectAll.css('margin-right','15px');
147 oSelectAll.css('margin-bottom','5px');
148 oSelectAll.unbind('click');
149 oSelectAll.click(this._selectAll);
151 /* Add a filtering function to the current table
152 * Note: we use closure to get access to the 'options'
154 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
155 /* No filtering if the table does not match */
156 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
158 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
161 /* Processing hidden_columns */
162 $.each(this.options.hidden_columns, function(i, field) {
163 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
164 self.hide_column(field);
166 $(".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>");
167 $(".dataTables_filter input").css("width","100%");
168 }, // initialize_table
171 * @brief Determine index of key in the table columns
175 getColIndex: function(key, cols) {
176 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
177 return (tabIndex.length > 0) ? tabIndex[0] : -1;
180 // create a checkbox <input> tag
181 // computes 'id' attribute from canonical_key
182 // computes 'init_id' from init_key for initialization phase
183 // no need to used convoluted ids with plugin-uuid or others, since
184 // we search using table.$ which looks only in this table
185 checkbox_html : function (record) {
187 // Prefix id with plugin_uuid
189 result += " class='querytable-checkbox'";
190 // compute id from canonical_key
191 var id = record[this.canonical_key]
192 // compute init_id form init_key
193 var init_id=record[this.init_key];
194 // set id - for retrieving from an id, or for posting events upon user's clicks
195 result += " id='"+record[this.canonical_key]+"'";
197 result += "init_id='" + init_id + "'";
199 result += " type='checkbox'";
200 result += " autocomplete='off'";
201 result += "></input>";
206 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.table.fnSettings().aoColumns;
214 var colnames = cols.map(function(x) {return 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));
224 /* fill in stuff depending on the column name */
225 for (var j = 1; j < nb_col; j++) {
226 if (typeof colnames[j] == 'undefined') {
228 } else if (colnames[j] == 'hostname') {
229 if (record['type'] == 'resource,link')
230 //TODO: we need to add source/destination for links
233 line.push(record['hostname']);
235 } else if (colnames[j] == this.init_key && typeof(record) != 'undefined') {
243 /* XXX TODO: Remove this and have something consistant */
245 //line.push('<a href="../'+obj+'/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
247 //line.push('<a href="../'+obj+'/'+record[this.init_key]+'"><span class="glyphicon glyphicon-search"></span></a> '+record[this.init_key]);
249 line.push(record[this.init_key]);
251 if (record[colnames[j]])
252 line.push(record[colnames[j]]);
260 // adding an array in one call is *much* more efficient
261 // this.table.fnAddData(line);
262 this.buffered_lines.push(line);
265 clear_table: function()
267 this.table.fnClearTable();
270 redraw_table: function()
275 show_column: function(field)
277 var oSettings = this.table.fnSettings();
278 var cols = oSettings.aoColumns;
279 var index = this.getColIndex(field,cols);
281 this.table.fnSetColumnVis(index, true);
284 hide_column: function(field)
286 var oSettings = this.table.fnSettings();
287 var cols = oSettings.aoColumns;
288 var index = this.getColIndex(field,cols);
290 this.table.fnSetColumnVis(index, false);
293 // this is used at init-time, at which point only init_key can make sense
294 // (because the argument record, if it comes from query, might not have canonical_key set
295 set_checkbox_from_record: function (record, checked) {
296 if (checked === undefined) checked = true;
297 var init_id = record[this.init_key];
298 if (debug) messages.debug("querytable.set_checkbox_from_record, init_id="+init_id);
299 // using table.$ to search inside elements that are not visible
300 var element = this.table.$('[init_id="'+init_id+'"]');
301 element.attr('checked',checked);
304 // id relates to canonical_key
305 set_checkbox_from_data: function (id, checked) {
306 if (checked === undefined) checked = true;
307 if (debug) messages.debug("querytable.set_checkbox_from_data, id="+id);
308 // using table.$ to search inside elements that are not visible
309 var element = this.table.$("[id='"+id+"']");
310 element.attr('checked',checked);
313 /*************************** QUERY HANDLER ****************************/
315 on_filter_added: function(filter)
317 this.filters.push(filter);
321 on_filter_removed: function(filter)
323 // Remove corresponding filters
324 this.filters = $.grep(this.filters, function(x) {
330 on_filter_clear: function()
336 on_field_added: function(field)
338 this.show_column(field);
341 on_field_removed: function(field)
343 this.hide_column(field);
346 on_field_clear: function()
348 alert('QueryTable::clear_fields() not implemented');
351 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
352 /*************************** ALL QUERY HANDLER ****************************/
354 on_all_filter_added: function(filter)
360 on_all_filter_removed: function(filter)
366 on_all_filter_clear: function()
372 on_all_field_added: function(field)
374 this.show_column(field);
377 on_all_field_removed: function(field)
379 this.hide_column(field);
382 on_all_field_clear: function()
384 alert('QueryTable::clear_fields() not implemented');
388 /*************************** RECORD HANDLER ***************************/
390 on_new_record: function(record)
392 if (this.received_all_query) {
393 // if the 'all' query has been dealt with already we may turn on the checkbox
394 this.set_checkbox_from_record(record, true);
396 this.buffered_records_to_check.push(record);
400 on_clear_records: function()
404 // Could be the default in parent
405 on_query_in_progress: function()
410 on_query_done: function()
412 this.received_query = true;
413 // unspin once we have received both
414 if (this.received_all_query && this.received_query) this.unspin();
417 on_field_state_changed: function(data)
419 switch(data.request) {
420 case FIELD_REQUEST_ADD:
421 case FIELD_REQUEST_ADD_RESET:
422 this.set_checkbox_from_data(data.value, true);
424 case FIELD_REQUEST_REMOVE:
425 case FIELD_REQUEST_REMOVE_RESET:
426 this.set_checkbox_from_data(data.value, false);
433 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
435 on_all_field_state_changed: function(data)
437 switch(data.request) {
438 case FIELD_REQUEST_ADD:
439 case FIELD_REQUEST_ADD_RESET:
440 this.set_checkbox_from_data(data.value, true);
442 case FIELD_REQUEST_REMOVE:
443 case FIELD_REQUEST_REMOVE_RESET:
444 this.set_checkbox_from_data(data.value, false);
451 on_all_new_record: function(record)
453 this.new_record(record);
456 on_all_clear_records: function()
462 on_all_query_in_progress: function()
466 }, // on_all_query_in_progress
468 on_all_query_done: function()
470 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
471 this.table.fnAddData (this.buffered_lines);
472 this.buffered_lines=[];
475 // if we've already received the slice query, we have not been able to set
476 // checkboxes on the fly at that time (dom not yet created)
477 $.each(this.buffered_records_to_check, function(i, record) {
478 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
479 self.set_checkbox_from_record(record, true);
481 this.buffered_records_to_check = [];
483 this.received_all_query = true;
484 // unspin once we have received both
485 if (this.received_all_query && this.received_query) this.unspin();
487 }, // on_all_query_done
489 /************************** PRIVATE METHODS ***************************/
492 * @brief QueryTable filtering function
494 _querytable_filter: function(oSettings, aData, iDataIndex)
497 $.each (this.filters, function(index, filter) {
498 /* XXX How to manage checkbox ? */
501 var value = filter[2];
503 /* Determine index of key in the table columns */
504 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
506 /* Unknown key: no filtering */
507 if (typeof(col) == 'undefined')
510 col_value=unfold.get_value(aData[col]);
511 /* Test whether current filter is compatible with the column */
512 if (op == '=' || op == '==') {
513 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
515 }else if (op == 'included') {
516 $.each(value, function(i,x) {
524 }else if (op == '!=') {
525 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
528 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
531 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
533 } else if(op=='<=' || op=='≤') {
534 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
536 } else if(op=='>=' || op=='≥') {
537 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
540 // How to break out of a loop ?
541 alert("filter not supported");
549 _querytable_draw_callback: function()
552 * Handle clicks on checkboxes: reassociate checkbox click every time
553 * the table is redrawn
555 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
560 /* Remove pagination if we show only a few results */
561 var wrapper = this.table; //.parent().parent().parent();
562 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
563 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
564 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
566 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
567 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
569 $('.querytable_paginate', wrapper).css('visibility', 'visible');
572 if ( rowsToShow <= minRowsPerPage ) {
573 $('.querytable_length', wrapper).css('visibility', 'hidden');
575 $('.querytable_length', wrapper).css('visibility', 'visible');
579 _check_click: function(e)
586 // this.id = key of object to be added... what about multiple keys ?
587 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
588 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
589 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
593 _selectAll: function()
595 // requires jQuery id
596 var uuid=this.id.split("-");
597 var oTable=$("#querytable-"+uuid[1]).dataTable();
598 // Function available in QueryTable 1.9.x
599 // Filter : displayed data only
600 var filterData = oTable._('tr', {"filter":"applied"});
601 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
602 if(filterData.length<=100){
603 $.each(filterData, function(index, obj) {
604 var last=$(obj).last();
605 var key_value=unfold.get_value(last[0]);
606 if(typeof($(last[0]).attr('checked'))=="undefined"){
607 $.publish('selected', 'add/'+key_value);
615 $.plugin('QueryTable', QueryTable);
617 /* define the 'dom-checkbox' type for sorting in datatables
618 http://datatables.net/examples/plug-ins/dom_sort.html
619 using trial and error I found that the actual column number
620 was in fact given as a third argument, and not second
621 as the various online resources had it - go figure */
622 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
623 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
624 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';