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             // query status
21             this.received_all = false;
22             this.received_set = false;
23             this.in_set_buffer = Array();
24
25             /* XXX Events XXX */
26             // this.$element.on('show.Datatables', this.on_show);
27             this.elmt().on('show', this, this.on_show);
28             // Unbind all events using namespacing
29             // TODO in destructor
30             // $(window).unbind('Hazelnut');
31
32             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
33             this.method = query.object;
34
35             var keys = manifold.metadata.get_key(this.method);
36             this.key = (keys && keys.length == 1) ? keys[0] : null;
37
38             /* Setup query and record handlers */
39             this.listen_query(options.query_uuid);
40             this.listen_query(options.query_all_uuid, 'all');
41
42             /* an internal buffer for keeping lines and display them in one call to fnAddData */
43             this.buffered_lines = [];
44
45             /* GUI setup and event binding */
46             this.initialize_table();
47         },
48
49         default_options: {
50             'checkboxes': false
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             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     $.extend(actual_options, options.datatables_options );
102             this.table = this.elmt('table').dataTable(actual_options);
103
104             /* Setup the SelectAll button in the dataTable header */
105             /* xxx not sure this is still working */
106             var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
107             oSelectAll.html("<span class='ui-icon ui-icon-check' style='float:right;display:inline-block;'></span>Select All");
108             oSelectAll.button();
109             oSelectAll.css('font-size','11px');
110             oSelectAll.css('float','right');
111             oSelectAll.css('margin-right','15px');
112             oSelectAll.css('margin-bottom','5px');
113             oSelectAll.unbind('click');
114             oSelectAll.click(this._selectAll);
115
116             /* Add a filtering function to the current table 
117              * Note: we use closure to get access to the 'options'
118              */
119             $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) { 
120                 /* No filtering if the table does not match */
121                 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
122                     return true;
123                 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
124             });
125
126             /* Processing hidden_columns */
127             $.each(this.options.hidden_columns, function(i, field) {
128                 self.hide_column(field);
129             });
130         }, // initialize_table
131
132         /**
133          * @brief Determine index of key in the table columns 
134          * @param key
135          * @param cols
136          */
137         getColIndex: function(key, cols) {
138             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
139             return (tabIndex.length > 0) ? tabIndex[0] : -1;
140         }, // getColIndex
141
142         checkbox: function (key, value)
143         {
144             var result="";
145             // Prefix id with plugin_uuid
146             result += "<input";
147             result += " class='hazelnut-checkbox'";
148             result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
149             result += " name='" + key + "'";
150             result += " type='checkbox'";
151             result += " autocomplete='off'";
152             result += " value='" + value + "'";
153             result += "></input>";
154             return result;
155         }, // checkbox
156
157
158         new_record: function(record)
159         {
160             // this models a line in dataTables, each element in the line describes a cell
161             line = new Array();
162      
163             // go through table headers to get column names we want
164             // in order (we have temporarily hack some adjustments in names)
165             var cols = this.table.fnSettings().aoColumns;
166             var colnames = cols.map(function(x) {return x.sTitle})
167             var nb_col = cols.length;
168             /* if we've requested checkboxes, then forget about the checkbox column for now */
169             if (this.options.checkboxes) nb_col -= 1;
170
171             /* fill in stuff depending on the column name */
172             for (var j = 0; j < nb_col; j++) {
173                 if (typeof colnames[j] == 'undefined') {
174                     line.push('...');
175                 } else if (colnames[j] == 'hostname') {
176                     if (record['type'] == 'resource,link')
177                         //TODO: we need to add source/destination for links
178                         line.push('');
179                     else
180                         line.push(record['hostname']);
181                 } else {
182                     if (record[colnames[j]])
183                         line.push(record[colnames[j]]);
184                     else
185                         line.push('');
186                 }
187             }
188     
189             /* catch up with the last column if checkboxes were requested */
190             if (this.options.checkboxes)
191                 // Use a key instead of hostname (hard coded...)
192                 // XXX remove the empty checked attribute
193                 line.push(this.checkbox(this.key, record[this.key]));
194     
195 // adding an array in one call is *much* more efficient
196 //            this.table.fnAddData(line);
197             this.buffered_lines.push(line)
198
199         },
200
201         clear_table: function()
202         {
203             this.table.fnClearTable();
204         },
205
206         redraw_table: function()
207         {
208             this.table.fnDraw();
209         },
210
211         show_column: function(field)
212         {
213             var oSettings = this.table.fnSettings();
214             var cols = oSettings.aoColumns;
215             var index = this.getColIndex(field,cols);
216             if (index != -1)
217                 this.table.fnSetColumnVis(index, true);
218         },
219
220         hide_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, false);
227         },
228
229         set_checkbox: function(record, checked)
230         {
231             /* Default: checked = true */
232             if (typeof checked === 'undefined')
233                 checked = true;
234
235             var key_value;
236             /* The function accepts both records and their key */
237             switch (manifold.get_type(record)) {
238                 case TYPE_VALUE:
239                     key_value = record;
240                     break;
241                 case TYPE_RECORD:
242                     /* XXX Test the key before ? */
243                     key_value = record[this.key];
244                     break;
245                 default:
246                     throw "Not implemented";
247                     break;
248             }
249
250
251             var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
252             checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
253
254             var element = $(checkbox_id, this.table.fnGetNodes());
255
256             element.attr('checked', checked);
257         },
258
259         /*************************** QUERY HANDLER ****************************/
260
261         on_filter_added: function(filter)
262         {
263             // XXX
264             this.redraw_table();
265         },
266
267         on_filter_removed: function(filter)
268         {
269             // XXX
270             this.redraw_table();
271         },
272         
273         on_filter_clear: function()
274         {
275             // XXX
276             this.redraw_table();
277         },
278
279         on_field_added: function(field)
280         {
281             this.show_column(field);
282         },
283
284         on_field_removed: function(field)
285         {
286             this.hide_column(field);
287         },
288
289         on_field_clear: function()
290         {
291             alert('Hazelnut::clear_fields() not implemented');
292         },
293
294         /*************************** RECORD HANDLER ***************************/
295
296         on_new_record: function(record)
297         {
298             /* NOTE in fact we are doing a join here */
299             if (this.received_all)
300                 // update checkbox for record
301                 this.set_checkbox(record, true);
302             else
303                 // store for later update of checkboxes
304                 this.in_set_buffer.push(record);
305         },
306
307         on_clear_records: function()
308         {
309         },
310
311         // Could be the default in parent
312         on_query_in_progress: function()
313         {
314             this.spin();
315         },
316
317         on_query_done: function()
318         {
319             if (this.received_all)
320                 this.unspin();
321             this.received_set = true;
322         },
323         
324         on_field_state_changed: function(data)
325         {
326             switch(data.request) {
327                 case FIELD_REQUEST_ADD:
328                 case FIELD_REQUEST_ADD_RESET:
329                     this.set_checkbox(data.value, true);
330                     break;
331                 case FIELD_REQUEST_REMOVE:
332                 case FIELD_REQUEST_REMOVE_RESET:
333                     this.set_checkbox(data.value, false);
334                     break;
335                 default:
336                     break;
337             }
338         },
339
340         // all
341
342         on_all_new_record: function(record)
343         {
344             this.new_record(record);
345         },
346
347         on_all_clear_records: function()
348         {
349             this.clear_table();
350
351         },
352
353         on_all_query_in_progress: function()
354         {
355             // XXX parent
356             this.spin();
357         }, // on_all_query_in_progress
358
359         on_all_query_done: function()
360         {
361             var self = this;
362             if (this.received_set) {
363                 /* XXX needed ? XXX We uncheck all checkboxes ... */
364                 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
365
366                 /* ... and check the ones specified in the resource list */
367                 $.each(this.in_set_buffer, function(i, record) {
368                     self.set_checkbox(record, true);
369                 });
370
371                 this.unspin();
372             }
373             this.table.fnAddData (this.buffered_lines);
374             this.buffered_lines=[];
375             this.received_all = true;
376
377         }, // on_all_query_done
378
379         /************************** PRIVATE METHODS ***************************/
380
381         /** 
382          * @brief Hazelnut filtering function
383          */
384         _hazelnut_filter: function(oSettings, aData, iDataIndex)
385         {
386             var cur_query = this.current_query;
387             if (!cur_query) return true;
388             var ret = true;
389
390             /* We have an array of filters : a filter is an array (key op val) 
391              * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
392              *     can we exploit the data property somewhere ?
393              * field values (unless formatting) : aData
394              *     formatting should leave original data available in a hidden field
395              *
396              * The current line should validate all filters
397              */
398             $.each (cur_query.filters, function(index, filter) { 
399                 /* XXX How to manage checkbox ? */
400                 var key = filter[0]; 
401                 var op = filter[1];
402                 var value = filter[2];
403
404                 /* Determine index of key in the table columns */
405                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
406
407                 /* Unknown key: no filtering */
408                 if (typeof(col) == 'undefined')
409                     return;
410
411                 col_value=unfold.get_value(aData[col]);
412                 /* Test whether current filter is compatible with the column */
413                 if (op == '=' || op == '==') {
414                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
415                         ret = false;
416                 }else if (op == '!=') {
417                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
418                         ret = false;
419                 } else if(op=='<') {
420                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
421                         ret = false;
422                 } else if(op=='>') {
423                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
424                         ret = false;
425                 } else if(op=='<=' || op=='≤') {
426                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
427                         ret = false;
428                 } else if(op=='>=' || op=='≥') {
429                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
430                         ret = false;
431                 }else{
432                     // How to break out of a loop ?
433                     alert("filter not supported");
434                     return false;
435                 }
436
437             });
438             return ret;
439         },
440
441         _hazelnut_draw_callback: function()
442         {
443             /* 
444              * Handle clicks on checkboxes: reassociate checkbox click every time
445              * the table is redrawn 
446              */
447             this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
448
449             if (!this.table)
450                 return;
451
452             /* Remove pagination if we show only a few results */
453             var wrapper = this.table; //.parent().parent().parent();
454             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
455             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
456             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
457
458             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
459                 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
460             } else {
461                 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
462             }
463
464             if ( rowsToShow <= minRowsPerPage ) {
465                 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
466             } else {
467                 $('.hazelnut_length', wrapper).css('visibility', 'visible');
468             }
469         },
470
471         _check_click: function(e) 
472         {
473             e.stopPropagation();
474
475             var self = e.data;
476
477             // XXX this.value = key of object to be added... what about multiple keys ?
478             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
479             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
480             
481         },
482
483         _selectAll: function() 
484         {
485             // requires jQuery id
486             var uuid=this.id.split("-");
487             var oTable=$("#hazelnut-"+uuid[1]).dataTable();
488             // Function available in Hazelnut 1.9.x
489             // Filter : displayed data only
490             var filterData = oTable._('tr', {"filter":"applied"});   
491             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
492             if(filterData.length<=100){
493                 $.each(filterData, function(index, obj) {
494                     var last=$(obj).last();
495                     var key_value=unfold.get_value(last[0]);
496                     if(typeof($(last[0]).attr('checked'))=="undefined"){
497                         $.publish('selected', 'add/'+key_value);
498                     }
499                 });
500             }
501         },
502
503     });
504
505     $.plugin('Hazelnut', Hazelnut);
506
507 })(jQuery);