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