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