js helper function 'get_value' not defined globally anymore, use unfold.get_velue...
[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='ui-icon ui-icon-triangle-1-e' 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                 bFilter     : false,
76                 bPaginate   : false,
77                 bInfo       : false,
78                 sScrollX    : '100%',         // Horizontal scrolling
79                 sScrollY    : '200px',
80                 //bJQueryUI   : true,           // Use jQuery UI
81                 bProcessing : true,           // Loading
82                 aaSorting   : [[ 1, "asc" ]], // sort by column fields on load
83                 aoColumnDefs: [
84                     { 'bSortable': false, 'aTargets': [ 0 ]},
85                     { 'sWidth': '8px', 'aTargets': [ 0 ] },
86                     { 'sWidth': '8px', 'aTargets': [ 4 ] } // XXX NB OF COLS
87                 ]
88             });
89
90             // Actions on the newly added fields
91             this.elmt('table tbody td span').on('click', function() {
92                 var nTr = this.parentNode.parentNode;
93                 // use jQuery UI instead of images to keep a common UI
94                 // class="ui-icon treeclick ui-icon-triangle-1-s tree-minus"
95                 // East oriented Triangle class="ui-icon-triangle-1-e"
96                 // South oriented Triangle class="ui-icon-triangle-1-s"
97                 
98                 if (this.className=="ui-icon ui-icon-triangle-1-e") {
99                     this.removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
100                     // XXX ??????
101                     metaTable.fnOpen(nTr, this.fnFormatDetails(metaTable, nTr, self.options.plugin_uuid+'_div'), 'details' );
102                 } else {
103                     this.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
104                     metaTable.fnClose(nTr);
105                 }
106             });
107
108             this.elmt('table_wrapper').css({
109                 'padding-top'   : '0em',
110                 'padding-bottom': '0em'
111             });
112             
113             // autocomplete list of tags
114             this.availableTags = {};
115
116         }, // init
117
118         /* UI management */
119
120         check_field: function(field)
121         {
122             this.elmt('check', field).attr('checked', true);
123         },
124
125         uncheck_field: function(field)
126         {
127             this.elmt('check', field).attr('checked', false);
128         },
129
130         update_filter_value: function(filter, removed)
131         {
132             removed = !(typeof removed === 'undefined'); // default = False
133
134             var key   = filter[0];
135             var op    = filter[1];
136             var value = filter[2];
137
138             var id = this.id_from_field(key);
139
140             if (op == '=') {
141                 var element = this.elmt(id);
142             } else {
143                 var suffix;
144                 if (op == '<') {
145                     this.elmt(id, 'max').val(value);
146                 } else if (op == '>') {
147                     this.elmt(id, 'min').val(value);
148                 } else {
149                     return;
150                 }
151                 var element = this.elmt(id, suffix);
152             }
153
154             element.val(removed?null:value);
155
156         },
157
158         /* Events */
159
160         on_filter_added: function(filter)
161         {
162             this.update_filter_value(filter);
163         },
164
165         on_filter_removed: function(filter)
166         {
167             this.update_filter_value(filter, true);
168         },
169
170         on_field_added: function(field)
171         {
172             console.log("on_field_added : "+field);
173             this.check_field(field);
174         },
175
176         on_field_removed: function(field)
177         {
178             this.uncheck_field(field);
179         },
180
181         /* RECORD HANDLERS */
182         on_query_done: function()
183         {
184             //console.log("Query_Editor: query_done!");
185             //console.log(this.availableTags);
186         },
187         on_new_record: function(record)
188         {
189             //console.log("Query_Editor: new_record!");
190             //console.log(record);
191             availableTags = this.availableTags;           
192             jQuery.each(record,function(key,value){
193                 value = unfold.get_value(value);
194                 if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
195                 //availableTags[key].push(value);
196                 var currentArray = availableTags[key];
197                 if(value!=null){
198                     if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
199                 }
200            });
201            this.availableTags = availableTags;
202            this.update_autocomplete(availableTags);
203         },
204
205         /* Former code not used at the moment */
206
207         print_field_description: function(field_header, div_id) 
208         { 
209             //var selected = all_headers[field_header];
210             var selected = getMetadata_field('resource',field_header);
211
212             field_header = div_id+"_"+field_header;
213
214             var output = "<div id='desc"+field_header+"'>";
215
216             output += "<div id='divinfo"+field_header+"'>";
217             output += '<p><span class="column-title">'+selected['title']+'</span></p></span>'; 
218             output += '<p><span class="column-detail">'+selected['description']+'</span></p></span>'; 
219
220             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>";
221
222             if (selected['value_type'] == 'string') {
223
224                 var values_select = "<p><select id='selectvalues"+field_header+"' MULTIPLE size=3>";
225
226                 output += '<p>Values: ';
227
228                 var values_list = selected['allowed_values'].split(",");
229
230                 for (var value_index = 0; value_index < values_list.length ; value_index++) {
231                     var value_desc = values_list[value_index].split("-");
232                     if (value_index > 0)
233                         output += ', ';
234                     output += '<span class="bold">'+value_desc[0]+'</span>';
235                     values_select += "<option value ='"+value_desc[0]+"'>&nbsp;"+value_desc[0];
236                     if (value_desc[1]!='') 
237                         output += ' ('+value_desc[1]+')';
238
239                     values_select += "&nbsp;</option>";
240                 }
241                 values_select += "</select>";
242             }
243             else
244                 output+='<p>Unit: '+selected['unit'];
245
246             output+= '</p>';
247
248             output += '<p>Source: <a class="source-url" target="source_window" href="'+selected['platform_url']+'">'+selected['platform']+'</a>';
249
250             //if (selected['via'] != '') 
251                 //output += ' via <a class="source-url" target="source_window" href="http://'+selected['via_url']+'">'+selected['via']+'</a>';
252
253             output += '</p>';
254             output += "</div>";
255
256     /*
257             output += "<div id='divgroup"+field_header+"'>";
258             output += "<p>Group resources with the same value <input type=checkbox></input>";
259             output += "<p>Select aggregator : <select><option>Count</option><option selected=true>Average</option><option>Maximum</option><option>Minimum</option></select>";
260             output += "</div>";
261             output += "<div id='divtime"+field_header+"'>";
262             output += "<p>Select timestamp : ";
263             output += period_select;
264             output += "</div>";
265     */
266             output += "</div>";
267
268             return output;
269         },
270
271         update_autocomplete: function(availableTags)
272         {
273             var self = this;
274             var domid = this.options.plugin_uuid;
275             
276             jQuery.each(availableTags, function(key, value){
277                 value.sort();
278                 jQuery("#"+domid+"__field__"+key).autocomplete({
279                             source: value,
280                             selectFirst: true,
281                             minLength: 0, // allows to browse items with no value typed in
282                             select: self.event_filter_added('=')
283                 });
284             });                
285         }, // update_autocomplete     
286
287 /*
288         update_autocomplete: function(e, rows, current_query)
289         {
290             var d = data;
291             d.current_query = current_query;
292             var availableTags={};
293             jQuery.each (rows, function(index, obj) {                    
294                 jQuery.each(obj,function(key,value){                       
295                     value = unfold.get_value(value); 
296                     if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
297                     //availableTags[key].push(value);
298                     var currentArray=availableTags[key];
299                     if(value!=null){
300                         if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
301                     }
302                 });                    
303             });
304             jQuery.each(availableTags, function(key, value){
305                 value.sort();
306                 jQuery("#"+options.plugin_uuid+"-filter-"+key).autocomplete({
307                             source: value,
308                             selectFirst: true,
309                             minLength: 0, // allows to browse items with no value typed in
310                             select: function(event, ui) {
311                                 var key=getKeySplitId(this.id,"-");
312                                 var op='=';
313                                 var val=ui.item.value;
314                                 
315                                 query=d.current_query;
316                                 query.update_filter(key,op,val);
317                                 // Publish the query changed, the other plugins with subscribe will get the changes
318                                 jQuery.publish('/query/' + query.uuid + '/changed', query);
319                                 //add_ActiveFilter(this.id,'=',ui.item.value,d);
320                             }
321                 });
322             });                
323         }, // update_autocomplete     
324 */
325         fnFormatDetails: function( metaTable, nTr, div_id ) 
326         {
327             var aData = metaTable.fnGetData( nTr );
328             var sOut = '<blockquote>';
329             //sOut += prepare_tab_description(aData[1].substr(21, aData[1].length-21-7), div_id);
330             sOut += this.print_field_description(aData[1].substring(3, aData[1].length-4), div_id);
331             sOut += '</blockquote>';
332          
333             return sOut;
334         }
335     });
336
337     $.plugin('QueryEditor', QueryEditor);
338
339 })(jQuery);