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