various cleanup
[myslice.git] / plugins / querygrid / static / js / querygrid.js
1 // -*- js-indent-tab:2 -*-
2 /**
3  * Description: display a query result in a slickgrid-powered table
4  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
5  * License: GPLv3
6  */
7
8 /* 
9  * WARNINGS
10  *
11  * This is very rough for now and not deemed working
12  * 
13  * WARNINGS
14  */
15
16 /* ongoing adaptation to slickgrid 
17    still missing are
18 . checkboxes really running properly
19 . ability to sort on columns (should be straightforward
20   IIRC this got broken when moving to dataview, see dataview doc
21 . ability to sort on the checkboxes column 
22   (e.g. have resources 'in' the slice show up first)
23   not quite clear how to do this
24 . searching
25 . filtering
26 . style improvement
27 . rendering in the sliceview - does not use up all space, 
28   this is different from the behaviour with simpleview
29 */
30
31 (function($) {
32
33     var debug=false;
34     debug=true
35     var debug_deep=false;
36 //    debug_deep=true;
37
38     var QueryGrid = Plugin.extend({
39
40         init: function(options, element) {
41             this._super(options, element);
42
43             /* Member variables */
44             // in general we expect 2 queries here
45             // query_uuid refers to a single object (typically a slice)
46             // query_all_uuid refers to a list (typically resources or users)
47             // these can return in any order so we keep track of which has been received yet
48             this.received_all_query = false;
49             this.received_query = false;
50
51 //            // We need to remember the active filter for filtering
52 //            this.filters = Array(); 
53
54             // an internal buffer for records that are 'in' and thus need to be checked 
55             this.buffered_records_to_check = [];
56
57             /* Events */
58             this.elmt().on('show', this, this.on_show);
59
60             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
61             this.object = query.object;
62
63             //// we need 2 different keys
64             // * canonical_key is the primary key as derived from metadata (typically: urn)
65             //   and is used to communicate about a given record with the other plugins
66             // * init_key is a key that both kinds of records 
67             //   (i.e. records returned by both queries) must have (typically: hrn or hostname)
68             //   in general query_all will return well populated records, but query
69             //   returns records with only the fields displayed on startup
70             var keys = manifold.metadata.get_key(this.object);
71             this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
72             // 
73             this.init_key = this.options.init_key;
74             // have init_key default to canonical_key
75             this.init_key = this.init_key || this.canonical_key;
76             // sanity check
77             if ( ! this.init_key ) messages.warning ("QueryGrid : cannot find init_key");
78             if ( ! this.canonical_key ) messages.warning ("QueryGrid : cannot find canonical_key");
79             if (debug) messages.debug("querygrid: canonical_key="+this.canonical_key+" init_key="+this.init_key);
80
81             /* Setup query and record handlers */
82             this.listen_query(options.query_uuid);
83             this.listen_query(options.query_all_uuid, 'all');
84
85             /* GUI setup and event binding */
86             this.initialize_table();
87         },
88
89         /* PLUGIN EVENTS */
90
91         on_show: function(e) {
92             var self = e.data;
93             self.redraw_table();
94         }, // on_show
95
96         /* GUI EVENTS */
97
98         /* GUI MANIPULATION */
99
100         initialize_table: function() {
101             // compute columns based on columns and hidden_columns
102             this.slick_columns = [];
103             var all_columns = this.options.columns; // .concat(this.options.hidden_columns)
104             // xxx would be helpful to support a column_renamings options arg
105             // for redefining some labels like 'network_hrn' that really are not meaningful
106             for (c in all_columns) {
107                 var column=all_columns[c];
108                 this.slick_columns.push ( {id:column, name:column, field:column, 
109                                            cssClass: "querygrid-column-"+column,
110                                            width:100, minWidth:40, });
111             }
112             var checkbox_selector = new Slick.CheckboxSelectColumn({
113                 cssClass: "slick-checkbox"
114             });
115             this.slick_columns.push(checkbox_selector.getColumnDefinition());
116
117             // xxx should be extensible from caller with this.options.slickgrid_options 
118             this.slick_options = {
119                 enableCellNavigation: false,
120                 enableColumnReorder: true,
121                 showHeaderRow: true,
122                 syncColumnCellResize: true,
123             };
124
125             this.slick_data = [];
126             this.slick_dataview = new Slick.Data.UnfoldDataView();
127 // capturing for debug
128 window.dv=this.slick_dataview;
129             var self=this;
130             this.slick_dataview.onRowCountChanged.subscribe ( function (e,args) {
131                 self.slick_grid.updateRowCount();
132                 self.slick_grid.autosizeColumns();
133                 self.slick_grid.render();
134             });
135           
136             
137             var selector="#grid-"+this.options.domid;
138             if (debug_deep) {
139                 messages.debug("slick grid selector is " + selector);
140                 for (c in this.slick_columns) {
141                     var col=this.slick_columns[c];
142                     var msg="";
143                     for (k in col) msg = msg+" col["+k+"]="+col[k];
144                     messages.debug("slick_column["+c+"]:"+msg);
145                 }
146             }
147
148             this.slick_grid = new Slick.Grid(selector, this.slick_dataview, this.slick_columns, this.slick_options);
149 //          this.slick_grid.setSelectionModel (new Slick.RowSelectionModel ({selectActiveRow: false}));
150             this.slick_grid.setSelectionModel (new Slick.UnfoldSelectionModel({selectActiveRow: false}));
151             this.slick_grid.registerPlugin (checkbox_selector);
152             // autotooltips: for showing the full column name when ellipsed
153             var auto_tooltips = new Slick.AutoTooltips ({ enableForHeaderCells: true });
154             this.slick_grid.registerPlugin (auto_tooltips);
155             
156             this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
157
158         }, // initialize_table
159
160         new_record: function(record) {
161             this.slick_data.push(record);
162         },
163
164         clear_table: function() {
165             this.slick_data=[];
166           this.slick_dataview.setItems(this.slick_data,this.init_key,this.canonical_key);
167         },
168
169         redraw_table: function() {
170             this.slick_grid.autosizeColumns();
171             this.slick_grid.render();
172         },
173
174         show_column: function(field) {
175             console.log ("querygrid.show_column not yet implemented with slickgrid - field="+field);
176         },
177
178         hide_column: function(field) {
179             console.log("querygrid.hide_column not implemented with slickgrid - field="+field);
180         },
181
182         /*************************** QUERY HANDLER ****************************/
183
184         on_filter_added: function(filter) {
185             this.filters.push(filter);
186             this.redraw_table();
187         },
188
189         on_filter_removed: function(filter) {
190             // Remove corresponding filters
191             this.filters = $.grep(this.filters, function(x) {
192                 return x != filter;
193             });
194             this.redraw_table();
195         },
196         
197         on_filter_clear: function() {
198             this.redraw_table();
199         },
200
201         on_field_added: function(field) {
202             this.show_column(field);
203         },
204
205         on_field_removed: function(field) {
206             this.hide_column(field);
207         },
208
209         on_field_clear: function() {
210             alert('QueryGrid::clear_fields() not implemented');
211         },
212
213         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
214         /*************************** ALL QUERY HANDLER ****************************/
215
216         on_all_filter_added: function(filter) {
217             // XXX
218             this.redraw_table();
219         },
220
221         on_all_filter_removed: function(filter) {
222             // XXX
223             this.redraw_table();
224         },
225         
226         on_all_filter_clear: function() {
227             // XXX
228             this.redraw_table();
229         },
230
231         on_all_field_added: function(field) {
232             this.show_column(field);
233         },
234
235         on_all_field_removed: function(field) {
236             this.hide_column(field);
237         },
238
239         on_all_field_clear: function() {
240             alert('QueryGrid::clear_fields() not implemented');
241         },
242
243
244         /*************************** RECORD HANDLER ***************************/
245
246         on_new_record: function(record) {
247             if (this.received_all_query) {
248                 // if the 'all' query has been dealt with already we may turn on the checkbox
249                 this._set_checkbox_from_record(record, true);
250             } else {
251                 // otherwise we need to remember that and do it later on
252                 if (debug) messages.debug("Remembering record to check, "+this.init_key+'='+ record[this.init_key]);
253                 this.buffered_records_to_check.push(record);
254             }
255         },
256
257         on_clear_records: function() {
258         },
259
260         // Could be the default in parent
261         on_query_in_progress: function() {
262             this.spin();
263         },
264
265         on_query_done: function() {
266             this.received_query = true;
267             // unspin once we have received both
268             if (this.received_all_query && this.received_query) {
269                 this._init_checkboxes();
270                 this.unspin();
271             }
272         },
273         
274         on_field_state_changed: function(data) {
275             switch(data.request) {
276                 case FIELD_REQUEST_ADD:
277                 case FIELD_REQUEST_ADD_RESET:
278                     this._set_checkbox_from_data(data.value, true);
279                     break;
280                 case FIELD_REQUEST_REMOVE:
281                 case FIELD_REQUEST_REMOVE_RESET:
282                     this._set_checkbox_from_data(data.value, false);
283                     break;
284                 default:
285                     break;
286             }
287         },
288
289         /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
290         // all
291         on_all_field_state_changed: function(data) {
292             switch(data.request) {
293                 case FIELD_REQUEST_ADD:
294                 case FIELD_REQUEST_ADD_RESET:
295                     this._set_checkbox_from_data(data.value, true);
296                     break;
297                 case FIELD_REQUEST_REMOVE:
298                 case FIELD_REQUEST_REMOVE_RESET:
299                     this._set_checkbox_from_data(data.value, false);
300                     break;
301                 default:
302                     break;
303             }
304         },
305
306         on_all_new_record: function(record) {
307             this.new_record(record);
308         },
309
310         on_all_clear_records: function() {
311             this.clear_table();
312
313         },
314
315         on_all_query_in_progress: function() {
316             // XXX parent
317             this.spin();
318         }, // on_all_query_in_progress
319
320         on_all_query_done: function() {
321             var start=new Date();
322             if (debug) messages.debug("1-shot initializing slickgrid content with " + this.slick_data.length + " lines");
323             // use this.init_key as the key for identifying rows
324           this.slick_dataview.setItems (this.slick_data, this.init_key,this.canonical_key);
325             var duration=new Date()-start;
326             if (debug) messages.debug("setItems " + duration + " ms");
327             if (debug_deep) {
328                 // show full contents of first row app
329                 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
330             }
331             
332             var self = this;
333             // if we've already received the slice query, we have not been able to set 
334             // checkboxes on the fly at that time (dom not yet created)
335             $.each(this.buffered_records_to_check, function(i, record) {
336                 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
337                 self._set_checkbox_from_record(record, true);
338             });
339             this.buffered_records_to_check = [];
340
341             this.received_all_query = true;
342             // unspin once we have received both
343             if (this.received_all_query && this.received_query) {
344                 this._init_checkboxes();
345                 this.unspin();
346             }
347
348         }, // on_all_query_done
349
350         /************************** PRIVATE METHODS ***************************/
351
352         _set_checkbox_from_record : function(record, checked) {
353             var init_id = record[this.init_key];
354             if (debug) messages.debug("querygrid.set_checkbox_from_record, init_id="+init_id);
355             var index = this.slick_dataview.getIdxById(init_id);
356             this._set_checkbox_from_index (index,checked);
357         },
358
359         _set_checkbox_from_data : function (id, checked) {
360             if (debug) messages.debug("querygrid.set_checkbox_from_data, id="+id);
361             // this is a local addition to mainstream dataview
362             // it's kind if slow in this first implementation (no hashing)
363             // but we should not notice that much
364             var index = this.slick_dataview.getIdxByIdKey(id,this.canonical_key);
365             this._set_checkbox_from_index (index,checked);
366         },
367
368         _set_checkbox_from_index : function (index, checked) {
369           if (index === undefined) { messages.warn("querygrid.set_checkbox - cannot find index"); return;}
370             if (checked === undefined) checked = true;
371             var selectedRows=this.slick_grid.getSelectedRows();
372             if (checked) // add index in current list
373                 selectedRows=selectedRows.concat(index);
374             else // remove index from current list
375                 selectedRows=selectedRows.filter(function(idx) {return idx!=index;});
376             // set new selection
377             this.slick_grid.setSelectedRows(selectedRows);
378         },
379
380 // initializing checkboxes
381 // have tried 2 approaches, but none seems to work as we need it
382 // issue summarized in here 
383 // http://stackoverflow.com/questions/20425193/slickgrid-selection-changed-callback-how-to-tell-between-manual-and-programmat
384         // arm the click callback on checkboxes
385         _init_checkboxes_manual : function () {
386             // xxx looks like checkboxes can only be the last column??
387             var checkbox_col = this.slick_grid.getColumns().length-1; // -1 +1 =0
388             console.log ("checkbox_col="+checkbox_col);
389             var self=this;
390             console.log ("HERE 1 with "+this.slick_dataview.getLength()+" sons");
391             for (var index=0; index < this.slick_dataview.getLength(); index++) {
392                 // retrieve key (i.e. hrn) for this line
393                 var key=this.slick_dataview.getItem(index)[this.key];
394                 // locate cell <div> for the checkbox
395                 var div=this.slick_grid.getCellNode(index,checkbox_col);
396                 if (index <=30) console.log("HERE2 div",div," index="+index+" col="+checkbox_col);
397                 // arm callback on single son of <div> that is the <input>
398                 $(div).children("input").each(function () {
399                     if (index<=30) console.log("HERE 3, index="+index+" key="+key);
400                     $(this).click(function() {self._checkbox_clicked(self,this,key);});
401                 });
402             }
403         },
404
405         // onSelectedRowsChanged will fire even when 
406         _init_checkboxes : function () {
407             console.log("_init_checkboxes");
408             var grid=this.slick_grid;
409             this.slick_grid.onSelectedRowsChanged.subscribe(function(){
410                 row_ids = grid.getSelectedRows();
411                 console.log(row_ids);
412             });
413         },
414
415         // the callback for when user clicks 
416         _checkbox_clicked: function(querygrid,input,key) {
417             // XXX this.value = key of object to be added... what about multiple keys ?
418             if (debug) messages.debug("querygrid click handler checked=" + input.checked + " key=" + key);
419             manifold.raise_event(querygrid.options.query_uuid, input.checked?SET_ADD:SET_REMOVED, key);
420             //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
421             
422         },
423
424         // xxx from this and down, probably needs further tweaks for slickgrid
425
426         _querygrid_filter: function(oSettings, aData, iDataIndex) {
427             var ret = true;
428             $.each (this.filters, function(index, filter) { 
429                 /* XXX How to manage checkbox ? */
430                 var key = filter[0]; 
431                 var op = filter[1];
432                 var value = filter[2];
433
434                 /* Determine index of key in the table columns */
435                 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
436
437                 /* Unknown key: no filtering */
438                 if (typeof(col) == 'undefined')
439                     return;
440
441                 col_value=unfold.get_value(aData[col]);
442                 /* Test whether current filter is compatible with the column */
443                 if (op == '=' || op == '==') {
444                     if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
445                         ret = false;
446                 }else if (op == '!=') {
447                     if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
448                         ret = false;
449                 } else if(op=='<') {
450                     if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
451                         ret = false;
452                 } else if(op=='>') {
453                     if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
454                         ret = false;
455                 } else if(op=='<=' || op=='≤') {
456                     if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
457                         ret = false;
458                 } else if(op=='>=' || op=='≥') {
459                     if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
460                         ret = false;
461                 }else{
462                     // How to break out of a loop ?
463                     alert("filter not supported");
464                     return false;
465                 }
466
467             });
468             return ret;
469         },
470
471         _selectAll: function() {
472             // requires jQuery id
473             var uuid=this.id.split("-");
474             var oTable=$("#querygrid-"+uuid[1]).dataTable();
475             // Function available in QueryGrid 1.9.x
476             // Filter : displayed data only
477             var filterData = oTable._('tr', {"filter":"applied"});   
478             /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */        
479             if(filterData.length<=100){
480                 $.each(filterData, function(index, obj) {
481                     var last=$(obj).last();
482                     var key_value=unfold.get_value(last[0]);
483                     if(typeof($(last[0]).attr('checked'))=="undefined"){
484                         $.publish('selected', 'add/'+key_value);
485                     }
486                 });
487             }
488         },
489
490     });
491
492     $.plugin('QueryGrid', QueryGrid);
493
494 })(jQuery);
495