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