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