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