hazelnut patched so that one single call to fnAddData is made once the 'all' query...
[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  // UNUSED ? //         this.update_plugin = function(e, rows) {
143  // UNUSED ? //             // e.data is what we passed in second argument to subscribe
144  // UNUSED ? //             // so here it is the jquery object attached to the plugin <div>
145  // UNUSED ? //             var $plugindiv=e.data;
146  // UNUSED ? //             if (debug)
147  // UNUSED ? //                 messages.debug("entering hazelnut.update_plugin on id '" + $plugindiv.attr('id') + "'");
148  // UNUSED ? //             // clear the spinning wheel: look up an ancestor that has the need-spin class
149  // UNUSED ? //             // do this before we might return
150  // UNUSED ? //             $plugindiv.closest('.need-spin').spin(false);
151  // UNUSED ? // 
152  // UNUSED ? //             var options = this.options;
153  // UNUSED ? //             var hazelnut = this;
154  // UNUSED ? //     
155  // UNUSED ? //             /* if we get no result, or an error, try to make that clear, and exit */
156  // UNUSED ? //             if (rows.length==0) {
157  // UNUSED ? //                 if (debug) 
158  // UNUSED ? //                     messages.debug("Empty result on hazelnut " + this.options.domid);
159  // UNUSED ? //                 var placeholder=$(this.table).find("td.dataTables_empty");
160  // UNUSED ? //                 console.log("placeholder "+placeholder);
161  // UNUSED ? //                 if (placeholder.length==1) 
162  // UNUSED ? //                     placeholder.html(unfold.warning("Empty result"));
163  // UNUSED ? //                 else
164  // UNUSED ? //                     this.table.html(unfold.warning("Empty result"));
165  // UNUSED ? //                     return;
166  // UNUSED ? //             } else if (typeof(rows[0].error) != 'undefined') {
167  // UNUSED ? //                 // we now should have another means to report errors that this inline/embedded hack
168  // UNUSED ? //                 if (debug) 
169  // UNUSED ? //                     messages.error ("undefined result on " + this.options.domid + " - should not happen anymore");
170  // UNUSED ? //                 this.table.html(unfold.error(rows[0].error));
171  // UNUSED ? //                 return;
172  // UNUSED ? //             }
173  // UNUSED ? // 
174  // UNUSED ? //             /* 
175  // UNUSED ? //              * fill the dataTables object
176  // UNUSED ? //              * we cannot set html content directly here, need to use fnAddData
177  // UNUSED ? //              */
178  // UNUSED ? //             var lines = new Array();
179  // UNUSED ? //     
180  // UNUSED ? //             this.current_resources = Array();
181  // UNUSED ? //     
182  // UNUSED ? //             $.each(rows, function(index, row) {
183  // UNUSED ? //                 // this models a line in dataTables, each element in the line describes a cell
184  // UNUSED ? //                 line = new Array();
185  // UNUSED ? //      
186  // UNUSED ? //                 // go through table headers to get column names we want
187  // UNUSED ? //                 // in order (we have temporarily hack some adjustments in names)
188  // UNUSED ? //                 var cols = object.table.fnSettings().aoColumns;
189  // UNUSED ? //                 var colnames = cols.map(function(x) {return x.sTitle})
190  // UNUSED ? //                 var nb_col = cols.length;
191  // UNUSED ? //                 /* if we've requested checkboxes, then forget about the checkbox column for now */
192  // UNUSED ? //                 if (options.checkboxes) nb_col -= 1;
193  // UNUSED ? // 
194  // UNUSED ? //                 /* fill in stuff depending on the column name */
195  // UNUSED ? //                 for (var j = 0; j < nb_col; j++) {
196  // UNUSED ? //                     if (typeof colnames[j] == 'undefined') {
197  // UNUSED ? //                         line.push('...');
198  // UNUSED ? //                     } else if (colnames[j] == 'hostname') {
199  // UNUSED ? //                         if (row['type'] == 'resource,link')
200  // UNUSED ? //                             //TODO: we need to add source/destination for links
201  // UNUSED ? //                             line.push('');
202  // UNUSED ? //                         else
203  // UNUSED ? //                             line.push(row['hostname']);
204  // UNUSED ? //                     } else {
205  // UNUSED ? //                         if (row[colnames[j]])
206  // UNUSED ? //                             line.push(row[colnames[j]]);
207  // UNUSED ? //                         else
208  // UNUSED ? //                             line.push('');
209  // UNUSED ? //                     }
210  // UNUSED ? //                 }
211  // UNUSED ? //     
212  // UNUSED ? //                 /* catch up with the last column if checkboxes were requested */
213  // UNUSED ? //                 if (options.checkboxes) {
214  // UNUSED ? //                     var checked = '';
215  // UNUSED ? //                     // xxx problem is, we don't get this 'sliver' thing set apparently
216  // UNUSED ? //                     if (typeof(row['sliver']) != 'undefined') { /* It is equal to null when <sliver/> is present */
217  // UNUSED ? //                         checked = 'checked ';
218  // UNUSED ? //                         hazelnut.current_resources.push(row[ELEMENT_KEY]);
219  // UNUSED ? //                     }
220  // UNUSED ? //                     // Use a key instead of hostname (hard coded...)
221  // UNUSED ? //                     line.push(hazelnut.checkbox(options.plugin_uuid, row[ELEMENT_KEY], row['type'], checked, false));
222  // UNUSED ? //                 }
223  // UNUSED ? //     
224  // UNUSED ? //                 lines.push(line);
225  // UNUSED ? //     
226  // UNUSED ? //             });
227  // UNUSED ? //     
228  // UNUSED ? //             this.table.fnClearTable();
229  // UNUSED ? //             if (debug)
230  // UNUSED ? //                 messages.debug("hazelnut.update_plugin: total of " + lines.length + " rows");
231  // UNUSED ? //             this.table.fnAddData(lines);
232  // UNUSED ? //         
233  // UNUSED ? //         }, // update_plugin
234
235         checkbox: function (key, value)
236         {
237             var result="";
238             // Prefix id with plugin_uuid
239             result += "<input";
240             result += " class='hazelnut-checkbox'";
241             result += " id='" + this.id('checkbox', this.id_from_key(key, value)) + "'";
242             result += " name='" + key + "'";
243             result += " type='checkbox'";
244             result += " autocomplete='off'";
245             result += " value='" + value + "'";
246             result += "></input>";
247             return result;
248         }, // checkbox
249
250
251         new_record: function(record)
252         {
253             // this models a line in dataTables, each element in the line describes a cell
254             line = new Array();
255      
256             // go through table headers to get column names we want
257             // in order (we have temporarily hack some adjustments in names)
258             var cols = this.table.fnSettings().aoColumns;
259             var colnames = cols.map(function(x) {return x.sTitle})
260             var nb_col = cols.length;
261             /* if we've requested checkboxes, then forget about the checkbox column for now */
262             if (this.options.checkboxes) nb_col -= 1;
263
264             /* fill in stuff depending on the column name */
265             for (var j = 0; j < nb_col; j++) {
266                 if (typeof colnames[j] == 'undefined') {
267                     line.push('...');
268                 } else if (colnames[j] == 'hostname') {
269                     if (record['type'] == 'resource,link')
270                         //TODO: we need to add source/destination for links
271                         line.push('');
272                     else
273                         line.push(record['hostname']);
274                 } else {
275                     if (record[colnames[j]])
276                         line.push(record[colnames[j]]);
277                     else
278                         line.push('');
279                 }
280             }
281     
282             /* catch up with the last column if checkboxes were requested */
283             if (this.options.checkboxes)
284                 // Use a key instead of hostname (hard coded...)
285                 // XXX remove the empty checked attribute
286                 line.push(this.checkbox(this.key, record[this.key]));
287     
288             // XXX Is adding an array of lines more efficient ?
289 //            this.table.fnAddData(line);
290             this.buffered_lines.push(line)
291
292         },
293
294         clear_table: function()
295         {
296             this.table.fnClearTable();
297         },
298
299         redraw_table: function()
300         {
301             this.table.fnDraw();
302         },
303
304         show_column: function(field)
305         {
306             var oSettings = this.table.fnSettings();
307             var cols = oSettings.aoColumns;
308             var index = this.getColIndex(field,cols);
309             if (index != -1)
310                 this.table.fnSetColumnVis(index, true);
311         },
312
313         hide_column: function(field)
314         {
315             var oSettings = this.table.fnSettings();
316             var cols = oSettings.aoColumns;
317             var index = this.getColIndex(field,cols);
318             if (index != -1)
319                 this.table.fnSetColumnVis(index, false);
320         },
321
322         set_checkbox: function(record, checked)
323         {
324             /* Default: checked = true */
325             if (typeof checked === 'undefined')
326                 checked = true;
327
328             var key_value;
329             /* The function accepts both records and their key */
330             switch (manifold.get_type(record)) {
331                 case TYPE_VALUE:
332                     key_value = record;
333                     break;
334                 case TYPE_RECORD:
335                     /* XXX Test the key before ? */
336                     key_value = record[this.key];
337                     break;
338                 default:
339                     throw "Not implemented";
340                     break;
341             }
342
343
344             var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
345             checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
346
347             var element = $(checkbox_id, this.table.fnGetNodes());
348
349             element.attr('checked', checked);
350         },
351
352         /*************************** QUERY HANDLER ****************************/
353
354         on_filter_added: function(filter)
355         {
356             // XXX
357             this.redraw_table();
358         },
359
360         on_filter_removed: function(filter)
361         {
362             // XXX
363             this.redraw_table();
364         },
365         
366         on_filter_clear: function()
367         {
368             // XXX
369             this.redraw_table();
370         },
371
372         on_field_added: function(field)
373         {
374             this.show_column(field);
375         },
376
377         on_field_removed: function(field)
378         {
379             this.hide_column(field);
380         },
381
382         on_field_clear: function()
383         {
384             alert('Hazelnut::clear_fields() not implemented');
385         },
386
387         /*************************** RECORD HANDLER ***************************/
388
389         on_new_record: function(record)
390         {
391             /* NOTE in fact we are doing a join here */
392             if (this.received_all)
393                 // update checkbox for record
394                 this.set_checkbox(record, true);
395             else
396                 // store for later update of checkboxes
397                 this.in_set_buffer.push(record);
398         },
399
400         on_clear_records: function()
401         {
402         },
403
404         // Could be the default in parent
405         on_query_in_progress: function()
406         {
407             this.spin();
408         },
409
410         on_query_done: function()
411         {
412             if (this.received_all)
413                 this.unspin();
414             this.received_set = true;
415         },
416         
417         on_field_state_changed: function(data)
418         {
419             switch(data.request) {
420                 case FIELD_REQUEST_ADD:
421                 case FIELD_REQUEST_ADD_RESET:
422                     this.set_checkbox(data.value, true);
423                     break;
424                 case FIELD_REQUEST_REMOVE:
425                 case FIELD_REQUEST_REMOVE_RESET:
426                     this.set_checkbox(data.value, false);
427                     break;
428                 default:
429                     break;
430             }
431         },
432
433         // all
434
435         on_all_new_record: function(record)
436         {
437             this.new_record(record);
438         },
439
440         on_all_clear_records: function()
441         {
442             this.clear_table();
443
444         },
445
446         on_all_query_in_progress: function()
447         {
448             // XXX parent
449             this.spin();
450         }, // on_all_query_in_progress
451
452         on_all_query_done: function()
453         {
454             var self = this;
455             if (this.received_set) {
456                 /* XXX needed ? XXX We uncheck all checkboxes ... */
457                 $("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
458
459                 /* ... and check the ones specified in the resource list */
460                 $.each(this.in_set_buffer, function(i, record) {
461                     self.set_checkbox(record, true);
462                 });
463
464                 this.unspin();
465             }
466             this.table.fnAddData (this.buffered_lines);
467             this.buffered_lines=[];
468             this.received_all = true;
469
470         }, // on_all_query_done
471
472         /************************** PRIVATE METHODS ***************************/
473
474         /** 
475          * @brief Hazelnut filtering function
476          */
477         _hazelnut_filter: function(oSettings, aData, iDataIndex)
478         {
479             var cur_query = this.current_query;
480             if (!cur_query) return true;
481             var ret = true;
482
483             /* We have an array of filters : a filter is an array (key op val) 
484              * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
485              *     can we exploit the data property somewhere ?
486              * field values (unless formatting) : aData
487              *     formatting should leave original data available in a hidden field
488              *
489              * The current line should validate all filters
490              */
491             $.each (cur_query.filters, function(index, filter) { 
492                 /* XXX How to manage checkbox ? */
493                 var key = filter[0]; 
494                 var op = filter[1];
495                 var value = filter[2];
496
497                 /* Determine index of key in the table columns */
498                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
499
500                 /* Unknown key: no filtering */
501                 if (typeof(col) == 'undefined')
502                     return;
503
504                 col_value=unfold.get_value(aData[col]);
505                 /* Test whether current filter is compatible with the column */
506                 if (op == '=' || op == '==') {
507                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
508                         ret = false;
509                 }else if (op == '!=') {
510                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
511                         ret = false;
512                 } else if(op=='<') {
513                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
514                         ret = false;
515                 } else if(op=='>') {
516                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
517                         ret = false;
518                 } else if(op=='<=' || op=='≤') {
519                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
520                         ret = false;
521                 } else if(op=='>=' || op=='≥') {
522                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
523                         ret = false;
524                 }else{
525                     // How to break out of a loop ?
526                     alert("filter not supported");
527                     return false;
528                 }
529
530             });
531             return ret;
532         },
533
534         _hazelnut_draw_callback: function()
535         {
536             /* 
537              * Handle clicks on checkboxes: reassociate checkbox click every time
538              * the table is redrawn 
539              */
540             this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
541
542             if (!this.table)
543                 return;
544
545             /* Remove pagination if we show only a few results */
546             var wrapper = this.table; //.parent().parent().parent();
547             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
548             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
549             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
550
551             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
552                 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
553             } else {
554                 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
555             }
556
557             if ( rowsToShow <= minRowsPerPage ) {
558                 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
559             } else {
560                 $('.hazelnut_length', wrapper).css('visibility', 'visible');
561             }
562         },
563
564         _check_click: function(e) 
565         {
566             e.stopPropagation();
567
568             var self = e.data;
569
570             // XXX this.value = key of object to be added... what about multiple keys ?
571             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
572             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
573             
574         },
575
576         _selectAll: function() 
577         {
578             // requires jQuery id
579             var uuid=this.id.split("-");
580             var oTable=$("#hazelnut-"+uuid[1]).dataTable();
581             // Function available in Hazelnut 1.9.x
582             // Filter : displayed data only
583             var filterData = oTable._('tr', {"filter":"applied"});   
584             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
585             if(filterData.length<=100){
586                 $.each(filterData, function(index, obj) {
587                     var last=$(obj).last();
588                     var key_value=unfold.get_value(last[0]);
589                     if(typeof($(last[0]).attr('checked'))=="undefined"){
590                         $.publish('selected', 'add/'+key_value);
591                     }
592                 });
593             }
594         },
595
596     });
597
598     $.plugin('Hazelnut', Hazelnut);
599
600 })(jQuery);