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("fv 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 = True;
26 //this.received_query = True;
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;
54 //alert("after super");
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 //alert("fv init called");
69 this.initialize_table();
75 on_show: function(e) {
76 if (debug) messages.debug("univbrisfv.on_show");
78 self.table.fnAdjustColumnSizing();
81 on_resize: function(e) {
82 if (debug) messages.debug("univbrisfv.on_resize");
84 self.table.fnAdjustColumnSizing();
89 /* GUI MANIPULATION */
91 initialize_table: function()
93 alert("init table fnc");
94 /* Transforms the table into DataTable, and keep a pointer to it */
96 var actual_options = {
97 // Customize the position of Datatables elements (length,filter,button,...)
98 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
99 //sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
100 sDom: "<'row'<'col-xs-9'r>t<'next'>",
101 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
102 // hopefully this would come with dataTables v1.10 ?
103 // in any case, search for 'sPaginationType' all over the code for more comments
104 sPaginationType: 'bootstrap',
105 // Handle the null values & the error : Datatables warning Requested unknown parameter
106 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
107 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
108 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
109 // sScrollX: '100%', /* Horizontal scrolling */
110 bProcessing: true, /* Loading */
111 fnDrawCallback: function() { self._querytable_draw_callback.call(self);}
112 //fnFooterCallback: function() {self._univbrisfv_footer_callback.call(self,nFoot, aData, iStart, iEnd, aiDisplay)};}
113 // XXX use $.proxy here !
115 // the intention here is that options.datatables_options as coming from the python object take precedence
116 // xxx DISABLED by jordan: was causing errors in datatables.js
117 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
118 // check your datatables_options tag instead
119 // however, we have to accumulate in aoColumnDefs from here (above)
120 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
121 /*if ( 'aoColumnDefs' in this.options.datatables_options) {
122 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
123 delete this.options.datatables_options['aoColumnDefs'];
125 //this.redraw_table();
128 $.extend(actual_options, this.options.datatables_options );
129 this.table = $('#univbris_flowspace_selection__table').dataTable(actual_options);
133 /* Setup the SelectAll button in the dataTable header */
134 /* xxx not sure this is still working */
135 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
136 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
138 oSelectAll.css('font-size','11px');
139 oSelectAll.css('float','right');
140 oSelectAll.css('margin-right','15px');
141 oSelectAll.css('margin-bottom','5px');
142 oSelectAll.unbind('click');
143 oSelectAll.click(this._selectAll);
145 /* Add a filtering function to the current table
146 * Note: we use closure to get access to the 'options'
148 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
149 /* No filtering if the table does not match */
150 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
152 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
155 //alert(this.options.hidden_columns);
157 /* Processing hidden_columns */
158 $.each(this.options.hidden_columns, function(i, field) {
159 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
161 self.hide_column(field);
162 //self.hide_column(field);
165 $('<button id="next" type="submit" style="height: 50px; width: 300px" onclick="fnButnext()">select flowspace</button>').appendTo('div.next');
167 $('<a href="http://localhost:8000/login/" id="next_link">next link</a>').appendTo('div.next');
168 alert("before record");
169 //this.redraw_table();
170 this.new_record("test");
171 this._querytable_draw_callback();
173 alert("after record");
177 }, // initialize_table
180 fnButnext:function(e){
182 //var sData = this.table.$('input').serialize();
183 //var sData = $(this).closest('checkboxes__table').find('input').serialize();
184 //var sData = $("form").find('input').serialize();
185 //var element=this.table.$("id="'NEC A/80<->NEC B/1080'"");
186 //var element=this.table.$("[id='"+"NEC A/80<->NEC B/1080"+"']");
187 //var x = element.checked;
188 //var uuid=this.id.split("-");
189 //var oTable=$('checkboxes__table').dataTable();
190 //var oTable=$.fn.dataTable();
191 //this.elts("table").unbind('click').click(this, this.fnButnext);
192 //var sData = $('input', oTable.fnGetNodes()).serialize();
195 ///var self = e.data;
196 //self=self.options.query_uuid;
197 //var oTable=$("#querytable-"+self).dataTable();
198 //var sData = $('input', oTable.fnGetNodes()).serialize();
199 //e.stopPropagation();
200 //var oTable=$('#myTable').dataTable();
201 //var sData = $('input', $("#uob_form")).serialize();
202 var sData=$("#uob_form").find("input").serialize();
203 //alert("clicked: "+sData);
205 //var url = "http://localhost:8000/login/";
206 //$(location).attr('href',url);
207 //window.location.href = "http://localhost:8000/login/"
208 //window.location.replace("http://localhost:8000/login/");
209 //UnivbrisFv(options,elements);
211 //$("#next_link").click();
218 * @brief Determine index of key in the table columns
222 getColIndex: function(key, cols) {
223 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
224 return (tabIndex.length > 0) ? tabIndex[0] : -1;
227 // create a checkbox <input> tag
228 // computes 'id' attribute from canonical_key
229 // computes 'init_id' from init_key for initialization phase
230 // no need to used convoluted ids with plugin-uuid or others, since
231 // we search using table.$ which looks only in this table
232 checkbox_html : function (record) {
234 // Prefix id with plugin_uuid
236 result += " class='univbrisfv-checkbox'";
237 // compute id from canonical_key
238 var id = record[this.canonical_key]
239 // compute init_id form init_key
240 var init_id=record[this.init_key];
241 // set id - for retrieving from an id, or for posting events upon user's clicks
242 result += " id='"+record[this.canonical_key]+"'";
244 result += "init_id='" + init_id + "'";
246 result += " type='checkbox'";
247 result += " autocomplete='off'";
248 result += "></input>";
252 fake_checkbox_html : function (record) {
253 //alert("fake fun called");
255 // Prefix id with plugin_uuid
257 //result += " class='univbrisfv-checkbox'";
258 // set id - for retrieving from an id, or for posting events upon user's clicks
259 result += " id='"+ record +"'";
260 result += " name='"+ record +"'";
262 result += " init_id='" + record + "'";
264 result += " type='checkbox'";
265 result += " autocomplete='off'";
266 result += "></input>";
272 new_record: function(record)
275 // this models a line in dataTables, each element in the line describes a cell
276 // alert("nb_col: ");
279 // go through table headers to get column names we want
280 // in order (we have temporarily hack some adjustments in names)
282 var cols = this.table.fnSettings().aoColumns;
284 var colnames = cols.map(function(x) {return x.sTitle})
285 var nb_col = cols.length;
286 alert("nb_col: "+ nb_col);
287 /* if we've requested checkboxes, then forget about the checkbox column for now */
288 if (this.options.checkboxes) nb_col -= 1;
289 alert("nb_col: "+ nb_col);
291 /*replace production*/
292 /* fill in stuff depending on the column name */
293 for (var j = 0; j < nb_col; j++) {
294 if (typeof colnames[j] == 'undefined') {
296 } else if (colnames[j] == 'Flowspace Selector') {
298 line.push("first form");
303 /*if (typeof colnames[j] == 'undefined') {
305 } else if (colnames[j] == 'hostname') {
306 if (record['type'] == 'resource,link')
307 //TODO: we need to add source/destination for links
310 line.push(record['hostname']);
312 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
313 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
315 if (record[colnames[j]])
316 line.push(record[colnames[j]]);
322 // catch up with the last column if checkboxes were requested
323 if (this.options.checkboxes) {
324 // Use a key instead of hostname (hard coded...)
325 line.push(this.checkbox_html(record));
328 // adding an array in one call is *much* more efficient
329 alert("sending to table");
330 $('#univbris_flowspace_selection__table').dataTable().fnAddData(['test']);
331 //$('#univbris_flowspace_selection__table').dataTable().fnDraw();
332 this._querytable_draw_callback();
333 alert("sent to table");
334 //this.buffered_lines.push(line);
337 clear_table: function()
339 this.table.fnClearTable();
342 redraw_table: function()
347 show_column: function(field)
349 var oSettings = this.table.fnSettings();
350 var cols = oSettings.aoColumns;
351 var index = this.getColIndex(field,cols);
353 this.table.fnSetColumnVis(index, true);
356 hide_column: function(field)
358 var oSettings = this.table.fnSettings();
359 var cols = oSettings.aoColumns;
360 var index = this.getColIndex(field,cols);
362 //alert(field + ": index: " + index );
364 //alert(field + ": hidden with index: " + index );
365 this.table.fnSetColumnVis(index, false);
368 // this is used at init-time, at which point only init_key can make sense
369 // (because the argument record, if it comes from query, might not have canonical_key set
370 set_checkbox_from_record: function (record, checked) {
371 if (checked === undefined) checked = true;
372 var init_id = record[this.init_key];
373 if (debug) messages.debug("univbrisfv.set_checkbox_from_record, init_id="+init_id);
374 // using table.$ to search inside elements that are not visible
375 var element = this.table.$('[init_id="'+init_id+'"]');
376 element.attr('checked',checked);
379 // id relates to canonical_key
380 set_checkbox_from_data: function (id, checked) {
381 if (checked === undefined) checked = true;
382 if (debug) messages.debug("univbrisfv.set_checkbox_from_data, id="+id);
383 // using table.$ to search inside elements that are not visible
384 var element = this.table.$("[id='"+id+"']");
385 element.attr('checked',checked);
388 /*************************** QUERY HANDLER ****************************/
390 on_filter_added: function(filter)
392 this.filters.push(filter);
396 on_filter_removed: function(filter)
398 // Remove corresponding filters
399 this.filters = $.grep(this.filters, function(x) {
405 on_filter_clear: function()
411 on_field_added: function(field)
413 this.show_column(field);
416 on_field_removed: function(field)
418 this.hide_column(field);
421 on_field_clear: function()
423 alert('UnivbrisFv::clear_fields() not implemented');
426 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
427 /*************************** ALL QUERY HANDLER ****************************/
429 on_all_filter_added: function(filter)
435 on_all_filter_removed: function(filter)
441 on_all_filter_clear: function()
447 on_all_field_added: function(field)
449 this.show_column(field);
452 on_all_field_removed: function(field)
454 this.hide_column(field);
457 on_all_field_clear: function()
459 alert('UnivbrisFv::clear_fields() not implemented');
463 /*************************** RECORD HANDLER ***************************/
465 on_new_record: function(record)
467 if (this.received_all_query) {
468 // if the 'all' query has been dealt with already we may turn on the checkbox
469 this.set_checkbox_from_record(record, true);
471 this.buffered_records_to_check.push(record);
475 on_clear_records: function()
479 // Could be the default in parent
480 on_query_in_progress: function()
485 on_query_done: function()
487 this.received_query = true;
488 // unspin once we have received both
489 if (this.received_all_query && this.received_query) this.unspin();
492 on_field_state_changed: function(data)
494 switch(data.request) {
495 case FIELD_REQUEST_ADD:
496 case FIELD_REQUEST_ADD_RESET:
497 this.set_checkbox_from_data(data.value, true);
499 case FIELD_REQUEST_REMOVE:
500 case FIELD_REQUEST_REMOVE_RESET:
501 this.set_checkbox_from_data(data.value, false);
508 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
510 on_all_field_state_changed: function(data)
512 switch(data.request) {
513 case FIELD_REQUEST_ADD:
514 case FIELD_REQUEST_ADD_RESET:
515 this.set_checkboxfrom_data(data.value, true);
517 case FIELD_REQUEST_REMOVE:
518 case FIELD_REQUEST_REMOVE_RESET:
519 this.set_checkbox_from_data(data.value, false);
526 on_all_new_record: function(record)
528 this.new_record(record);
531 on_all_clear_records: function()
537 on_all_query_in_progress: function()
541 }, // on_all_query_in_progress
543 on_all_query_done: function()
545 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
546 this.table.fnAddData (this.buffered_lines);
547 this.buffered_lines=[];
550 // if we've already received the slice query, we have not been able to set
551 // checkboxes on the fly at that time (dom not yet created)
552 $.each(this.buffered_records_to_check, function(i, record) {
553 if (debug) messages.debug ("querytable delayed turning on checkbox " + i + " record= " + record);
554 self.set_checkbox_from_record(record, true);
556 this.buffered_records_to_check = [];
558 this.received_all_query = true;
559 // unspin once we have received both
560 if (this.received_all_query && this.received_query) this.unspin();
562 }, // on_all_query_done
564 /************************** PRIVATE METHODS ***************************/
567 * @brief QueryTable filtering function
569 _querytable_filter: function(oSettings, aData, iDataIndex)
572 $.each (this.filters, function(index, filter) {
573 /* XXX How to manage checkbox ? */
576 var value = filter[2];
578 /* Determine index of key in the table columns */
579 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
581 /* Unknown key: no filtering */
582 if (typeof(col) == 'undefined')
585 col_value=unfold.get_value(aData[col]);
586 /* Test whether current filter is compatible with the column */
587 if (op == '=' || op == '==') {
588 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
590 }else if (op == '!=') {
591 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
594 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
597 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
599 } else if(op=='<=' || op=='≤') {
600 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
602 } else if(op=='>=' || op=='≥') {
603 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
606 // How to break out of a loop ?
607 alert("filter not supported");
615 _querytable_draw_callback: function()
618 * Handle clicks on checkboxes: reassociate checkbox click every time
619 * the table is redrawn
621 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
622 this.elts("next").unbind('click').click(this, this.fnButnext);
628 /* Remove pagination if we show only a few results */
629 var wrapper = this.table; //.parent().parent().parent();
630 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
631 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
632 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
634 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
635 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
637 $('.querytable_paginate', wrapper).css('visibility', 'visible');
640 if ( rowsToShow <= minRowsPerPage ) {
641 $('.querytable_length', wrapper).css('visibility', 'hidden');
643 $('.querytable_length', wrapper).css('visibility', 'visible');
650 _check_click: function(e)
657 // this.id = key of object to be added... what about multiple keys ?
658 if (debug) messages.debug("querytable._check_click key="+this.canonical_key+"->"+id+" checked="+this.checked);
659 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, id);
660 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
664 _selectAll: function()
666 // requires jQuery id
667 var uuid=this.id.split("-");
668 var oTable=$("#querytable-"+uuid[1]).dataTable();
669 // Function available in QueryTable 1.9.x
670 // Filter : displayed data only
671 var filterData = oTable._('tr', {"filter":"applied"});
672 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
673 if(filterData.length<=100){
674 $.each(filterData, function(index, obj) {
675 var last=$(obj).last();
676 var key_value=unfold.get_value(last[0]);
677 if(typeof($(last[0]).attr('checked'))=="undefined"){
678 $.publish('selected', 'add/'+key_value);
686 $.plugin('UnivbrisFv', UnivbrisFv);
688 /* define the 'dom-checkbox' type for sorting in datatables
689 http://datatables.net/examples/plug-ins/dom_sort.html
690 using trial and error I found that the actual column number
691 was in fact given as a third argument, and not second
692 as the various online resources had it - go figure */
693 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
694 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
695 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';