7686e194e5f66b5d0fbbdb817413046d1d337ac4
[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     var debug_deep=false;
12 //    debug_deep=true;
13
14     var QueryTable = Plugin.extend({
15
16         init: function(options, element) {
17             this._super(options, element);
18
19             /* Member variables */
20             // in general we expect 2 queries here
21             // query_uuid refers to a single object (typically a slice)
22             // query_all_uuid refers to a list (typically resources or users)
23             // these can return in any order so we keep track of which has been received yet
24             this.received_all_query = false;
25             this.received_query = false;
26
27 //            // We need to remember the active filter for datatables filtering
28 //            this.filters = Array(); 
29
30             // an internal buffer for records that are 'in' and thus need to be checked 
31             this.buffered_records_to_check = [];
32
33             /* XXX Events XXX */
34             // this.$element.on('show.Datatables', this.on_show);
35             this.elmt().on('show', this, this.on_show);
36             // Unbind all events using namespacing
37             // TODO in destructor
38             // $(window).unbind('QueryTable');
39
40             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
41             this.method = query.object;
42
43             // xxx beware that this.key needs to contain a key that all records will have
44             // in general query_all will return well populated records, but query
45             // returns records with only the fields displayed on startup. 
46             this.key = (this.options.id_key);
47             if (! this.key) {
48                 // if not specified by caller, decide from metadata
49                 var keys = manifold.metadata.get_key(this.method);
50                 this.key = (keys && keys.length == 1) ? keys[0] : null;
51             }
52             if (! this.key) messages.warning("querytable.init could not kind valid key");
53
54             if (debug) messages.debug("querytable: key="+this.key);
55
56             /* Setup query and record handlers */
57             this.listen_query(options.query_uuid);
58             this.listen_query(options.query_all_uuid, 'all');
59
60             /* GUI setup and event binding */
61             this.initialize_table();
62         },
63
64         /* PLUGIN EVENTS */
65
66         on_show: function(e) {
67             var self = e.data;
68             self.table.fnAdjustColumnSizing()
69         }, // on_show
70
71         /* GUI EVENTS */
72
73         /* GUI MANIPULATION */
74
75         initialize_table: function() {
76             // compute columns based on columns and hidden_columns
77             this.slick_columns = [];
78             var all_columns = this.options.columns; // .concat(this.options.hidden_columns)
79             for (c in all_columns) {
80                 var column=all_columns[c];
81                 this.slick_columns.push ( {id:column, name:column, field:column, width:100, minWidth:40, });
82             }
83
84             // xxx should be extensible from caller with this.options.slickgrid_options 
85             this.slick_options = {
86                 enableCellNavigation: false,
87                 enableColumnReorder: true,
88             };
89
90             this.slick_data=[];
91             
92             var selector="#grid-"+this.options.domid;
93             if (debug_deep) {
94                 messages.debug("slick grid selector is " + selector);
95                 for (c in this.slick_columns) {
96                     var col=this.slick_columns[c];
97                     var msg="";
98                     for (k in col) msg = msg+" col["+k+"]="+col[k];
99                     messages.debug("slick_column["+c+"]:"+msg);
100                 }
101             }
102             // add a checkbox column
103             var checkbox_selector = new Slick.CheckboxSelectColumn({
104                 cssClass: "slick-cell-checkboxsel"
105             });
106             this.slick_columns.push(checkbox_selector.getColumnDefinition());
107             this.slick_grid = new Slick.Grid(selector, this.slick_data, this.slick_columns, this.slick_options);
108             this.slick_grid.setSelectionModel (new Slick.RowSelectionModel ({selectActiveRow: false}));
109             this.slick_grid.registerPlugin (checkbox_selector);
110             
111             this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
112
113         }, // initialize_table
114
115         // Determine index of key in the table columns 
116         getColIndex: function(key, cols) {
117             var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
118             return (tabIndex.length > 0) ? tabIndex[0] : -1;
119         }, // getColIndex
120
121         checkbox_html : function (key, value) {
122             if (debug_deep) messages.debug("checkbox_html, value="+value);
123             var result="";
124             // Prefix id with plugin_uuid
125             result += "<input";
126             result += " class='querytable-checkbox'";
127             result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
128             result += " name='" + key + "'";
129             result += " type='checkbox'";
130             result += " autocomplete='off'";
131             if (value === undefined) {
132                 messages.warning("querytable.checkbox_html - undefined value");
133             } else {
134                 result += " value='" + value + "'";
135             }
136             result += "></input>";
137             return result;
138         }, 
139
140         new_record: function(record) {
141             this.slick_data.push(record);
142         },
143
144         clear_table: function() {
145             console.log("clear_table not implemented");
146         },
147
148         redraw_table: function() {
149             this.table.fnDraw();
150         },
151
152         show_column: function(field) {
153             var oSettings = this.table.fnSettings();
154             var cols = oSettings.aoColumns;
155             var index = this.getColIndex(field,cols);
156             if (index != -1)
157                 this.table.fnSetColumnVis(index, true);
158         },
159
160         hide_column: function(field) {
161             console.log("hide_column not implemented - field="+field);
162         },
163
164         set_checkbox: function(record, checked) {
165             console.log("set_checkbox not yet implemented with slickgrid");
166             return;
167             /* Default: checked = true */
168             if (checked === undefined) checked = true;
169
170             var id;
171             /* The function accepts both records and their key */
172             switch (manifold.get_type(record)) {
173             case TYPE_VALUE:
174                 id = record;
175                 break;
176             case TYPE_RECORD:
177                 /* XXX Test the key before ? */
178                 id = record[this.key];
179                 break;
180             default:
181                 throw "Not implemented";
182                 break;
183             }
184
185
186             if (id === undefined) {
187                 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
188                 return;
189             }
190             var checkbox_id = this.flat_id(this.id('checkbox', id));
191             // function escape_id(myid) is defined in portal/static/js/common.functions.js
192             checkbox_id = escape_id(checkbox_id);
193             // using dataTables's $ to search also in nodes that are not currently displayed
194             var element = this.table.$(checkbox_id);
195             if (debug_deep) 
196                 messages.debug("set_checkbox checked=" + checked
197                                + " id=" + checkbox_id + " matches=" + element.length);
198             element.attr('checked', checked);
199         },
200
201         /*************************** QUERY HANDLER ****************************/
202
203         on_filter_added: function(filter) {
204             this.filters.push(filter);
205             this.redraw_table();
206         },
207
208         on_filter_removed: function(filter) {
209             // Remove corresponding filters
210             this.filters = $.grep(this.filters, function(x) {
211                 return x != filter;
212             });
213             this.redraw_table();
214         },
215         
216         on_filter_clear: function() {
217             this.redraw_table();
218         },
219
220         on_field_added: function(field) {
221             this.show_column(field);
222         },
223
224         on_field_removed: function(field) {
225             this.hide_column(field);
226         },
227
228         on_field_clear: function() {
229             alert('QueryTable::clear_fields() not implemented');
230         },
231
232         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
233         /*************************** ALL QUERY HANDLER ****************************/
234
235         on_all_filter_added: function(filter) {
236             // XXX
237             this.redraw_table();
238         },
239
240         on_all_filter_removed: function(filter) {
241             // XXX
242             this.redraw_table();
243         },
244         
245         on_all_filter_clear: function() {
246             // XXX
247             this.redraw_table();
248         },
249
250         on_all_field_added: function(field) {
251             this.show_column(field);
252         },
253
254         on_all_field_removed: function(field) {
255             this.hide_column(field);
256         },
257
258         on_all_field_clear: function() {
259             alert('QueryTable::clear_fields() not implemented');
260         },
261
262
263         /*************************** RECORD HANDLER ***************************/
264
265         on_new_record: function(record) {
266             if (this.received_all_query) {
267                 // if the 'all' query has been dealt with already we may turn on the checkbox
268                 this.set_checkbox(record, true);
269             } else {
270                 // otherwise we need to remember that and do it later on
271                 if (debug) messages.debug("Remembering record to check " + record[this.key]);
272                 this.buffered_records_to_check.push(record);
273             }
274         },
275
276         on_clear_records: function() {
277         },
278
279         // Could be the default in parent
280         on_query_in_progress: function() {
281             this.spin();
282         },
283
284         on_query_done: function() {
285             this.received_query = true;
286             // unspin once we have received both
287             if (this.received_all_query && this.received_query) this.unspin();
288         },
289         
290         on_field_state_changed: function(data) {
291             switch(data.request) {
292                 case FIELD_REQUEST_ADD:
293                 case FIELD_REQUEST_ADD_RESET:
294                     this.set_checkbox(data.value, true);
295                     break;
296                 case FIELD_REQUEST_REMOVE:
297                 case FIELD_REQUEST_REMOVE_RESET:
298                     this.set_checkbox(data.value, false);
299                     break;
300                 default:
301                     break;
302             }
303         },
304
305         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
306         // all
307         on_all_field_state_changed: function(data) {
308             switch(data.request) {
309                 case FIELD_REQUEST_ADD:
310                 case FIELD_REQUEST_ADD_RESET:
311                     this.set_checkbox(data.value, true);
312                     break;
313                 case FIELD_REQUEST_REMOVE:
314                 case FIELD_REQUEST_REMOVE_RESET:
315                     this.set_checkbox(data.value, false);
316                     break;
317                 default:
318                     break;
319             }
320         },
321
322         on_all_new_record: function(record) {
323             this.new_record(record);
324         },
325
326         on_all_clear_records: function() {
327             this.clear_table();
328
329         },
330
331         on_all_query_in_progress: function() {
332             // XXX parent
333             this.spin();
334         }, // on_all_query_in_progress
335
336         on_all_query_done: function() {
337             if (debug) messages.debug("1-shot initializing dataTables content with " + this.slick_data.length + " lines");
338             var start=new Date();
339             this.slick_grid.setData (this.slick_data, true);
340             this.slick_grid.render();
341             var duration=new Date()-start;
342             if (debug) messages.debug("setData+render took " + duration + " ms");
343             if (debug_deep) {
344                 // show full contents of first row app
345                 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
346             }
347             
348             var self = this;
349             // if we've already received the slice query, we have not been able to set 
350             // checkboxes on the fly at that time (dom not yet created)
351             $.each(this.buffered_records_to_check, function(i, record) {
352                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
353                 self.set_checkbox(record, true);
354             });
355             this.buffered_records_to_check = [];
356
357             this.received_all_query = true;
358             // unspin once we have received both
359             if (this.received_all_query && this.received_query) this.unspin();
360
361         }, // on_all_query_done
362
363         /************************** PRIVATE METHODS ***************************/
364
365         /** 
366          * @brief QueryTable filtering function
367          */
368         _querytable_filter: function(oSettings, aData, iDataIndex) {
369             var ret = true;
370             $.each (this.filters, function(index, filter) { 
371                 /* XXX How to manage checkbox ? */
372                 var key = filter[0]; 
373                 var op = filter[1];
374                 var value = filter[2];
375
376                 /* Determine index of key in the table columns */
377                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
378
379                 /* Unknown key: no filtering */
380                 if (typeof(col) == 'undefined')
381                     return;
382
383                 col_value=unfold.get_value(aData[col]);
384                 /* Test whether current filter is compatible with the column */
385                 if (op == '=' || op == '==') {
386                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
387                         ret = false;
388                 }else if (op == '!=') {
389                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
390                         ret = false;
391                 } else if(op=='<') {
392                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
393                         ret = false;
394                 } else if(op=='>') {
395                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
396                         ret = false;
397                 } else if(op=='<=' || op=='≤') {
398                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
399                         ret = false;
400                 } else if(op=='>=' || op=='≥') {
401                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
402                         ret = false;
403                 }else{
404                     // How to break out of a loop ?
405                     alert("filter not supported");
406                     return false;
407                 }
408
409             });
410             return ret;
411         },
412
413         _querytable_draw_callback: function() {
414             /* 
415              * Handle clicks on checkboxes: reassociate checkbox click every time
416              * the table is redrawn 
417              */
418             this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
419
420             if (!this.table)
421                 return;
422
423             /* Remove pagination if we show only a few results */
424             var wrapper = this.table; //.parent().parent().parent();
425             var rowsPerPage = this.table.fnSettings()._iDisplayLength;
426             var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
427             var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
428
429             if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
430                 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
431             } else {
432                 $('.querytable_paginate', wrapper).css('visibility', 'visible');
433             }
434
435             if ( rowsToShow <= minRowsPerPage ) {
436                 $('.querytable_length', wrapper).css('visibility', 'hidden');
437             } else {
438                 $('.querytable_length', wrapper).css('visibility', 'visible');
439             }
440         },
441
442         _check_click: function(e) {
443             e.stopPropagation();
444
445             var self = e.data;
446
447             // XXX this.value = key of object to be added... what about multiple keys ?
448             if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
449             manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
450             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
451             
452         },
453
454         _selectAll: function() {
455             // requires jQuery id
456             var uuid=this.id.split("-");
457             var oTable=$("#querytable-"+uuid[1]).dataTable();
458             // Function available in QueryTable 1.9.x
459             // Filter : displayed data only
460             var filterData = oTable._('tr', {"filter":"applied"});   
461             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
462             if(filterData.length<=100){
463                 $.each(filterData, function(index, obj) {
464                     var last=$(obj).last();
465                     var key_value=unfold.get_value(last[0]);
466                     if(typeof($(last[0]).attr('checked'))=="undefined"){
467                         $.publish('selected', 'add/'+key_value);
468                     }
469                 });
470             }
471         },
472
473     });
474
475     $.plugin('QueryTable', QueryTable);
476
477 //  /* define the 'dom-checkbox' type for sorting in datatables 
478 //     http://datatables.net/examples/plug-ins/dom_sort.html
479 //     using trial and error I found that the actual column number
480 //     was in fact given as a third argument, and not second 
481 //     as the various online resources had it - go figure */
482 //    $.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, _, iColumn ) {
483 //      return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
484 //          return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';
485 //      } );
486 //    }
487
488 })(jQuery);
489