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