2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
12 var UnivbrisFoam = Plugin.extend({
14 init: function(options, element) {
15 //alert("foam init called");
16 this.classname="univbrisfoam";
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 ("UnivbrisFoam : cannot find init_key");
60 if ( ! this.canonical_key ) messages.warning ("UnivbrisFoam : cannot find canonical_key");
61 if (debug) messages.debug("UnivbrisFoam: canonical_key="+this.canonical_key+" init_key="+this.init_key);
62 /* Setup query and record handlers */
63 this.listen_query(options.query_uuid);
64 this.listen_query(options.query_all_uuid, 'all');
66 /* GUI setup and event binding */
67 this.initialize_table();
73 on_show: function(e) {
74 if (debug) messages.debug("univbrisfoam.on_show");
76 self.table.fnAdjustColumnSizing();
79 on_resize: function(e) {
80 if (debug) messages.debug("univbrisfoam.on_resize");
82 self.table.fnAdjustColumnSizing();
87 /* GUI MANIPULATION */
89 initialize_table: function()
91 /* 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-2'l><'col-xs-9'r><'col-xs-2'f>>t<'row'<'col-xs-5'i><'col-xs-5'p>><'next'>",
99 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
100 // hopefully this would come with dataTables v1.10 ?
101 // in any case, search for 'sPaginationType' all over the code for more comments
102 sPaginationType: 'bootstrap',
103 // Handle the null values & the error : Datatables warning Requested unknown parameter
104 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
105 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
106 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
107 // sScrollX: '100%', /* Horizontal scrolling */
108 bProcessing: true, /* Loading */
109 fnDrawCallback: function() { self._querytable_draw_callback.call(self);}
110 //fnFooterCallback: function() {self._univbrisfoam_footer_callback.call(self,nFoot, aData, iStart, iEnd, aiDisplay)};}
111 // XXX use $.proxy here !
113 // the intention here is that options.datatables_options as coming from the python object take precedence
114 // xxx DISABLED by jordan: was causing errors in datatables.js
115 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
116 // check your datatables_options tag instead
117 // however, we have to accumulate in aoColumnDefs from here (above)
118 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
119 if ( 'aoColumnDefs' in this.options.datatables_options) {
120 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
121 delete this.options.datatables_options['aoColumnDefs'];
123 $.extend(actual_options, this.options.datatables_options );
124 this.table = $("#univbris_foam_ports_selection__table").dataTable(actual_options);
126 //this.table = this.elmt("table").dataTable(actual_options);
129 /* Setup the SelectAll button in the dataTable header */
130 /* xxx not sure this is still working */
131 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
132 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
134 oSelectAll.css('font-size','11px');
135 oSelectAll.css('float','right');
136 oSelectAll.css('margin-right','15px');
137 oSelectAll.css('margin-bottom','5px');
138 oSelectAll.unbind('click');
139 oSelectAll.click(this._selectAll);
141 /* Add a filtering function to the current table
142 * Note: we use closure to get access to the 'options'
144 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
145 /* No filtering if the table does not match */
146 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
148 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
151 //alert(this.options.hidden_columns);
153 /* Processing hidden_columns */
154 $.each(this.options.hidden_columns, function(i, field) {
155 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
157 self.hide_column(field);
158 //self.hide_column(field);
161 $('<button id="next" type="button" style="height: 50px; width: 300px" onclick="fnButnext()">select flowspace</button>').appendTo('div.next');
165 //$('<a href="http://localhost:8000/login/" id="next_link">next link</a>').appendTo('div.next');
166 //$("#univbris_flowspace_selection").style.display="none";
169 }, // initialize_table
172 fnButnext:function(e){
174 //var sData = this.table.$('input').serialize();
175 //var sData = $(this).closest('checkboxes__table').find('input').serialize();
176 //var sData = $("form").find('input').serialize();
177 //var element=this.table.$("id="'NEC A/80<->NEC B/1080'"");
178 //var element=this.table.$("[id='"+"NEC A/80<->NEC B/1080"+"']");
179 //var x = element.checked;
180 //var uuid=this.id.split("-");
181 //var oTable=$('checkboxes__table').dataTable();
182 //var oTable=$.fn.dataTable();
183 //this.elts("table").unbind('click').click(this, this.fnButnext);
184 //var sData = $('input', oTable.fnGetNodes()).serialize();
187 ///var self = e.data;
188 //self=self.options.query_uuid;
189 //var oTable=$("#querytable-"+self).dataTable();
190 //var sData = $('input', oTable.fnGetNodes()).serialize();
191 //e.stopPropagation();
192 //var oTable=$('#myTable').dataTable();
193 //var sData = $('input', $("#uob_form")).serialize();
194 //$("#univbris_flowspace_selection").style.visibility='visible';
195 var sData=$("#uob_form").find("input").serialize();
196 //alert("clicked: "+sData);
197 jQuery( "#univbris_flowspace_selection" ).show();
198 //$("#multi_flowpspace_ports_selected").append('<label><input type="checkbox" name="option[]" value="1" />chocolate</label>');
200 $("form#uob_form :input[type=checkbox]").each(function(){
201 var input = $(this); // This is the jquery object of the input, do what you will
202 //alert("id: "+ input.attr('id') + " checked: "+ input.is(':checked'));
203 if(input.is(':checked')==true){
205 $("#multi_flowpspace_ports_selected").append('<label><input type="checkbox" name="'+input.attr('id')+'" />'+input.attr('id')+'</label>');
209 jQuery( "#univbris_foam_ports_selection" ).hide();
210 //jQuery( "#univbris_flowspace_selection" ).hide();
212 //var url = "http://localhost:8000/login/";
213 //$(location).attr('href',url);
214 //window.location.href = "http://localhost:8000/login/"
215 //window.location.replace("http://localhost:8000/login/");
216 //UnivbrisFv(options,elements);
218 //$("#next_link").click();
225 * @brief Determine index of key in the table columns
229 getColIndex: function(key, cols) {
230 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
231 return (tabIndex.length > 0) ? tabIndex[0] : -1;
234 // create a checkbox <input> tag
235 // computes 'id' attribute from canonical_key
236 // computes 'init_id' from init_key for initialization phase
237 // no need to used convoluted ids with plugin-uuid or others, since
238 // we search using table.$ which looks only in this table
239 checkbox_html : function (record) {
241 // Prefix id with plugin_uuid
243 result += " class='univbrisfoam-checkbox'";
244 // compute id from canonical_key
245 var id = record[this.canonical_key]
246 // compute init_id form init_key
247 var init_id=record[this.init_key];
248 // set id - for retrieving from an id, or for posting events upon user's clicks
249 result += " id='"+record[this.canonical_key]+"'";
251 result += "init_id='" + init_id + "'";
253 result += " type='checkbox'";
254 result += " autocomplete='off'";
255 result += "></input>";
259 fake_checkbox_html : function (record) {
260 //alert("fake fun called");
262 // Prefix id with plugin_uuid
264 //result += " class='univbrisfoam-checkbox'";
265 // set id - for retrieving from an id, or for posting events upon user's clicks
266 result += " id='"+ record +"'";
267 result += " name='"+ record +"'";
269 result += " init_id='" + record + "'";
271 result += " type='checkbox'";
272 result += " autocomplete='off'";
273 result += "></input>";
279 new_record: function(record)
282 // this models a line in dataTables, each element in the line describes a cell
285 // go through table headers to get column names we want
286 // in order (we have temporarily hack some adjustments in names)
287 var cols = this.table.fnSettings().aoColumns;
288 var colnames = cols.map(function(x) {return x.sTitle})
289 var nb_col = cols.length;
290 /* if we've requested checkboxes, then forget about the checkbox column for now */
291 if (this.options.checkboxes) nb_col -= 1;
294 var urn = record['urn'];
296 var pos = urn.search('link');
297 //filter records to add links only
300 var link = urn.substring(pos+5);
301 pos = link.search("_");
302 var head_node=link.substring(0,pos);
303 link=link.substring(pos+1);
304 pos = link.search("_");
305 var head_port=link.substring(0,pos);
306 link=link.substring(pos+1);
307 pos = link.search("_");
308 var tail_node=link.substring(0,pos);
309 link=link.substring(pos+1);
310 //pos = link.search("_");
314 //var head_node=urn.substring(pos+5,pos+28);
315 //var head_port=urn.substring(pos+29,pos+31);
316 //var tail_node=urn.substring(pos+32,pos+55);
317 //var tail_port=urn.substring(pos+56,pos+58);
319 //link type int 0-packet, 1-optical, 2-compute
321 if (urn.search('circuit')!=-1){
324 else if (urn.search('compute')!=-1){
329 pos = urn.search('ofam');
330 var testbed=urn.substring(pos+5);
331 testbed=testbed.substring(0, testbed.search('link')-1);
335 //alert("h: "+head_node+"/"+head_port);
336 //alert("t: "+tail_node+"/"+tail_port);
340 /*replace production*/
341 /* fill in stuff depending on the column name */
342 for (var j = 0; j < nb_col; j++) {
343 if (typeof colnames[j] == 'undefined') {
345 } else if (colnames[j] == 'testbed') {
347 } else if (colnames[j] == 'head node id/port') {
348 line.push(head_node+"/"+head_port);
350 else if (colnames[j] == 'tail node id/port'){
351 line.push(tail_node+"/"+tail_port);
353 else if (colnames[j] == 'link type'){
360 line.push("optical");
364 line.push("compute");
368 else if (colnames[j] == 'selected'){
370 line.push(this.fake_checkbox_html(urn));
376 // catch up with the last column if checkboxes were requested
377 if (this.options.checkboxes) {
378 // Use a key instead of hostname (hard coded...)
379 line.push(this.checkbox_html(record));
382 // adding an array in one call is *much* more efficient
383 // this.table.fnAddData(line);
384 this.buffered_lines.push(line);
389 clear_table: function()
391 this.table.fnClearTable();
394 redraw_table: function()
399 show_column: function(field)
401 var oSettings = this.table.fnSettings();
402 var cols = oSettings.aoColumns;
403 var index = this.getColIndex(field,cols);
405 this.table.fnSetColumnVis(index, true);
408 hide_column: function(field)
410 var oSettings = this.table.fnSettings();
411 var cols = oSettings.aoColumns;
412 var index = this.getColIndex(field,cols);
414 //alert(field + ": index: " + index );
416 //alert(field + ": hidden with index: " + index );
417 this.table.fnSetColumnVis(index, false);
420 // this is used at init-time, at which point only init_key can make sense
421 // (because the argument record, if it comes from query, might not have canonical_key set
422 set_checkbox_from_record: function (record, checked) {
423 if (checked === undefined) checked = true;
424 var init_id = record[this.init_key];
425 if (debug) messages.debug("univbrisfoam.set_checkbox_from_record, init_id="+init_id);
426 // using table.$ to search inside elements that are not visible
427 var element = this.table.$('[init_id="'+init_id+'"]');
428 element.attr('checked',checked);
431 // id relates to canonical_key
432 set_checkbox_from_data: function (id, checked) {
433 if (checked === undefined) checked = true;
434 if (debug) messages.debug("univbrisfoam.set_checkbox_from_data, id="+id);
435 // using table.$ to search inside elements that are not visible
436 var element = this.table.$("[id='"+id+"']");
437 element.attr('checked',checked);
440 /*************************** QUERY HANDLER ****************************/
442 on_filter_added: function(filter)
444 this.filters.push(filter);
448 on_filter_removed: function(filter)
450 // Remove corresponding filters
451 this.filters = $.grep(this.filters, function(x) {
457 on_filter_clear: function()
463 on_field_added: function(field)
465 this.show_column(field);
468 on_field_removed: function(field)
470 this.hide_column(field);
473 on_field_clear: function()
475 alert('UnivbrisFoam::clear_fields() not implemented');
478 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
479 /*************************** ALL QUERY HANDLER ****************************/
481 on_all_filter_added: function(filter)
487 on_all_filter_removed: function(filter)
493 on_all_filter_clear: function()
499 on_all_field_added: function(field)
501 this.show_column(field);
504 on_all_field_removed: function(field)
506 this.hide_column(field);
509 on_all_field_clear: function()
511 alert('UnivbrisFoam::clear_fields() not implemented');
515 /*************************** RECORD HANDLER ***************************/
517 on_new_record: function(record)
519 if (this.received_all_query) {
520 // if the 'all' query has been dealt with already we may turn on the checkbox
521 this.set_checkbox_from_record(record, true);
523 this.buffered_records_to_check.push(record);
527 on_clear_records: function()
531 // Could be the default in parent
532 on_query_in_progress: function()
537 on_query_done: function()
539 this.received_query = true;
540 // unspin once we have received both
541 if (this.received_all_query && this.received_query) this.unspin();
544 on_field_state_changed: function(data)
546 switch(data.request) {
547 case FIELD_REQUEST_ADD:
548 case FIELD_REQUEST_ADD_RESET:
549 this.set_checkbox_from_data(data.value, true);
551 case FIELD_REQUEST_REMOVE:
552 case FIELD_REQUEST_REMOVE_RESET:
553 this.set_checkbox_from_data(data.value, false);
560 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
562 on_all_field_state_changed: function(data)
564 switch(data.request) {
565 case FIELD_REQUEST_ADD:
566 case FIELD_REQUEST_ADD_RESET:
567 this.set_checkboxfrom_data(data.value, true);
569 case FIELD_REQUEST_REMOVE:
570 case FIELD_REQUEST_REMOVE_RESET:
571 this.set_checkbox_from_data(data.value, false);
578 on_all_new_record: function(record)
580 this.new_record(record);
583 on_all_clear_records: function()
589 on_all_query_in_progress: function()
593 }, // on_all_query_in_progress
595 on_all_query_done: function()
597 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
598 this.table.fnAddData (this.buffered_lines);
599 this.buffered_lines=[];
602 // if we've already received the slice query, we have not been able to set
603 // checkboxes on the fly at that time (dom not yet created)
604 $.each(this.buffered_records_to_check, function(i, record) {
605 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
606 self.set_checkbox_from_record(record, true);
608 this.buffered_records_to_check = [];
610 this.received_all_query = true;
611 // unspin once we have received both
612 if (this.received_all_query && this.received_query) this.unspin();
614 }, // on_all_query_done
616 /************************** PRIVATE METHODS ***************************/
619 * @brief QueryTable filtering function
621 _querytable_filter: function(oSettings, aData, iDataIndex)
624 $.each (this.filters, function(index, filter) {
625 /* XXX How to manage checkbox ? */
628 var value = filter[2];
630 /* Determine index of key in the table columns */
631 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
633 /* Unknown key: no filtering */
634 if (typeof(col) == 'undefined')
637 col_value=unfold.get_value(aData[col]);
638 /* Test whether current filter is compatible with the column */
639 if (op == '=' || op == '==') {
640 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
642 }else if (op == '!=') {
643 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
646 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
649 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
651 } else if(op=='<=' || op=='≤') {
652 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
654 } else if(op=='>=' || op=='≥') {
655 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
658 // How to break out of a loop ?
659 alert("filter not supported");
667 _querytable_draw_callback: function()
670 * Handle clicks on checkboxes: reassociate checkbox click every time
671 * the table is redrawn
673 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
674 this.elts("next").unbind('click').click(this, this.fnButnext);
680 /* Remove pagination if we show only a few results */
681 var wrapper = this.table; //.parent().parent().parent();
682 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
683 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
684 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
686 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
687 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
689 $('.querytable_paginate', wrapper).css('visibility', 'visible');
692 if ( rowsToShow <= minRowsPerPage ) {
693 $('.querytable_length', wrapper).css('visibility', 'hidden');
695 $('.querytable_length', wrapper).css('visibility', 'visible');
702 _check_click: function(e)
709 // this.id = key of object to be added... what about multiple keys ?
710 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
711 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
712 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
716 _selectAll: function()
718 // requires jQuery id
719 var uuid=this.id.split("-");
720 var oTable=$("#querytable-"+uuid[1]).dataTable();
721 // Function available in QueryTable 1.9.x
722 // Filter : displayed data only
723 var filterData = oTable._('tr', {"filter":"applied"});
724 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
725 if(filterData.length<=100){
726 $.each(filterData, function(index, obj) {
727 var last=$(obj).last();
728 var key_value=unfold.get_value(last[0]);
729 if(typeof($(last[0]).attr('checked'))=="undefined"){
730 $.publish('selected', 'add/'+key_value);
738 $.plugin('UnivbrisFoam', UnivbrisFoam);
740 /* define the 'dom-checkbox' type for sorting in datatables
741 http://datatables.net/examples/plug-ins/dom_sort.html
742 using trial and error I found that the actual column number
743 was in fact given as a third argument, and not second
744 as the various online resources had it - go figure */
745 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
746 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
747 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';