plugin.hazelnut: fixed issue with filtering
[myslice.git] / plugins / hazelnut / static / js / hazelnut.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 Hazelnut = 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('Hazelnut');
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('#hazelnut-' + this.id).parent();
68                     if(myDiv.height()==0) {
69                         var oTable=$('#hazelnut-' + 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._hazelnut_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._hazelnut_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             var result="";
157             // Prefix id with plugin_uuid
158             result += "<input";
159             result += " class='hazelnut-checkbox'";
160             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
161             result += " name='" + key + "'";
162             result += " type='checkbox'";
163             result += " autocomplete='off'";
164             result += " value='" + value + "'";
165             result += "></input>";
166             return result;
167         }, // checkbox
168
169
170         new_record: function(record)
171         {
172             // this models a line in dataTables, each element in the line describes a cell
173             line = new Array();
174      
175             // go through table headers to get column names we want
176             // in order (we have temporarily hack some adjustments in names)
177             var cols = this.table.fnSettings().aoColumns;
178             var colnames = cols.map(function(x) {return x.sTitle})
179             var nb_col = cols.length;
180             /* if we've requested checkboxes, then forget about the checkbox column for now */
181             if (this.options.checkboxes) nb_col -= 1;
182
183             /* fill in stuff depending on the column name */
184             for (var j = 0; j < nb_col; j++) {
185                 if (typeof colnames[j] == 'undefined') {
186                     line.push('...');
187                 } else if (colnames[j] == 'hostname') {
188                     if (record['type'] == 'resource,link')
189                         //TODO: we need to add source/destination for links
190                         line.push('');
191                     else
192                         line.push(record['hostname']);
193
194                 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
195                     line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
196                 } else {
197                     if (record[colnames[j]])
198                         line.push(record[colnames[j]]);
199                     else
200                         line.push('');
201                 }
202             }
203     
204             // catch up with the last column if checkboxes were requested 
205             if (this.options.checkboxes) {
206                 // Use a key instead of hostname (hard coded...)
207                 line.push(this.checkbox_html(this.key, record[this.key]));
208                 }
209     
210             // adding an array in one call is *much* more efficient
211                 // this.table.fnAddData(line);
212                 this.buffered_lines.push(line);
213         },
214
215         clear_table: function()
216         {
217             this.table.fnClearTable();
218         },
219
220         redraw_table: function()
221         {
222             this.table.fnDraw();
223         },
224
225         show_column: function(field)
226         {
227             var oSettings = this.table.fnSettings();
228             var cols = oSettings.aoColumns;
229             var index = this.getColIndex(field,cols);
230             if (index != -1)
231                 this.table.fnSetColumnVis(index, true);
232         },
233
234         hide_column: function(field)
235         {
236             var oSettings = this.table.fnSettings();
237             var cols = oSettings.aoColumns;
238             var index = this.getColIndex(field,cols);
239             if (index != -1)
240                 this.table.fnSetColumnVis(index, false);
241         },
242
243         set_checkbox: function(record, checked)
244         {
245             /* Default: checked = true */
246             if (checked === undefined) checked = true;
247
248             var key_value;
249             /* The function accepts both records and their key */
250             switch (manifold.get_type(record)) {
251                 case TYPE_VALUE:
252                     key_value = record;
253                     break;
254                 case TYPE_RECORD:
255                     /* XXX Test the key before ? */
256                     key_value = record[this.key];
257                     break;
258                 default:
259                     throw "Not implemented";
260                     break;
261             }
262
263
264             var checkbox_id = this.flat_id(this.id('checkbox', key_value));
265             // function escape_id(myid) is defined in portal/static/js/common.functions.js
266             checkbox_id = escape_id(checkbox_id);
267                 // using dataTables's $ to search also in nodes that are not currently displayed
268             var element = this.table.$(checkbox_id);
269                 if (debug) messages.debug("set_checkbox checked=" + checked + " id=" + checkbox_id + " matches=" + element.length);
270             element.attr('checked', checked);
271         },
272
273         /*************************** QUERY HANDLER ****************************/
274
275         on_filter_added: function(filter)
276         {
277             this.filters.push(filter);
278             this.redraw_table();
279         },
280
281         on_filter_removed: function(filter)
282         {
283             // Remove corresponding filters
284             this.filters = $.grep(this.filters, function(x) {
285                 return x != filter;
286             });
287             this.redraw_table();
288         },
289         
290         on_filter_clear: function()
291         {
292             // XXX
293             this.redraw_table();
294         },
295
296         on_field_added: function(field)
297         {
298             this.show_column(field);
299         },
300
301         on_field_removed: function(field)
302         {
303             this.hide_column(field);
304         },
305
306         on_field_clear: function()
307         {
308             alert('Hazelnut::clear_fields() not implemented');
309         },
310
311         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
312         /*************************** ALL QUERY HANDLER ****************************/
313
314         on_all_filter_added: function(filter)
315         {
316             // XXX
317             this.redraw_table();
318         },
319
320         on_all_filter_removed: function(filter)
321         {
322             // XXX
323             this.redraw_table();
324         },
325         
326         on_all_filter_clear: function()
327         {
328             // XXX
329             this.redraw_table();
330         },
331
332         on_all_field_added: function(field)
333         {
334             this.show_column(field);
335         },
336
337         on_all_field_removed: function(field)
338         {
339             this.hide_column(field);
340         },
341
342         on_all_field_clear: function()
343         {
344             alert('Hazelnut::clear_fields() not implemented');
345         },
346
347
348         /*************************** RECORD HANDLER ***************************/
349
350         on_new_record: function(record)
351         {
352             if (this.received_all_query) {
353                         // if the 'all' query has been dealt with already we may turn on the checkbox
354                         if (debug) messages.debug("turning on checkbox for record "+record[this.key]);
355                 this.set_checkbox(record, true);
356                 } else {
357                         // otherwise we need to remember that and do it later on
358                         if (debug) messages.debug("Remembering record to check " + record[this.key]);
359                 this.buffered_records_to_check.push(record);
360                 }
361         },
362
363         on_clear_records: function()
364         {
365         },
366
367         // Could be the default in parent
368         on_query_in_progress: function()
369         {
370             this.spin();
371         },
372
373         on_query_done: function()
374         {
375             this.received_query = true;
376             // unspin once we have received both
377             if (this.received_all_query && this.received_query) this.unspin();
378         },
379         
380         on_field_state_changed: function(data)
381         {
382             switch(data.request) {
383                 case FIELD_REQUEST_ADD:
384                 case FIELD_REQUEST_ADD_RESET:
385                     this.set_checkbox(data.value, true);
386                     break;
387                 case FIELD_REQUEST_REMOVE:
388                 case FIELD_REQUEST_REMOVE_RESET:
389                     this.set_checkbox(data.value, false);
390                     break;
391                 default:
392                     break;
393             }
394         },
395
396         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
397         // all
398         on_all_field_state_changed: function(data)
399         {
400             switch(data.request) {
401                 case FIELD_REQUEST_ADD:
402                 case FIELD_REQUEST_ADD_RESET:
403                     this.set_checkbox(data.value, true);
404                     break;
405                 case FIELD_REQUEST_REMOVE:
406                 case FIELD_REQUEST_REMOVE_RESET:
407                     this.set_checkbox(data.value, false);
408                     break;
409                 default:
410                     break;
411             }
412         },
413
414         on_all_new_record: function(record)
415         {
416             this.new_record(record);
417         },
418
419         on_all_clear_records: function()
420         {
421             this.clear_table();
422
423         },
424
425         on_all_query_in_progress: function()
426         {
427             // XXX parent
428             this.spin();
429         }, // on_all_query_in_progress
430
431         on_all_query_done: function()
432         {
433             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
434             this.table.fnAddData (this.buffered_lines);
435             this.buffered_lines=[];
436             
437             var self = this;
438             // if we've already received the slice query, we have not been able to set 
439             // checkboxes on the fly at that time (dom not yet created)
440             $.each(this.buffered_records_to_check, function(i, record) {
441                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
442                 self.set_checkbox(record, true);
443             });
444             this.buffered_records_to_check = [];
445
446             this.received_all_query = true;
447             // unspin once we have received both
448             if (this.received_all_query && this.received_query) this.unspin();
449
450         }, // on_all_query_done
451
452         /************************** PRIVATE METHODS ***************************/
453
454         /** 
455          * @brief Hazelnut filtering function
456          */
457         _hazelnut_filter: function(oSettings, aData, iDataIndex)
458         {
459             var ret = true;
460             $.each (this.filters, function(index, filter) { 
461                 /* XXX How to manage checkbox ? */
462                 var key = filter[0]; 
463                 var op = filter[1];
464                 var value = filter[2];
465
466                 /* Determine index of key in the table columns */
467                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
468
469                 /* Unknown key: no filtering */
470                 if (typeof(col) == 'undefined')
471                     return;
472
473                 col_value=unfold.get_value(aData[col]);
474                 /* Test whether current filter is compatible with the column */
475                 if (op == '=' || op == '==') {
476                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
477                         ret = false;
478                 }else if (op == '!=') {
479                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
480                         ret = false;
481                 } else if(op=='<') {
482                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
483                         ret = false;
484                 } else if(op=='>') {
485                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
486                         ret = false;
487                 } else if(op=='<=' || op=='≤') {
488                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
489                         ret = false;
490                 } else if(op=='>=' || op=='≥') {
491                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
492                         ret = false;
493                 }else{
494                     // How to break out of a loop ?
495                     alert("filter not supported");
496                     return false;
497                 }
498
499             });
500             return ret;
501         },
502
503         _hazelnut_draw_callback: function()
504         {
505             /* 
506              * Handle clicks on checkboxes: reassociate checkbox click every time
507              * the table is redrawn 
508              */
509             this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
510
511             if (!this.table)
512                 return;
513
514             /* Remove pagination if we show only a few results */
515             var wrapper = this.table; //.parent().parent().parent();
516             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
517             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
518             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
519
520             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
521                 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
522             } else {
523                 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
524             }
525
526             if ( rowsToShow <= minRowsPerPage ) {
527                 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
528             } else {
529                 $('.hazelnut_length', wrapper).css('visibility', 'visible');
530             }
531         },
532
533         _check_click: function(e) 
534         {
535             e.stopPropagation();
536
537             var self = e.data;
538
539             // XXX this.value = key of object to be added... what about multiple keys ?
540             if (debug) messages.debug("hazelnut click handler checked=" + this.checked + " hrn=" + this.value);
541             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
542             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
543             
544         },
545
546         _selectAll: function() 
547         {
548             // requires jQuery id
549             var uuid=this.id.split("-");
550             var oTable=$("#hazelnut-"+uuid[1]).dataTable();
551             // Function available in Hazelnut 1.9.x
552             // Filter : displayed data only
553             var filterData = oTable._('tr', {"filter":"applied"});   
554             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
555             if(filterData.length<=100){
556                 $.each(filterData, function(index, obj) {
557                     var last=$(obj).last();
558                     var key_value=unfold.get_value(last[0]);
559                     if(typeof($(last[0]).attr('checked'))=="undefined"){
560                         $.publish('selected', 'add/'+key_value);
561                     }
562                 });
563             }
564         },
565
566     });
567
568     $.plugin('Hazelnut', Hazelnut);
569
570   /* define the 'dom-checkbox' type for sorting in datatables 
571      http://datatables.net/examples/plug-ins/dom_sort.html
572      using trial and error I found that the actual column number
573      was in fact given as a third argument, and not second 
574      as the various online resources had it - go figure */
575     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
576         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
577             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
578         } );
579     }
580
581 })(jQuery);
582