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