fac8c72946f602ace9513245ab84590ee6306a8a
[myslice.git] / plugins / query_editor / static / js / query_editor.js
1 /**
2  * Description: QueryEditor plugin
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite
4  * License: GPLv3
5  */
6
7 // XXX TODO This plugin will be interested in changes in metadata
8 // What if we remove a filter, is it removed in the right min/max field ???
9 //  -> no on_filter_removed is not yet implemented
10 // XXX if a plugin has not declared a handler, it might become inconsistent,
11 // and the interface should either reset or disable it
12 (function($){
13
14     var QueryEditor = Plugin.extend({
15
16         event_filter_added: function(op, suffix) {
17             suffix = (typeof suffix === 'undefined') ? '' : manifold.separator + suffix;
18             var self = this;
19             return function(e, ui) {
20                 var array = self.array_from_id(e.target.id);
21                 var key   = self.field_from_id(array); // No need to remove suffix...
22
23                 // using autocomplete ui
24                 if(typeof(ui) != "undefined"){
25                     var value = ui.item.value;
26                 }else{
27                     var value = e.target.value;
28                 }
29
30                 if (value) {
31                     // XXX This should be handled by manifold
32                     //manifold.raise_event(object.options.query_uuid, FILTER_UPDATED, [key, op, value]);
33                     manifold.raise_event(self.options.query_uuid, FILTER_ADDED, [key, op, value]);
34                 } else {
35                     // XXX This should be handled by manifold
36                     manifold.raise_event(self.options.query_uuid, FILTER_REMOVED, [key, op]);
37                 }
38             }
39         },
40
41         init: function(options, element) {
42             this._super(options, element);
43             this.listen_query(options.query_uuid);
44
45             this.elts('queryeditor-auto-filter').change(this.event_filter_added('='));
46             this.elts('queryeditor-filter').change(this.event_filter_added('='));
47             this.elts('queryeditor-filter-min').change(this.event_filter_added('>'));
48             this.elts('queryeditor-filter-max').change(this.event_filter_added('<'));
49
50             var self = this;
51             this.elts('queryeditor-check').click(function() { 
52                 manifold.raise_event(self.options.query_uuid, this.checked?FIELD_ADDED:FIELD_REMOVED, this.value);
53             });
54
55             /* The following code adds an expandable column for the table
56             // XXX Why isn't it done statically ?
57             var nCloneTh = document.createElement( 'th' );
58             var nCloneTd = document.createElement( 'td' );
59             nCloneTd.innerHTML = "<span class='glyphicon glyphicon-chevron-right' style='cursor:pointer'></span>";
60             //nCloneTd.innerHTML = '<img src="/components/com_tophat/images/details_open.png">';
61             nCloneTh.innerHTML = '<b>Info</b>';
62             nCloneTd.className = "center";
63             nCloneTh.className = "center";
64             this.elmt('table thead tr').each(function() {
65                 this.insertBefore(nCloneTh, this.childNodes[0]);
66             });
67             this.elmt('table tbody tr').each(function() {
68                 this.insertBefore(nCloneTd.cloneNode( true ), this.childNodes[0]);
69             });
70             */
71          
72             // We are currently using a DataTable display, but another browsing component could be better
73             //jQuery('#'+this.options.plugin_uuid+'-table').dataTable...
74             var  metaTable = this.elmt('table').dataTable({
75 // Thierry : I'm turning off all the dataTables options for now, so that
76 // the table displays more properly again, might need more tuning though
77 //                bFilter     : false,
78 //                bPaginate   : false,
79 //                bInfo       : false,
80 //                sScrollX    : '100%',         // Horizontal scrolling
81 //                sScrollY    : '200px',
82 //                //bJQueryUI   : true,           // Use jQuery UI
83 //                bProcessing : true,           // Loading
84 //                aaSorting   : [[ 1, "asc" ]], // sort by column fields on load
85 //                aoColumnDefs: [
86 //                    { 'bSortable': false, 'aTargets': [ 0 ]},
87 //                    { 'sWidth': '8px', 'aTargets': [ 0 ] },
88 //                    { 'sWidth': '8px', 'aTargets': [ 4 ] } // XXX NB OF COLS
89 //                ]
90             });
91
92             // Actions on the newly added fields
93             this.elmt('table tbody td span').on('click', function() {
94                 var nTr = this.parentNode.parentNode;
95                 // use jQuery UI instead of images to keep a common UI
96                 // class="glyphicon glyphicon-chevron-down treeclick tree-minus"
97                 // East oriented Triangle class="glyphicon-chevron-right"
98                 // South oriented Triangle class="glyphicon-chevron-down"
99                 
100                 if (this.hasClass("glyphicon-chevron-right")) {
101                     this.removeClass("glyphicon-chevron-right").addClass("glyphicon-chevron-down");
102                     // XXX ??????
103                     metaTable.fnOpen(nTr, this.fnFormatDetails(metaTable, nTr, self.options.plugin_uuid+'_div'), 'details' );
104                 } else {
105                     this.removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-right");
106                     metaTable.fnClose(nTr);
107                 }
108             });
109
110             this.elmt('table_wrapper').css({
111                 'padding-top'   : '0em',
112                 'padding-bottom': '0em'
113             });
114             
115             // autocomplete list of tags
116             this.availableTags = {};
117
118         }, // init
119
120         /* UI management */
121
122         check_field: function(field)
123         {
124             this.elmt('check', field).attr('checked', true);
125         },
126
127         uncheck_field: function(field)
128         {
129             this.elmt('check', field).attr('checked', false);
130         },
131
132         update_filter_value: function(filter, removed)
133         {
134             removed = !(typeof removed === 'undefined'); // default = False
135
136             var key   = filter[0];
137             var op    = filter[1];
138             var value = filter[2];
139
140             var id = this.id_from_field(key);
141
142             if (op == '=') {
143                 var element = this.elmt(id);
144             } else {
145                 var suffix;
146                 if (op == '<') {
147                     this.elmt(id, 'max').val(value);
148                 } else if (op == '>') {
149                     this.elmt(id, 'min').val(value);
150                 } else {
151                     return;
152                 }
153                 var element = this.elmt(id, suffix);
154             }
155
156             element.val(removed?null:value);
157
158         },
159
160         /* Events */
161
162         on_filter_added: function(filter)
163         {
164             this.update_filter_value(filter);
165         },
166
167         on_filter_removed: function(filter)
168         {
169             this.update_filter_value(filter, true);
170         },
171
172         on_field_added: function(field)
173         {
174             console.log("on_field_added : "+field);
175             this.check_field(field);
176         },
177
178         on_field_removed: function(field)
179         {
180             this.uncheck_field(field);
181         },
182
183         /* RECORD HANDLERS */
184         on_query_done: function()
185         {
186             //console.log("Query_Editor: query_done!");
187             //console.log(this.availableTags);
188         },
189         on_new_record: function(record)
190         {
191             //console.log("Query_Editor: new_record!");
192             //console.log(record);
193             availableTags = this.availableTags;           
194             jQuery.each(record,function(key,value){
195                 value = unfold.get_value(value);
196                 if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
197                 //availableTags[key].push(value);
198                 var currentArray = availableTags[key];
199                 if(value!=null){
200                     if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
201                 }
202            });
203            this.availableTags = availableTags;
204            this.update_autocomplete(availableTags);
205         },
206
207         /* Former code not used at the moment */
208
209         print_field_description: function(field_header, div_id) 
210         { 
211             //var selected = all_headers[field_header];
212             var selected = getMetadata_field('resource',field_header);
213
214             field_header = div_id+"_"+field_header;
215
216             var output = "<div id='desc"+field_header+"'>";
217
218             output += "<div id='divinfo"+field_header+"'>";
219             output += '<p><span class="column-title">'+selected['title']+'</span></p></span>'; 
220             output += '<p><span class="column-detail">'+selected['description']+'</span></p></span>'; 
221
222             var period_select = "<select id='selectperiod"+field_header+"'><option value='Now'> Now </option><option value='latest'> Latest  </option><option value=w> Week </option><option value=m> Month </option><option value=y> Year </option></select>";
223
224             if (selected['value_type'] == 'string') {
225
226                 var values_select = "<p><select id='selectvalues"+field_header+"' MULTIPLE size=3>";
227
228                 output += '<p>Values: ';
229
230                 var values_list = selected['allowed_values'].split(",");
231
232                 for (var value_index = 0; value_index < values_list.length ; value_index++) {
233                     var value_desc = values_list[value_index].split("-");
234                     if (value_index > 0)
235                         output += ', ';
236                     output += '<span class="bold">'+value_desc[0]+'</span>';
237                     values_select += "<option value ='"+value_desc[0]+"'>&nbsp;"+value_desc[0];
238                     if (value_desc[1]!='') 
239                         output += ' ('+value_desc[1]+')';
240
241                     values_select += "&nbsp;</option>";
242                 }
243                 values_select += "</select>";
244             }
245             else
246                 output+='<p>Unit: '+selected['unit'];
247
248             output+= '</p>';
249
250             output += '<p>Source: <a class="source-url" target="source_window" href="'+selected['platform_url']+'">'+selected['platform']+'</a>';
251
252             //if (selected['via'] != '') 
253                 //output += ' via <a class="source-url" target="source_window" href="http://'+selected['via_url']+'">'+selected['via']+'</a>';
254
255             output += '</p>';
256             output += "</div>";
257
258     /*
259             output += "<div id='divgroup"+field_header+"'>";
260             output += "<p>Group resources with the same value <input type=checkbox></input>";
261             output += "<p>Select aggregator : <select><option>Count</option><option selected=true>Average</option><option>Maximum</option><option>Minimum</option></select>";
262             output += "</div>";
263             output += "<div id='divtime"+field_header+"'>";
264             output += "<p>Select timestamp : ";
265             output += period_select;
266             output += "</div>";
267     */
268             output += "</div>";
269
270             return output;
271         },
272
273         update_autocomplete: function(availableTags)
274         {
275             var self = this;
276             var domid = this.options.plugin_uuid;
277             
278             jQuery.each(availableTags, function(key, value){
279                 value.sort();
280                 jQuery("#"+domid+"__field__"+key).autocomplete({
281                             source: value,
282                             selectFirst: true,
283                             minLength: 0, // allows to browse items with no value typed in
284                             select: self.event_filter_added('=')
285                 });
286             });                
287         }, // update_autocomplete     
288
289 /*
290         update_autocomplete: function(e, rows, current_query)
291         {
292             var d = data;
293             d.current_query = current_query;
294             var availableTags={};
295             jQuery.each (rows, function(index, obj) {                    
296                 jQuery.each(obj,function(key,value){                       
297                     value = unfold.get_value(value); 
298                     if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
299                     //availableTags[key].push(value);
300                     var currentArray=availableTags[key];
301                     if(value!=null){
302                         if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
303                     }
304                 });                    
305             });
306             jQuery.each(availableTags, function(key, value){
307                 value.sort();
308                 jQuery("#"+options.plugin_uuid+"-filter-"+key).autocomplete({
309                             source: value,
310                             selectFirst: true,
311                             minLength: 0, // allows to browse items with no value typed in
312                             select: function(event, ui) {
313                                 var key=getKeySplitId(this.id,"-");
314                                 var op='=';
315                                 var val=ui.item.value;
316                                 
317                                 query=d.current_query;
318                                 query.update_filter(key,op,val);
319                                 // Publish the query changed, the other plugins with subscribe will get the changes
320                                 jQuery.publish('/query/' + query.uuid + '/changed', query);
321                                 //add_ActiveFilter(this.id,'=',ui.item.value,d);
322                             }
323                 });
324             });                
325         }, // update_autocomplete     
326 */
327         fnFormatDetails: function( metaTable, nTr, div_id ) 
328         {
329             var aData = metaTable.fnGetData( nTr );
330             var sOut = '<blockquote>';
331             //sOut += prepare_tab_description(aData[1].substr(21, aData[1].length-21-7), div_id);
332             sOut += this.print_field_description(aData[1].substring(3, aData[1].length-4), div_id);
333             sOut += '</blockquote>';
334          
335             return sOut;
336         }
337     });
338
339     $.plugin('QueryEditor', QueryEditor);
340
341 })(jQuery);