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