2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
14 regex_filter="((packet)|(compute))";
16 var UnivbrisFoam = Plugin.extend({
18 init: function(options, element) {
19 //alert("foam init called");
20 this.classname="univbrisfoam";
21 this._super(options, element);
23 //alert(this.options.hidden_columns);
24 /* Member variables */
25 // in general we expect 2 queries here
26 // query_uuid refers to a single object (typically a slice)
27 // query_all_uuid refers to a list (typically resources or users)
28 // these can return in any order so we keep track of which has been received yet
29 this.received_all_query = false;
30 this.received_query = false;
32 // We need to remember the active filter for datatables filtering
33 this.filters = Array();
35 // an internal buffer for records that are 'in' and thus need to be checked
36 this.buffered_records_to_check = [];
37 // an internal buffer for keeping lines and display them in one call to fnAddData
38 this.buffered_lines = [];
41 // xx somehow non of these triggers at all for now
42 this.elmt().on('show', this, this.on_show);
43 this.elmt().on('shown.bs.tab', this, this.on_show);
44 this.elmt().on('resize', this, this.on_resize);
46 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
47 this.object = query.object;
49 //// we need 2 different keys
50 // * canonical_key is the primary key as derived from metadata (typically: urn)
51 // and is used to communicate about a given record with the other plugins
52 // * init_key is a key that both kinds of records
53 // (i.e. records returned by both queries) must have (typically: hrn or hostname)
54 // in general query_all will return well populated records, but query
55 // returns records with only the fields displayed on startup
56 var keys = manifold.metadata.get_key(this.object);
57 this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
59 this.init_key = this.options.init_key;
60 // have init_key default to canonical_key
61 this.init_key = this.init_key || this.canonical_key;
63 if ( ! this.init_key ) messages.warning ("UnivbrisFoam : cannot find init_key");
64 if ( ! this.canonical_key ) messages.warning ("UnivbrisFoam : cannot find canonical_key");
65 if (debug) messages.debug("UnivbrisFoam: canonical_key="+this.canonical_key+" init_key="+this.init_key);
66 /* Setup query and record handlers */
67 this.listen_query(options.query_uuid);
68 this.listen_query(options.query_all_uuid, 'all');
69 this.listen_query(options.sync_query_uuid,'sync');
71 /* GUI setup and event binding */
72 this.initialize_table();
74 jQuery( "#univbris_foam_ports_selection" ).hide();
80 on_show: function(e) {
81 if (debug) messages.debug("univbrisfoam.on_show");
83 self.table.fnAdjustColumnSizing();
86 on_resize: function(e) {
87 if (debug) messages.debug("univbrisfoam.on_resize");
89 self.table.fnAdjustColumnSizing();
94 /* GUI MANIPULATION */
96 initialize_table: function()
98 /* Transforms the table into DataTable, and keep a pointer to it */
101 var actual_options = {
102 // Customize the position of Datatables elements (length,filter,button,...)
103 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
104 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
105 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-5'p>>",
106 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
107 // hopefully this would come with dataTables v1.10 ?
108 // in any case, search for 'sPaginationType' all over the code for more comments
109 sPaginationType: 'bootstrap',
110 // Handle the null values & the error : Datatables warning Requested unknown parameter
111 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
112 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
113 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
114 // sScrollX: '100%', /* Horizontal scrolling */
115 bProcessing: true, /* Loading */
116 fnDrawCallback: function() { self._querytable_draw_callback.call(self);}
117 //fnFooterCallback: function() {self._univbrisfoam_footer_callback.call(self,nFoot, aData, iStart, iEnd, aiDisplay)};}
118 // XXX use $.proxy here !
120 // the intention here is that options.datatables_options as coming from the python object take precedence
121 // xxx DISABLED by jordan: was causing errors in datatables.js
122 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
123 // check your datatables_options tag instead
124 // however, we have to accumulate in aoColumnDefs from here (above)
125 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
126 if ( 'aoColumnDefs' in this.options.datatables_options) {
127 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
128 delete this.options.datatables_options['aoColumnDefs'];
130 $.extend(actual_options, this.options.datatables_options );
131 this.table = $("#univbris_foam_ports_selection__table").dataTable(actual_options);
133 //this.table = this.elmt("table").dataTable(actual_options);
136 /* Setup the SelectAll button in the dataTable header */
137 /* xxx not sure this is still working */
138 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
139 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
141 oSelectAll.css('font-size','11px');
142 oSelectAll.css('float','right');
143 oSelectAll.css('margin-right','15px');
144 oSelectAll.css('margin-bottom','5px');
145 oSelectAll.unbind('click');
146 oSelectAll.click(this._selectAll);
148 /* Add a filtering function to the current table
149 * Note: we use closure to get access to the 'options'
151 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
152 /* No filtering if the table does not match */
153 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
155 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
158 //alert(this.options.hidden_columns);
160 /* Processing hidden_columns */
161 $.each(this.options.hidden_columns, function(i, field) {
162 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
164 self.hide_column(field);
165 //self.hide_column(field);
168 //$('<button id="next" type="button" style="height: 50px; width: 300px" onclick="fnButnext()">select flowspace</button>').appendTo('div.next');
172 //$('<a href="http://localhost:8000/login/" id="next_link">next link</a>').appendTo('div.next');
173 //$("#univbris_flowspace_selection").style.display="none";
176 }, // initialize_table
179 fnButnext:function(e){
181 //var sData = this.table.$('input').serialize();
182 //var sData = $(this).closest('checkboxes__table').find('input').serialize();
183 //var sData = $("form").find('input').serialize();
184 //var element=this.table.$("id="'NEC A/80<->NEC B/1080'"");
185 //var element=this.table.$("[id='"+"NEC A/80<->NEC B/1080"+"']");
186 //var x = element.checked;
187 //var uuid=this.id.split("-");
188 //var oTable=$('checkboxes__table').dataTable();
189 //var oTable=$.fn.dataTable();
190 //this.elts("table").unbind('click').click(this, this.fnButnext);
191 //var sData = $('input', oTable.fnGetNodes()).serialize();
194 ///var self = e.data;
195 //self=self.options.query_uuid;
196 //var oTable=$("#querytable-"+self).dataTable();
197 //var sData = $('input', oTable.fnGetNodes()).serialize();
198 //e.stopPropagation();
199 //var oTable=$('#myTable').dataTable();
200 //var sData = $('input', $("#uob_form")).serialize();
201 //$("#univbris_flowspace_selection").style.visibility='visible';
202 var sData=$("#uob_form").find("input").serialize();
203 //alert("clicked: "+sData);
204 jQuery( "#univbris_flowspace_selection" ).show();
205 //$("#multi_flowpspace_ports_selected").append('<label><input type="checkbox" name="option[]" value="1" />chocolate</label>');
207 //$("form#uob_form :input[type=checkbox]").each(function(){
208 // var input = $(this); // This is the jquery object of the input, do what you will
209 // //alert("id: "+ input.attr('id') + " checked: "+ input.is(':checked'));
210 // if(input.is(':checked')==true){
211 // //alert("got true");
212 // $("#multi_flowpspace_ports_selected").append('<label><input type="checkbox" name="'+input.attr('id')+'" />'+input.attr('id')+'</label>');
216 jQuery( "#univbris_foam_ports_selection" ).hide();
217 //jQuery( "#univbris_flowspace_selection" ).hide();
219 //var url = "http://localhost:8000/login/";
220 //$(location).attr('href',url);
221 //window.location.href = "http://localhost:8000/login/"
222 //window.location.replace("http://localhost:8000/login/");
223 //UnivbrisFv(options,elements);
225 //$("#next_link").click();
232 * @brief Determine index of key in the table columns
236 getColIndex: function(key, cols) {
237 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
238 return (tabIndex.length > 0) ? tabIndex[0] : -1;
241 // create a checkbox <input> tag
242 // computes 'id' attribute from canonical_key
243 // computes 'init_id' from init_key for initialization phase
244 // no need to used convoluted ids with plugin-uuid or others, since
245 // we search using table.$ which looks only in this table
246 checkbox_html : function (record) {
248 // Prefix id with plugin_uuid
250 result += " class='univbrisfoam-checkbox'";
251 // compute id from canonical_key
252 var id = record[this.canonical_key]
253 // compute init_id form init_key
254 var init_id=record[this.init_key];
255 // set id - for retrieving from an id, or for posting events upon user's clicks
256 result += " id='"+record[this.canonical_key]+"'";
258 result += "init_id='" + init_id + "'";
260 result += " type='checkbox'";
261 result += " autocomplete='off'";
262 result += "></input>";
266 fnLinkClick:function(link){
267 //console.log("link has been clicked: ");
268 //console.log(link.target.id);
270 var svg_links = svg.selectAll(".link");
271 for(var i=0;i<svg_links[0].length;i++){
272 //console.log(svg_links[0][i].__data__.value);
273 if(svg_links[0][i].__data__.value==link.target.id){
274 //console.log("got clicked link in svg");
276 if(link.target.checked==true){
277 svg_links[0][i].style.stroke= 'black';
278 svg_links[0][i].style.strokeWidth= '5px';
281 svg_links[0][i].style.stroke= '#ccc';
282 svg_links[0][i].style.strokeWidth= '4px';
289 //console.log(svg_links);
292 fake_checkbox_html : function (record) {
293 //alert("fake fun called");
295 // Prefix id with plugin_uuid
297 //result += " class='univbrisfoam-checkbox'";
298 // set id - for retrieving from an id, or for posting events upon user's clicks
299 result += " id='"+ record +"'";
300 result += " name='"+ record +"'";
301 result += " class='checkboxlink'";
302 //result += " onclick=fnLinkClick(this)";
304 result += " init_id='" + record + "'";
306 result += " type='checkbox'";
307 result += " autocomplete='off'";
308 result += "></input>";
314 new_record: function(record)
317 var urn = record['urn'];
318 var pos = urn.search('link');
320 var link = urn.substring(pos+5);
321 pos = link.search("_");
322 var head_node=link.substring(0,pos);
323 link=link.substring(pos+1);
324 pos = link.search("_");
325 var head_port=link.substring(0,pos);
326 link=link.substring(pos+1);
327 pos = link.search("_");
328 var tail_node=link.substring(0,pos);
329 link=link.substring(pos+1);
333 var link_type="packet";
335 if (urn.search('opticalpacket')!=-1){
336 link_type='opticalpacket';
338 else if (urn.search('optical')!=-1){
341 else if (urn.search('compute')!=-1){
344 else if (urn.search('federation')!=-1){
345 link_type='federation';
349 pos = urn.search('ofam');
350 var testbed=urn.substring(pos+5);
351 testbed=testbed.substring(0, testbed.search('link')-1);
354 for(i=0;i<table_links.length;i++){
355 if((table_links[i].head_node==head_node && table_links[i].tail_node==tail_node && table_links[i].head_port==head_port && table_links[i].tail_port==tail_port) ||
356 (table_links[i].head_node==tail_node && table_links[i].tail_node==head_node && table_links[i].head_port==tail_port && table_links[i].tail_port==head_port)){
364 tmp_link['head_node']=head_node;
365 tmp_link['tail_node']=tail_node;
366 tmp_link['head_port']=head_port;
367 tmp_link['tail_port']=tail_port;
368 tmp_link['testbed']=testbed;
369 tmp_link['link_type']=link_type;
371 table_links.push(tmp_link);
379 process_records: function(link){
381 // this models a line in dataTables, each element in the line describes a cell
384 // go through table headers to get column names we want
385 // in order (we have temporarily hack some adjustments in names)
386 var cols = this.table.fnSettings().aoColumns;
387 var colnames = cols.map(function(x) {return x.sTitle})
388 var nb_col = cols.length;
389 /* if we've requested checkboxes, then forget about the checkbox column for now */
390 if (this.options.checkboxes) nb_col -= 1;
392 for (var j = 0; j < nb_col; j++) {
393 if (typeof colnames[j] == 'undefined') {
395 } else if (colnames[j] == 'testbed') {
396 line.push(link.testbed);
397 } else if (colnames[j] == 'head node id/port') {
398 line.push(link.head_node+"/"+link.head_port);
400 else if (colnames[j] == 'tail node id/port'){
401 line.push(link.tail_node+"/"+link.tail_port);
403 else if (colnames[j] == 'link type'){
404 line.push(link.link_type);
406 else if (colnames[j] == 'selected'){
408 line.push(this.fake_checkbox_html(link.urn));
413 // catch up with the last column if checkboxes were requested
414 if (this.options.checkboxes) {
415 // Use a key instead of hostname (hard coded...)
416 line.push(this.checkbox_html(record));
419 // adding an array in one call is *much* more efficient
420 // this.table.fnAddData(line);
421 this.buffered_lines.push(line);
424 clear_table: function()
426 this.table.fnClearTable();
429 redraw_table: function()
434 show_column: function(field)
436 var oSettings = this.table.fnSettings();
437 var cols = oSettings.aoColumns;
438 var index = this.getColIndex(field,cols);
440 this.table.fnSetColumnVis(index, true);
443 hide_column: function(field)
445 var oSettings = this.table.fnSettings();
446 var cols = oSettings.aoColumns;
447 var index = this.getColIndex(field,cols);
449 //alert(field + ": index: " + index );
451 //alert(field + ": hidden with index: " + index );
452 this.table.fnSetColumnVis(index, false);
455 // this is used at init-time, at which point only init_key can make sense
456 // (because the argument record, if it comes from query, might not have canonical_key set
457 set_checkbox_from_record: function (record, checked) {
458 if (checked === undefined) checked = true;
459 var init_id = record[this.init_key];
460 if (debug) messages.debug("univbrisfoam.set_checkbox_from_record, init_id="+init_id);
461 // using table.$ to search inside elements that are not visible
462 var element = this.table.$('[init_id="'+init_id+'"]');
463 element.attr('checked',checked);
466 // id relates to canonical_key
467 set_checkbox_from_data: function (id, checked) {
468 if (checked === undefined) checked = true;
469 if (debug) messages.debug("univbrisfoam.set_checkbox_from_data, id="+id);
470 // using table.$ to search inside elements that are not visible
471 var element = this.table.$("[id='"+id+"']");
472 element.attr('checked',checked);
475 /*************************** QUERY HANDLER ****************************/
477 on_filter_added: function(filter)
479 this.filters.push(filter);
483 on_filter_removed: function(filter)
485 // Remove corresponding filters
486 this.filters = $.grep(this.filters, function(x) {
492 on_filter_clear: function()
498 on_field_added: function(field)
500 this.show_column(field);
503 on_field_removed: function(field)
505 this.hide_column(field);
508 on_field_clear: function()
510 alert('UnivbrisFoam::clear_fields() not implemented');
514 /* sync query handler*/
516 on_sync_filter_added:function(filter)
518 //alert("sync query filter called");
520 this.on_filter_added(filter);
523 on_sync_filter_clear: function()
526 this.filters=Array();
533 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
534 /*************************** ALL QUERY HANDLER ****************************/
536 on_all_filter_added: function(filter)
542 on_all_filter_removed: function(filter)
548 on_all_filter_clear: function()
554 on_all_field_added: function(field)
556 this.show_column(field);
559 on_all_field_removed: function(field)
561 this.hide_column(field);
564 on_all_field_clear: function()
566 alert('UnivbrisFoam::clear_fields() not implemented');
570 /*************************** RECORD HANDLER ***************************/
572 on_new_record: function(record)
574 if (this.received_all_query) {
575 // if the 'all' query has been dealt with already we may turn on the checkbox
576 this.set_checkbox_from_record(record, true);
578 this.buffered_records_to_check.push(record);
582 on_clear_records: function()
586 // Could be the default in parent
587 on_query_in_progress: function()
592 on_query_done: function()
594 this.received_query = true;
595 // unspin once we have received both
596 if (this.received_all_query && this.received_query) this.unspin();
599 on_field_state_changed: function(data)
601 switch(data.request) {
602 case FIELD_REQUEST_ADD:
603 case FIELD_REQUEST_ADD_RESET:
604 this.set_checkbox_from_data(data.value, true);
606 case FIELD_REQUEST_REMOVE:
607 case FIELD_REQUEST_REMOVE_RESET:
608 this.set_checkbox_from_data(data.value, false);
615 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
617 on_all_field_state_changed: function(data)
619 switch(data.request) {
620 case FIELD_REQUEST_ADD:
621 case FIELD_REQUEST_ADD_RESET:
622 this.set_checkboxfrom_data(data.value, true);
624 case FIELD_REQUEST_REMOVE:
625 case FIELD_REQUEST_REMOVE_RESET:
626 this.set_checkbox_from_data(data.value, false);
633 on_all_new_record: function(record)
635 this.new_record(record);
638 on_all_clear_records: function()
644 on_all_query_in_progress: function()
648 }, // on_all_query_in_progress
650 on_all_query_done: function()
652 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
653 this.buffered_lines=[];
654 for(var i=0;i<table_links.length;i++){
655 this.process_records(table_links[i]);
657 this.table.fnAddData (this.buffered_lines);
658 this.buffered_lines=[];
659 //alert(regex_filter)
661 //this.table.column(3).search("packet",True,True).draw();
662 this.table.fnFilter(regex_filter,3,true);
669 // if we've already received the slice query, we have not been able to set
670 // checkboxes on the fly at that time (dom not yet created)
671 $.each(this.buffered_records_to_check, function(i, record) {
672 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
673 self.set_checkbox_from_record(record, true);
675 this.buffered_records_to_check = [];
677 this.received_all_query = true;
678 // unspin once we have received both
679 if (this.received_all_query && this.received_query) this.unspin();
681 }, // on_all_query_done
683 /************************** PRIVATE METHODS ***************************/
686 * @brief QueryTable filtering function
688 _querytable_filter: function(oSettings, aData, iDataIndex)
691 $.each (this.filters, function(index, filter) {
692 /* XXX How to manage checkbox ? */
695 var value = filter[2];
697 /* Determine index of key in the table columns */
698 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
700 /* Unknown key: no filtering */
701 if (typeof(col) == 'undefined')
704 col_value=unfold.get_value(aData[col]);
705 /* Test whether current filter is compatible with the column */
706 if (op == '=' || op == '==') {
707 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
709 }else if (op == '!=') {
710 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
713 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
716 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
718 } else if(op=='<=' || op=='≤') {
719 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
721 } else if(op=='>=' || op=='≥') {
722 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
725 // How to break out of a loop ?
726 alert("filter not supported");
734 _querytable_draw_callback: function()
737 * Handle clicks on checkboxes: reassociate checkbox click every time
738 * the table is redrawn
741 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
742 // this.elts("next").unbind('click').click(this, this.fnButnext);
743 $(".checkboxlink").unbind('click').click(this,this.fnLinkClick);
748 /* Remove pagination if we show only a few results */
749 var wrapper = this.table; //.parent().parent().parent();
750 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
751 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
752 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
754 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
755 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
757 $('.querytable_paginate', wrapper).css('visibility', 'visible');
760 if ( rowsToShow <= minRowsPerPage ) {
761 $('.querytable_length', wrapper).css('visibility', 'hidden');
763 $('.querytable_length', wrapper).css('visibility', 'visible');
770 _check_click: function(e)
777 // this.id = key of object to be added... what about multiple keys ?
778 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
779 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
780 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
784 _selectAll: function()
786 // requires jQuery id
787 var uuid=this.id.split("-");
788 var oTable=$("#querytable-"+uuid[1]).dataTable();
789 // Function available in QueryTable 1.9.x
790 // Filter : displayed data only
791 var filterData = oTable._('tr', {"filter":"applied"});
792 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
793 if(filterData.length<=100){
794 $.each(filterData, function(index, obj) {
795 var last=$(obj).last();
796 var key_value=unfold.get_value(last[0]);
797 if(typeof($(last[0]).attr('checked'))=="undefined"){
798 $.publish('selected', 'add/'+key_value);
806 $.plugin('UnivbrisFoam', UnivbrisFoam);
808 /* define the 'dom-checkbox' type for sorting in datatables
809 http://datatables.net/examples/plug-ins/dom_sort.html
810 using trial and error I found that the actual column number
811 was in fact given as a third argument, and not second
812 as the various online resources had it - go figure */
813 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
814 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
815 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
819 /*function fnLinkClick(link){
820 console.log("link has been clicked: ");