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