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