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