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