2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
12 var UnivbrisFv = Plugin.extend({
14 init: function(options, element) {
15 //alert("foam init called");
16 this.classname="univbrisfv";
17 this._super(options, element);
19 //alert(this.options.hidden_columns);
20 /* Member variables */
21 // in general we expect 2 queries here
22 // query_uuid refers to a single object (typically a slice)
23 // query_all_uuid refers to a list (typically resources or users)
24 // these can return in any order so we keep track of which has been received yet
25 //this.received_all_query = false;
26 //this.received_query = false;
28 // We need to remember the active filter for datatables filtering
29 this.filters = Array();
31 // an internal buffer for records that are 'in' and thus need to be checked
32 this.buffered_records_to_check = [];
33 // an internal buffer for keeping lines and display them in one call to fnAddData
34 this.buffered_lines = [];
37 // xx somehow non of these triggers at all for now
38 //this.elmt().on('show', this, this.on_show);
39 //this.elmt().on('shown.bs.tab', this, this.on_show);
40 //this.elmt().on('resize', this, this.on_resize);
42 //var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
43 //this.object = query.object;
45 //// we need 2 different keys
46 // * canonical_key is the primary key as derived from metadata (typically: urn)
47 // and is used to communicate about a given record with the other plugins
48 // * init_key is a key that both kinds of records
49 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
50 // in general query_all will return well populated records, but query
51 // returns records with only the fields displayed on startup
52 var keys = manifold.metadata.get_key(this.object);
53 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
55 this.init_key = this.options.init_key;
56 // have init_key default to canonical_key
57 this.init_key = this.init_key || this.canonical_key;
59 if ( ! this.init_key ) messages.warning ("UnivbrisFv : cannot find init_key");
60 if ( ! this.canonical_key ) messages.warning ("UnivbrisFv : cannot find canonical_key");
61 if (debug) messages.debug("UnivbrisFv: canonical_key="+this.canonical_key+" init_key="+this.init_key);
63 /* Setup query and record handlers */
64 //this.listen_query(options.query_uuid);
65 //this.listen_query(options.query_all_uuid, 'all');
67 /* GUI setup and event binding */
68 this.initialize_table();
74 on_show: function(e) {
75 if (debug) messages.debug("univbrisfv.on_show");
77 self.table.fnAdjustColumnSizing();
80 on_resize: function(e) {
81 if (debug) messages.debug("univbrisfv.on_resize");
83 self.table.fnAdjustColumnSizing();
88 /* GUI MANIPULATION */
90 initialize_table: function()
92 /* Transforms the table into DataTable, and keep a pointer to it */
94 var actual_options = {
95 // Customize the position of Datatables elements (length,filter,button,...)
96 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
97 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
98 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>><'buttons'>",
99 //sDom: "<'row'<'col-xs-9'r>t<'buttons'>",
100 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
101 // hopefully this would come with dataTables v1.10 ?
102 // in any case, search for 'sPaginationType' all over the code for more comments
103 sPaginationType: 'bootstrap',
104 // Handle the null values & the error : Datatables warning Requested unknown parameter
105 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
106 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
107 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
108 // sScrollX: '100%', /* Horizontal scrolling */
109 bProcessing: true, /* Loading */
110 fnDrawCallback: function() { self._querytable_draw_callback.call(self);}
111 //fnFooterCallback: function() {self._univbrisfv_footer_callback.call(self,nFoot, aData, iStart, iEnd, aiDisplay)};}
112 // XXX use $.proxy here !
114 // the intention here is that options.datatables_options as coming from the python object take precedence
115 // xxx DISABLED by jordan: was causing errors in datatables.js
116 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
117 // check your datatables_options tag instead
118 // however, we have to accumulate in aoColumnDefs from here (above)
119 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
120 if ( 'aoColumnDefs' in this.options.datatables_options) {
121 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
122 delete this.options.datatables_options['aoColumnDefs'];
124 $.extend(actual_options, this.options.datatables_options );
125 this.table = $("#univbris_flowspace_selection__table").dataTable(actual_options);
128 //alert(this.table.$("name"));
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 //alert(this.options.hidden_columns);
154 /* Processing hidden_columns */
155 $.each(this.options.hidden_columns, function(i, field) {
156 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
158 self.hide_column(field);
159 //self.hide_column(field);
162 //document.getElementById('buttons').text-align='center';
164 /**$('<table><tr><td><button id="add_flowspace" type="button" style="height: 25px; width: 400px; text-align: center" onclick="fnAddflowspace()">Define another packet flowspace</button></td>').appendTo('div.buttons');
166 $('<table><tr><td><button id="add_flowspace" type="button" style="height: 25px; width: 400px" onclick="fnAddflowspace()">Define another optical flowspace</button></td>').appendTo('div.buttons');
168 $('<td><button id="submit_flowspace" type="button" style="height: 25px; width: 400px" onclick="fnButsubmit()">Submit flowspaces</button></td></tr></table>').appendTo('div.buttons');
170 $('<td><button id="submit_flowspace" type="button" style="height: 25px; width: 400px" onclick="fnButsubmit()">Define controller location</button></td></tr></table>').appendTo('div.buttons');**/
173 jQuery( "#univbris_flowspace_selection" ).hide();
175 //$('<a href="http://localhost:8000/login/" id="next_link">next link</a>').appendTo('div.submit');
177 //this.new_record("t");
178 //this.new_record("t");
179 //this.new_record("t");
180 //this.new_record("t");
181 //this.new_record("t");
182 this._querytable_draw_callback();
186 }, // initialize_table
189 fnButsubmit:function(e){
190 alert("submitting flowspaces to AM (TO BE IMPLEMENTED)");
195 fnAddflowspace:function(e){
196 this.table = $("#univbris_flowspace_selection__table").dataTable();
197 //alert("table length" + this.table.fnGetNodes().length);
198 $("#flowspace_name").val("flowspace"+(this.table.fnGetNodes().length+1));
199 jQuery( "#univbris_flowspace_selection" ).hide();
200 jQuery("#uob_fv_table_form").show();
208 * @brief Determine index of key in the table columns
212 getColIndex: function(key, cols) {
213 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
214 return (tabIndex.length > 0) ? tabIndex[0] : -1;
217 // create a checkbox <input> tag
218 // computes 'id' attribute from canonical_key
219 // computes 'init_id' from init_key for initialization phase
220 // no need to used convoluted ids with plugin-uuid or others, since
221 // we search using table.$ which looks only in this table
222 checkbox_html : function (record) {
224 // Prefix id with plugin_uuid
226 result += " class='univbrisfv-checkbox'";
227 // compute id from canonical_key
228 var id = record[this.canonical_key]
229 // compute init_id form init_key
230 var init_id=record[this.init_key];
231 // set id - for retrieving from an id, or for posting events upon user's clicks
232 result += " id='"+record[this.canonical_key]+"'";
234 result += "init_id='" + init_id + "'";
236 result += " type='checkbox'";
237 result += " autocomplete='off'";
238 result += "></input>";
242 fake_checkbox_html : function (record) {
243 //alert("fake fun called");
245 // Prefix id with plugin_uuid
247 //result += " class='univbrisfv-checkbox'";
248 // set id - for retrieving from an id, or for posting events upon user's clicks
249 result += " id='"+ record +"'";
250 result += " name='"+ record +"'";
252 result += " init_id='" + record + "'";
254 result += " type='checkbox'";
255 result += " autocomplete='off'";
256 result += "></input>";
262 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.table.fnSettings().aoColumns;
271 var colnames = cols.map(function(x) {return 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;
277 /*replace production*/
278 /* fill in stuff depending on the column name */
279 var cols = this.table.fnSettings().aoColumns;
280 //alert("col "+cols);
281 var colnames = cols.map(function(x) {return x.sTitle})
282 var nb_col = cols.length;
283 //alert("nb_col: "+ nb_col);
284 /* if we've requested checkboxes, then forget about the checkbox column for now */
285 if (this.options.checkboxes) nb_col -= 1;
286 //alert("nb_col: "+ nb_col);
288 /*replace production*/
289 /* fill in stuff depending on the column name */
290 for (var j = 0; j < nb_col; j++) {
291 if (typeof colnames[j] == 'undefined') {
293 } else if (colnames[j] == 'Flowspace Selector') {
299 /*if (typeof colnames[j] == 'undefined') {
301 } else if (colnames[j] == 'hostname') {
302 if (record['type'] == 'resource,link')
303 //TODO: we need to add source/destination for links
306 line.push(record['hostname']);
308 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
309 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
311 if (record[colnames[j]])
312 line.push(record[colnames[j]]);
318 // catch up with the last column if checkboxes were requested
319 if (this.options.checkboxes) {
320 // Use a key instead of hostname (hard coded...)
321 line.push(this.checkbox_html(record));
324 // adding an array in one call is *much* more efficient
325 // this.table.fnAddData(line);
326 this.buffered_lines.push(line);
327 this.table.fnAddData(this.buffered_lines);
328 //this.table.redraw();
329 //this._querytable_draw_callback();
332 clear_table: function()
334 this.table.fnClearTable();
337 redraw_table: function()
342 show_column: function(field)
344 var oSettings = this.table.fnSettings();
345 var cols = oSettings.aoColumns;
346 var index = this.getColIndex(field,cols);
348 this.table.fnSetColumnVis(index, true);
351 hide_column: function(field)
353 var oSettings = this.table.fnSettings();
354 var cols = oSettings.aoColumns;
355 var index = this.getColIndex(field,cols);
357 //alert(field + ": index: " + index );
359 //alert(field + ": hidden with index: " + index );
360 this.table.fnSetColumnVis(index, false);
363 // this is used at init-time, at which point only init_key can make sense
364 // (because the argument record, if it comes from query, might not have canonical_key set
365 set_checkbox_from_record: function (record, checked) {
366 if (checked === undefined) checked = true;
367 var init_id = record[this.init_key];
368 if (debug) messages.debug("univbrisfv.set_checkbox_from_record, init_id="+init_id);
369 // using table.$ to search inside elements that are not visible
370 var element = this.table.$('[init_id="'+init_id+'"]');
371 element.attr('checked',checked);
374 // id relates to canonical_key
375 set_checkbox_from_data: function (id, checked) {
376 if (checked === undefined) checked = true;
377 if (debug) messages.debug("univbrisfv.set_checkbox_from_data, id="+id);
378 // using table.$ to search inside elements that are not visible
379 var element = this.table.$("[id='"+id+"']");
380 element.attr('checked',checked);
383 /*************************** QUERY HANDLER ****************************/
385 on_filter_added: function(filter)
387 this.filters.push(filter);
391 on_filter_removed: function(filter)
393 // Remove corresponding filters
394 this.filters = $.grep(this.filters, function(x) {
400 on_filter_clear: function()
406 on_field_added: function(field)
408 this.show_column(field);
411 on_field_removed: function(field)
413 this.hide_column(field);
416 on_field_clear: function()
418 alert('UnivbrisFv::clear_fields() not implemented');
421 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
422 /*************************** ALL QUERY HANDLER ****************************/
424 on_all_filter_added: function(filter)
430 on_all_filter_removed: function(filter)
436 on_all_filter_clear: function()
442 on_all_field_added: function(field)
444 this.show_column(field);
447 on_all_field_removed: function(field)
449 this.hide_column(field);
452 on_all_field_clear: function()
454 alert('UnivbrisFv::clear_fields() not implemented');
458 /*************************** RECORD HANDLER ***************************/
460 on_new_record: function(record)
462 if (this.received_all_query) {
463 // if the 'all' query has been dealt with already we may turn on the checkbox
464 this.set_checkbox_from_record(record, true);
466 this.buffered_records_to_check.push(record);
470 on_clear_records: function()
474 // Could be the default in parent
475 on_query_in_progress: function()
480 on_query_done: function()
482 this.received_query = true;
483 // unspin once we have received both
484 if (this.received_all_query && this.received_query) this.unspin();
487 on_field_state_changed: function(data)
489 switch(data.request) {
490 case FIELD_REQUEST_ADD:
491 case FIELD_REQUEST_ADD_RESET:
492 this.set_checkbox_from_data(data.value, true);
494 case FIELD_REQUEST_REMOVE:
495 case FIELD_REQUEST_REMOVE_RESET:
496 this.set_checkbox_from_data(data.value, false);
503 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
505 on_all_field_state_changed: function(data)
507 switch(data.request) {
508 case FIELD_REQUEST_ADD:
509 case FIELD_REQUEST_ADD_RESET:
510 this.set_checkboxfrom_data(data.value, true);
512 case FIELD_REQUEST_REMOVE:
513 case FIELD_REQUEST_REMOVE_RESET:
514 this.set_checkbox_from_data(data.value, false);
521 on_all_new_record: function(record)
523 this.new_record(record);
526 on_all_clear_records: function()
532 on_all_query_in_progress: function()
536 }, // on_all_query_in_progress
538 on_all_query_done: function()
540 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
541 this.table.fnAddData (this.buffered_lines);
542 this.buffered_lines=[];
545 // if we've already received the slice query, we have not been able to set
546 // checkboxes on the fly at that time (dom not yet created)
547 $.each(this.buffered_records_to_check, function(i, record) {
548 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
549 self.set_checkbox_from_record(record, true);
551 this.buffered_records_to_check = [];
553 this.received_all_query = true;
554 // unspin once we have received both
555 if (this.received_all_query && this.received_query) this.unspin();
557 }, // on_all_query_done
559 /************************** PRIVATE METHODS ***************************/
562 * @brief QueryTable filtering function
564 _querytable_filter: function(oSettings, aData, iDataIndex)
567 $.each (this.filters, function(index, filter) {
568 /* XXX How to manage checkbox ? */
571 var value = filter[2];
573 /* Determine index of key in the table columns */
574 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
576 /* Unknown key: no filtering */
577 if (typeof(col) == 'undefined')
580 col_value=unfold.get_value(aData[col]);
581 /* Test whether current filter is compatible with the column */
582 if (op == '=' || op == '==') {
583 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
585 }else if (op == '!=') {
586 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
589 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
592 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
594 } else if(op=='<=' || op=='≤') {
595 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
597 } else if(op=='>=' || op=='≥') {
598 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
601 // How to break out of a loop ?
602 alert("filter not supported");
610 _querytable_draw_callback: function()
613 * Handle clicks on checkboxes: reassociate checkbox click every time
614 * the table is redrawn
616 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
617 $("#submit_flowspace").unbind('click').click(this, this.fnButsubmit);
618 $("#add_flowspace").unbind('click').click(this, this.fnAddflowspace);
623 /* Remove pagination if we show only a few results */
624 var wrapper = this.table; //.parent().parent().parent();
625 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
626 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
627 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
629 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
630 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
632 $('.querytable_paginate', wrapper).css('visibility', 'visible');
635 if ( rowsToShow <= minRowsPerPage ) {
636 $('.querytable_length', wrapper).css('visibility', 'hidden');
638 $('.querytable_length', wrapper).css('visibility', 'visible');
645 _check_click: function(e)
652 // this.id = key of object to be added... what about multiple keys ?
653 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
654 //manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
655 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
659 _selectAll: function()
661 // requires jQuery id
662 var uuid=this.id.split("-");
663 var oTable=$("#querytable-"+uuid[1]).dataTable();
664 // Function available in QueryTable 1.9.x
665 // Filter : displayed data only
666 var filterData = oTable._('tr', {"filter":"applied"});
667 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
668 if(filterData.length<=100){
669 $.each(filterData, function(index, obj) {
670 var last=$(obj).last();
671 var key_value=unfold.get_value(last[0]);
672 if(typeof($(last[0]).attr('checked'))=="undefined"){
673 $.publish('selected', 'add/'+key_value);
681 $.plugin('UnivbrisFv', UnivbrisFv);
683 /* define the 'dom-checkbox' type for sorting in datatables
684 http://datatables.net/examples/plug-ins/dom_sort.html
685 using trial and error I found that the actual column number
686 was in fact given as a third argument, and not second
687 as the various online resources had it - go figure */
688 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
689 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
690 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';