ResourcesSelected Plugin working with URNs - http://trac.myslice.info/ticket/36
[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                 //manifold.raise_event(self.options.query_all_uuid, FIELD_REMOVED, field);
137                 self.hide_column(field);
138             });
139         }, // initialize_table
140
141         /**
142          * @brief Determine index of key in the table columns 
143          * @param key
144          * @param cols
145          */
146         getColIndex: function(key, cols) {
147             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
148             return (tabIndex.length > 0) ? tabIndex[0] : -1;
149         }, // getColIndex
150
151         checkbox_html : function (key, value)
152         {
153             var result="";
154             // Prefix id with plugin_uuid
155             result += "<input";
156             result += " class='hazelnut-checkbox'";
157             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
158             result += " name='" + key + "'";
159             result += " type='checkbox'";
160             result += " autocomplete='off'";
161             result += " value='" + value + "'";
162             result += "></input>";
163             return result;
164         }, // checkbox
165
166
167         new_record: function(record)
168         {
169             // this models a line in dataTables, each element in the line describes a cell
170             line = new Array();
171      
172             // go through table headers to get column names we want
173             // in order (we have temporarily hack some adjustments in names)
174             var cols = this.table.fnSettings().aoColumns;
175             var colnames = cols.map(function(x) {return x.sTitle})
176             var nb_col = cols.length;
177             /* if we've requested checkboxes, then forget about the checkbox column for now */
178             if (this.options.checkboxes) nb_col -= 1;
179
180             /* fill in stuff depending on the column name */
181             for (var j = 0; j < nb_col; j++) {
182                 if (typeof colnames[j] == 'undefined') {
183                     line.push('...');
184                 } else if (colnames[j] == 'hostname') {
185                     if (record['type'] == 'resource,link')
186                         //TODO: we need to add source/destination for links
187                         line.push('');
188                     else
189                         line.push(record['hostname']);
190
191                 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
192                     line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
193                 } else {
194                     if (record[colnames[j]])
195                         line.push(record[colnames[j]]);
196                     else
197                         line.push('');
198                 }
199             }
200     
201             // catch up with the last column if checkboxes were requested 
202             if (this.options.checkboxes) {
203                 // Use a key instead of hostname (hard coded...)
204                 line.push(this.checkbox_html(this.key, record[this.key]));
205                 }
206     
207             // adding an array in one call is *much* more efficient
208                 // this.table.fnAddData(line);
209                 this.buffered_lines.push(line);
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             // function escape_id(myid) is defined in portal/static/js/common.functions.js
263             checkbox_id = escape_id(checkbox_id);
264                 // using dataTables's $ to search also in nodes that are not currently displayed
265             var element = this.table.$(checkbox_id);
266                 if (debug) messages.debug("set_checkbox checked=" + checked + " id=" + checkbox_id + " matches=" + element.length);
267             element.attr('checked', checked);
268         },
269
270         /*************************** QUERY HANDLER ****************************/
271
272         on_filter_added: function(filter)
273         {
274             // XXX
275             this.redraw_table();
276         },
277
278         on_filter_removed: function(filter)
279         {
280             // XXX
281             this.redraw_table();
282         },
283         
284         on_filter_clear: function()
285         {
286             // XXX
287             this.redraw_table();
288         },
289
290         on_field_added: function(field)
291         {
292             this.show_column(field);
293         },
294
295         on_field_removed: function(field)
296         {
297             this.hide_column(field);
298         },
299
300         on_field_clear: function()
301         {
302             alert('Hazelnut::clear_fields() not implemented');
303         },
304
305         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
306         /*************************** ALL QUERY HANDLER ****************************/
307
308         on_all_filter_added: function(filter)
309         {
310             // XXX
311             this.redraw_table();
312         },
313
314         on_all_filter_removed: function(filter)
315         {
316             // XXX
317             this.redraw_table();
318         },
319         
320         on_all_filter_clear: function()
321         {
322             // XXX
323             this.redraw_table();
324         },
325
326         on_all_field_added: function(field)
327         {
328             this.show_column(field);
329         },
330
331         on_all_field_removed: function(field)
332         {
333             this.hide_column(field);
334         },
335
336         on_all_field_clear: function()
337         {
338             alert('Hazelnut::clear_fields() not implemented');
339         },
340
341
342         /*************************** RECORD HANDLER ***************************/
343
344         on_new_record: function(record)
345         {
346             if (this.received_all_query) {
347                         // if the 'all' query has been dealt with already we may turn on the checkbox
348                         if (debug) messages.debug("turning on checkbox for record "+record[this.key]);
349                 this.set_checkbox(record, true);
350                 } else {
351                         // otherwise we need to remember that and do it later on
352                         if (debug) messages.debug("Remembering record to check " + record[this.key]);
353                 this.buffered_records_to_check.push(record);
354                 }
355         },
356
357         on_clear_records: function()
358         {
359         },
360
361         // Could be the default in parent
362         on_query_in_progress: function()
363         {
364             this.spin();
365         },
366
367         on_query_done: function()
368         {
369             this.received_query = true;
370             // unspin once we have received both
371             if (this.received_all_query && this.received_query) this.unspin();
372         },
373         
374         on_field_state_changed: function(data)
375         {
376             switch(data.request) {
377                 case FIELD_REQUEST_ADD:
378                 case FIELD_REQUEST_ADD_RESET:
379                     this.set_checkbox(data.value, true);
380                     break;
381                 case FIELD_REQUEST_REMOVE:
382                 case FIELD_REQUEST_REMOVE_RESET:
383                     this.set_checkbox(data.value, false);
384                     break;
385                 default:
386                     break;
387             }
388         },
389
390         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
391         // all
392         on_all_field_state_changed: function(data)
393         {
394             switch(data.request) {
395                 case FIELD_REQUEST_ADD:
396                 case FIELD_REQUEST_ADD_RESET:
397                     this.set_checkbox(data.value, true);
398                     break;
399                 case FIELD_REQUEST_REMOVE:
400                 case FIELD_REQUEST_REMOVE_RESET:
401                     this.set_checkbox(data.value, false);
402                     break;
403                 default:
404                     break;
405             }
406         },
407
408         on_all_new_record: function(record)
409         {
410             this.new_record(record);
411         },
412
413         on_all_clear_records: function()
414         {
415             this.clear_table();
416
417         },
418
419         on_all_query_in_progress: function()
420         {
421             // XXX parent
422             this.spin();
423         }, // on_all_query_in_progress
424
425         on_all_query_done: function()
426         {
427             if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
428             this.table.fnAddData (this.buffered_lines);
429             this.buffered_lines=[];
430             
431             var self = this;
432             // if we've already received the slice query, we have not been able to set 
433             // checkboxes on the fly at that time (dom not yet created)
434             $.each(this.buffered_records_to_check, function(i, record) {
435                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
436                 self.set_checkbox(record, true);
437             });
438             this.buffered_records_to_check = [];
439
440             this.received_all_query = true;
441             // unspin once we have received both
442             if (this.received_all_query && this.received_query) this.unspin();
443
444         }, // on_all_query_done
445
446         /************************** PRIVATE METHODS ***************************/
447
448         /** 
449          * @brief Hazelnut filtering function
450          */
451         _hazelnut_filter: function(oSettings, aData, iDataIndex)
452         {
453             var cur_query = this.current_query;
454             if (!cur_query) return true;
455             var ret = true;
456
457             /* We have an array of filters : a filter is an array (key op val) 
458              * field names (unless shortcut)    : oSettings.aoColumns  = [ sTitle ]
459              *     can we exploit the data property somewhere ?
460              * field values (unless formatting) : aData
461              *     formatting should leave original data available in a hidden field
462              *
463              * The current line should validate all filters
464              */
465             $.each (cur_query.filters, function(index, filter) { 
466                 /* XXX How to manage checkbox ? */
467                 var key = filter[0]; 
468                 var op = filter[1];
469                 var value = filter[2];
470
471                 /* Determine index of key in the table columns */
472                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
473
474                 /* Unknown key: no filtering */
475                 if (typeof(col) == 'undefined')
476                     return;
477
478                 col_value=unfold.get_value(aData[col]);
479                 /* Test whether current filter is compatible with the column */
480                 if (op == '=' || op == '==') {
481                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
482                         ret = false;
483                 }else if (op == '!=') {
484                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
485                         ret = false;
486                 } else if(op=='<') {
487                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
488                         ret = false;
489                 } else if(op=='>') {
490                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
491                         ret = false;
492                 } else if(op=='<=' || op=='≤') {
493                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
494                         ret = false;
495                 } else if(op=='>=' || op=='≥') {
496                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
497                         ret = false;
498                 }else{
499                     // How to break out of a loop ?
500                     alert("filter not supported");
501                     return false;
502                 }
503
504             });
505             return ret;
506         },
507
508         _hazelnut_draw_callback: function()
509         {
510             /* 
511              * Handle clicks on checkboxes: reassociate checkbox click every time
512              * the table is redrawn 
513              */
514             this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
515
516             if (!this.table)
517                 return;
518
519             /* Remove pagination if we show only a few results */
520             var wrapper = this.table; //.parent().parent().parent();
521             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
522             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
523             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
524
525             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
526                 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
527             } else {
528                 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
529             }
530
531             if ( rowsToShow <= minRowsPerPage ) {
532                 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
533             } else {
534                 $('.hazelnut_length', wrapper).css('visibility', 'visible');
535             }
536         },
537
538         _check_click: function(e) 
539         {
540             e.stopPropagation();
541
542             var self = e.data;
543
544             // XXX this.value = key of object to be added... what about multiple keys ?
545             if (debug) messages.debug("hazelnut click handler checked=" + this.checked + " hrn=" + this.value);
546             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
547             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
548             
549         },
550
551         _selectAll: function() 
552         {
553             // requires jQuery id
554             var uuid=this.id.split("-");
555             var oTable=$("#hazelnut-"+uuid[1]).dataTable();
556             // Function available in Hazelnut 1.9.x
557             // Filter : displayed data only
558             var filterData = oTable._('tr', {"filter":"applied"});   
559             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
560             if(filterData.length<=100){
561                 $.each(filterData, function(index, obj) {
562                     var last=$(obj).last();
563                     var key_value=unfold.get_value(last[0]);
564                     if(typeof($(last[0]).attr('checked'))=="undefined"){
565                         $.publish('selected', 'add/'+key_value);
566                     }
567                 });
568             }
569         },
570
571     });
572
573     $.plugin('Hazelnut', Hazelnut);
574
575   /* define the 'dom-checkbox' type for sorting in datatables 
576      http://datatables.net/examples/plug-ins/dom_sort.html
577      using trial and error I found that the actual column number
578      was in fact given as a third argument, and not second 
579      as the various online resources had it - go figure */
580     $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
581         return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
582             return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
583         } );
584     }
585
586 })(jQuery);
587