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