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