4cafe83e808e8065510e2c264dce46c401b5b130
[myslice.git] / plugins / querytable / static / js / querytable.js
1 /**
2  * Description: display a query result in a datatables-powered <table>
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 (function($){
8
9     var debug=false;
10 //    debug=true
11
12     var QueryTable = Plugin.extend({
13
14         init: function(options, element) 
15         {
16             this._super(options, element);
17
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;
25
26             // We need to remember the active filter for datatables filtering
27             this.filters = Array(); 
28
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 = [];
33
34             /* XXX Events XXX */
35             // this.$element.on('show.Datatables', this.on_show);
36             this.elmt().on('show', this, this.on_show);
37             // Unbind all events using namespacing
38             // TODO in destructor
39             // $(window).unbind('QueryTable');
40
41             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
42             this.method = query.object;
43
44             var keys = manifold.metadata.get_key(this.method);
45             this.key = (keys && keys.length == 1) ? keys[0] : null;
46
47             /* Setup query and record handlers */
48             this.listen_query(options.query_uuid);
49             this.listen_query(options.query_all_uuid, 'all');
50
51             /* GUI setup and event binding */
52             this.initialize_table();
53         },
54
55         /* PLUGIN EVENTS */
56
57         on_show: function(e)
58         {
59             var self = e.data;
60
61             self.table.fnAdjustColumnSizing()
62         
63             /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */        
64             /* temp disabled... useful ? -- jordan
65             $(this).each(function(i,elt) {
66                 if (jQuery(elt).hasClass('dataTables')) {
67                     var myDiv=jQuery('#querytable-' + this.id).parent();
68                     if(myDiv.height()==0) {
69                         var oTable=$('#querytable-' + this.id).dataTable();            
70                         oTable.fnDraw();
71                     }
72                 }
73             });
74             */
75         }, // on_show
76
77         /* GUI EVENTS */
78
79         /* GUI MANIPULATION */
80
81         initialize_table: function() 
82         {
83             /* Transforms the table into DataTable, and keep a pointer to it */
84             var self = this;
85             var actual_options = {
86                 // Customize the position of Datatables elements (length,filter,button,...)
87                 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
88                 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
89                 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
90                 // hopefully this would come with dataTables v1.10 ?
91                 // in any case, search for 'sPaginationType' all over the code for more comments
92                 sPaginationType: 'bootstrap',
93                 // Handle the null values & the error : Datatables warning Requested unknown parameter
94                 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
95                 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
96                 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
97                 // sScrollX: '100%',       /* Horizontal scrolling */
98                 bProcessing: true,      /* Loading */
99                 fnDrawCallback: function() { self._querytable_draw_callback.call(self); }
100                 // XXX use $.proxy here !
101             };
102             // the intention here is that options.datatables_options as coming from the python object take precedence
103             // xxx DISABLED by jordan: was causing errors in datatables.js
104             // xxx turned back on by Thierry - this is the code that takes python-provided options into account
105             // check your datatables_options tag instead 
106             // however, we have to accumulate in aoColumnDefs from here (above) 
107             // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
108             if ( 'aoColumnDefs' in this.options.datatables_options) {
109                 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
110                 delete this.options.datatables_options['aoColumnDefs'];
111             }
112             $.extend(actual_options, this.options.datatables_options );
113             this.table = this.elmt('table').dataTable(actual_options);
114
115             /* Setup the SelectAll button in the dataTable header */
116             /* xxx not sure this is still working */
117             var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
118             oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
119             oSelectAll.button();
120             oSelectAll.css('font-size','11px');
121             oSelectAll.css('float','right');
122             oSelectAll.css('margin-right','15px');
123             oSelectAll.css('margin-bottom','5px');
124             oSelectAll.unbind('click');
125             oSelectAll.click(this._selectAll);
126
127             /* Add a filtering function to the current table 
128              * Note: we use closure to get access to the 'options'
129              */
130             $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
131                 /* No filtering if the table does not match */
132                 if (oSettings.nTable.id != self.options.plugin_uuid + '__table')
133                     return true;
134                 return self._querytable_filter.call(self, oSettings, aData, iDataIndex);
135             });
136
137             /* Processing hidden_columns */
138             $.each(this.options.hidden_columns, function(i, field) {
139                 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
140                 self.hide_column(field);
141             });
142         }, // initialize_table
143
144         /**
145          * @brief Determine index of key in the table columns 
146          * @param key
147          * @param cols
148          */
149         getColIndex: function(key, cols) {
150             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
151             return (tabIndex.length > 0) ? tabIndex[0] : -1;
152         }, // getColIndex
153
154         checkbox_html : function (key, value)
155         {
156 //          if (debug) messages.debug("checkbox_html, value="+value);
157             var result="";
158             // Prefix id with plugin_uuid
159             result += "<input";
160             result += " class='querytable-checkbox'";
161             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
162             result += " name='" + key + "'";
163             result += " type='checkbox'";
164             result += " autocomplete='off'";
165             if (value === undefined) {
166                 messages.warning("querytable.checkbox_html - undefined value");
167             } else {
168                 result += " value='" + value + "'";
169             }
170             result += "></input>";
171             return result;
172         }, 
173
174
175         new_record: function(record)
176         {
177             // this models a line in dataTables, each element in the line describes a cell
178             line = new Array();
179      
180             // go through table headers to get column names we want
181             // in order (we have temporarily hack some adjustments in names)
182             var cols = this.table.fnSettings().aoColumns;
183             var colnames = cols.map(function(x) {return x.sTitle})
184             var nb_col = cols.length;
185             /* if we've requested checkboxes, then forget about the checkbox column for now */
186             if (this.options.checkboxes) nb_col -= 1;
187
188             /* fill in stuff depending on the column name */
189             for (var j = 0; j < nb_col; j++) {
190                 if (typeof colnames[j] == 'undefined') {
191                     line.push('...');
192                 } else if (colnames[j] == 'hostname') {
193                     if (record['type'] == 'resource,link')
194                         //TODO: we need to add source/destination for links
195                         line.push('');
196                     else
197                         line.push(record['hostname']);
198
199                 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
200                     line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
201                 } else {
202                     if (record[colnames[j]])
203                         line.push(record[colnames[j]]);
204                     else
205                         line.push('');
206                 }
207             }
208     
209             // catch up with the last column if checkboxes were requested 
210             if (this.options.checkboxes) {
211                 // Use a key instead of hostname (hard coded...)
212                 line.push(this.checkbox_html(this.key, record[this.key]));
213                 }
214     
215             // adding an array in one call is *much* more efficient
216                 // this.table.fnAddData(line);
217                 this.buffered_lines.push(line);
218         },
219
220         clear_table: function()
221         {
222             this.table.fnClearTable();
223         },
224
225         redraw_table: function()
226         {
227             this.table.fnDraw();
228         },
229
230         show_column: function(field)
231         {
232             var oSettings = this.table.fnSettings();
233             var cols = oSettings.aoColumns;
234             var index = this.getColIndex(field,cols);
235             if (index != -1)
236                 this.table.fnSetColumnVis(index, true);
237         },
238
239         hide_column: function(field)
240         {
241             var oSettings = this.table.fnSettings();
242             var cols = oSettings.aoColumns;
243             var index = this.getColIndex(field,cols);
244             if (index != -1)
245                 this.table.fnSetColumnVis(index, false);
246         },
247
248         set_checkbox: function(record, checked)
249         {
250             /* Default: checked = true */
251             if (checked === undefined) checked = true;
252
253             var id;
254             /* The function accepts both records and their key */
255             switch (manifold.get_type(record)) {
256             case TYPE_VALUE:
257                 id = record;
258                 break;
259             case TYPE_RECORD:
260                 /* XXX Test the key before ? */
261                 id = record[this.key];
262                 break;
263             default:
264                 throw "Not implemented";
265                 break;
266             }
267
268
269             if (id === undefined) {
270                 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
271                 return;
272             }
273             var checkbox_id = this.flat_id(this.id('checkbox', id));
274             // function escape_id(myid) is defined in portal/static/js/common.functions.js
275             checkbox_id = escape_id(checkbox_id);
276             // using dataTables's $ to search also in nodes that are not currently displayed
277             var element = this.table.$(checkbox_id);
278             if (debug) 
279                 messages.debug("set_checkbox checked=" + checked
280                                + " id=" + checkbox_id + " matches=" + element.length);
281             element.attr('checked', checked);
282         },
283
284         /*************************** QUERY HANDLER ****************************/
285
286         on_filter_added: function(filter)
287         {
288             this.filters.push(filter);
289             this.redraw_table();
290         },
291
292         on_filter_removed: function(filter)
293         {
294             // Remove corresponding filters
295             this.filters = $.grep(this.filters, function(x) {
296                 return x != filter;
297             });
298             this.redraw_table();
299         },
300         
301         on_filter_clear: function()
302         {
303             // XXX
304             this.redraw_table();
305         },
306
307         on_field_added: function(field)
308         {
309             this.show_column(field);
310         },
311
312         on_field_removed: function(field)
313         {
314             this.hide_column(field);
315         },
316
317         on_field_clear: function()
318         {
319             alert('QueryTable::clear_fields() not implemented');
320         },
321
322         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
323         /*************************** ALL QUERY HANDLER ****************************/
324
325         on_all_filter_added: function(filter)
326         {
327             // XXX
328             this.redraw_table();
329         },
330
331         on_all_filter_removed: function(filter)
332         {
333             // XXX
334             this.redraw_table();
335         },
336         
337         on_all_filter_clear: function()
338         {
339             // XXX
340             this.redraw_table();
341         },
342
343         on_all_field_added: function(field)
344         {
345             this.show_column(field);
346         },
347
348         on_all_field_removed: function(field)
349         {
350             this.hide_column(field);
351         },
352
353         on_all_field_clear: function()
354         {
355             alert('QueryTable::clear_fields() not implemented');
356         },
357
358
359         /*************************** RECORD HANDLER ***************************/
360
361         on_new_record: function(record)
362         {
363             if (this.received_all_query) {
364                 // if the 'all' query has been dealt with already we may turn on the checkbox
365                 this.set_checkbox(record, true);
366             } else {
367                 // otherwise we need to remember that and do it later on
368                 if (debug) messages.debug("Remembering record to check " + record[this.key]);
369                 this.buffered_records_to_check.push(record);
370             }
371         },
372
373         on_clear_records: function()
374         {
375         },
376
377         // Could be the default in parent
378         on_query_in_progress: function()
379         {
380             this.spin();
381         },
382
383         on_query_done: function()
384         {
385             this.received_query = true;
386             // unspin once we have received both
387             if (this.received_all_query && this.received_query) this.unspin();
388         },
389         
390         on_field_state_changed: function(data)
391         {
392             switch(data.request) {
393                 case FIELD_REQUEST_ADD:
394                 case FIELD_REQUEST_ADD_RESET:
395                     this.set_checkbox(data.value, true);
396                     break;
397                 case FIELD_REQUEST_REMOVE:
398                 case FIELD_REQUEST_REMOVE_RESET:
399                     this.set_checkbox(data.value, false);
400                     break;
401                 default:
402                     break;
403             }
404         },
405
406         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
407         // all
408         on_all_field_state_changed: function(data)
409         {
410             switch(data.request) {
411                 case FIELD_REQUEST_ADD:
412                 case FIELD_REQUEST_ADD_RESET:
413                     this.set_checkbox(data.value, true);
414                     break;
415                 case FIELD_REQUEST_REMOVE:
416                 case FIELD_REQUEST_REMOVE_RESET:
417                     this.set_checkbox(data.value, false);
418                     break;
419                 default:
420                     break;
421             }
422         },
423
424         on_all_new_record: function(record)
425         {
426             this.new_record(record);
427         },
428
429         on_all_clear_records: function()
430         {
431             this.clear_table();
432
433         },
434
435         on_all_query_in_progress: function()
436         {
437             // XXX parent
438             this.spin();
439         }, // on_all_query_in_progress
440
441         on_all_query_done: function()
442         {
443             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
444             this.table.fnAddData (this.buffered_lines);
445             this.buffered_lines=[];
446             
447             var self = this;
448             // if we've already received the slice query, we have not been able to set 
449             // checkboxes on the fly at that time (dom not yet created)
450             $.each(this.buffered_records_to_check, function(i, record) {
451                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
452                 self.set_checkbox(record, true);
453             });
454             this.buffered_records_to_check = [];
455
456             this.received_all_query = true;
457             // unspin once we have received both
458             if (this.received_all_query && this.received_query) this.unspin();
459
460         }, // on_all_query_done
461
462         /************************** PRIVATE METHODS ***************************/
463
464         /** 
465          * @brief QueryTable filtering function
466          */
467         _querytable_filter: function(oSettings, aData, iDataIndex)
468         {
469             var ret = true;
470             $.each (this.filters, function(index, filter) { 
471                 /* XXX How to manage checkbox ? */
472                 var key = filter[0]; 
473                 var op = filter[1];
474                 var value = filter[2];
475
476                 /* Determine index of key in the table columns */
477                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
478
479                 /* Unknown key: no filtering */
480                 if (typeof(col) == 'undefined')
481                     return;
482
483                 col_value=unfold.get_value(aData[col]);
484                 /* Test whether current filter is compatible with the column */
485                 if (op == '=' || op == '==') {
486                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
487                         ret = false;
488                 }else if (op == '!=') {
489                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
490                         ret = false;
491                 } else if(op=='<') {
492                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
493                         ret = false;
494                 } else if(op=='>') {
495                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
496                         ret = false;
497                 } else if(op=='<=' || op=='≤') {
498                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
499                         ret = false;
500                 } else if(op=='>=' || op=='≥') {
501                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
502                         ret = false;
503                 }else{
504                     // How to break out of a loop ?
505                     alert("filter not supported");
506                     return false;
507                 }
508
509             });
510             return ret;
511         },
512
513         _querytable_draw_callback: function()
514         {
515             /* 
516              * Handle clicks on checkboxes: reassociate checkbox click every time
517              * the table is redrawn 
518              */
519             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
520
521             if (!this.table)
522                 return;
523
524             /* Remove pagination if we show only a few results */
525             var wrapper = this.table; //.parent().parent().parent();
526             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
527             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
528             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
529
530             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
531                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
532             } else {
533                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
534             }
535
536             if ( rowsToShow <= minRowsPerPage ) {
537                 $('.querytable_length', wrapper).css('visibility', 'hidden');
538             } else {
539                 $('.querytable_length', wrapper).css('visibility', 'visible');
540             }
541         },
542
543         _check_click: function(e) 
544         {
545             e.stopPropagation();
546
547             var self = e.data;
548
549             // XXX this.value = key of object to be added... what about multiple keys ?
550             if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
551             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
552             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
553             
554         },
555
556         _selectAll: function() 
557         {
558             // requires jQuery id
559             var uuid=this.id.split("-");
560             var oTable=$("#querytable-"+uuid[1]).dataTable();
561             // Function available in QueryTable 1.9.x
562             // Filter : displayed data only
563             var filterData = oTable._('tr', {"filter":"applied"});   
564             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
565             if(filterData.length<=100){
566                 $.each(filterData, function(index, obj) {
567                     var last=$(obj).last();
568                     var key_value=unfold.get_value(last[0]);
569                     if(typeof($(last[0]).attr('checked'))=="undefined"){
570                         $.publish('selected', 'add/'+key_value);
571                     }
572                 });
573             }
574         },
575
576     });
577
578     $.plugin('QueryTable', QueryTable);
579
580   /* define the 'dom-checkbox' type for sorting in datatables 
581      http://datatables.net/examples/plug-ins/dom_sort.html
582      using trial and error I found that the actual column number
583      was in fact given as a third argument, and not second 
584      as the various online resources had it - go figure */
585     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
586         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
587             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
588         } );
589     }
590
591 })(jQuery);
592