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