global helper functions need to have grep-able names, i.e. a little bit longer
[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) {
20                 var array = self.array_from_id(e.target.id);
21                 var key   = self.field_from_id(array); // No need to remove suffix...
22                 var value = e.target.value;
23
24                 if (value) {
25                     // XXX This should be handled by manifold
26                     //manifold.raise_event(object.options.query_uuid, FILTER_UPDATED, [key, op, value]);
27                     manifold.raise_event(self.options.query_uuid, FILTER_ADDED, [key, op, value]);
28                 } else {
29                     // XXX This should be handled by manifold
30                     manifold.raise_event(self.options.query_uuid, FILTER_REMOVED, [key, op]);
31                 }
32             }
33         },
34
35         init: function(options, element) {
36             this._super(options, element);
37
38             this.listen_query(options.query_uuid);
39
40             this.elts('queryeditor-auto-filter').change(this.event_filter_added('='));
41             this.elts('queryeditor-filter').change(this.event_filter_added('='));
42             this.elts('queryeditor-filter-min').change(this.event_filter_added('>'));
43             this.elts('queryeditor-filter-max').change(this.event_filter_added('<'));
44
45             var self = this;
46             this.elts('queryeditor-check').click(function() { 
47                 manifold.raise_event(self.options.query_uuid, this.checked?FIELD_ADDED:FIELD_REMOVED, this.value);
48             });
49
50             /* The following code adds an expandable column for the table
51             // XXX Why isn't it done statically ?
52             var nCloneTh = document.createElement( 'th' );
53             var nCloneTd = document.createElement( 'td' );
54             nCloneTd.innerHTML = "<span class='ui-icon ui-icon-triangle-1-e' style='cursor:pointer'></span>";
55             //nCloneTd.innerHTML = '<img src="/components/com_tophat/images/details_open.png">';
56             nCloneTh.innerHTML = '<b>Info</b>';
57             nCloneTd.className = "center";
58             nCloneTh.className = "center";
59             this.el('table thead tr').each(function() {
60                 this.insertBefore(nCloneTh, this.childNodes[0]);
61             });
62             this.el('table tbody tr').each(function() {
63                 this.insertBefore(nCloneTd.cloneNode( true ), this.childNodes[0]);
64             });
65             */
66          
67             // We are currently using a DataTable display, but another browsing component could be better
68             //jQuery('#'+this.options.plugin_uuid+'-table').dataTable...
69             var  metaTable = this.el('table').dataTable({
70                 bFilter     : false,
71                 bPaginate   : false,
72                 bInfo       : false,
73                 sScrollX    : '100%',         // Horizontal scrolling
74                 sScrollY    : '200px',
75                 //bJQueryUI   : true,           // Use jQuery UI
76                 bProcessing : true,           // Loading
77                 aaSorting   : [[ 1, "asc" ]], // sort by column fields on load
78                 aoColumnDefs: [
79                     { 'bSortable': false, 'aTargets': [ 0 ]},
80                     { 'sWidth': '8px', 'aTargets': [ 0 ] },
81                     { 'sWidth': '8px', 'aTargets': [ 4 ] } // XXX NB OF COLS
82                 ]
83             });
84
85             var self = this;
86             // Actions on the newly added fields
87             this.el('table tbody td span').on('click', function() {
88                 var nTr = this.parentNode.parentNode;
89                 // use jQuery UI instead of images to keep a common UI
90                 // class="ui-icon treeclick ui-icon-triangle-1-s tree-minus"
91                 // East oriented Triangle class="ui-icon-triangle-1-e"
92                 // South oriented Triangle class="ui-icon-triangle-1-s"
93                 
94                 if (this.className=="ui-icon ui-icon-triangle-1-e") {
95                     this.removeClass("ui-icon-triangle-1-e").addClass("ui-icon-triangle-1-s");
96                     // XXX ??????
97                     metaTable.fnOpen(nTr, this.fnFormatDetails(metaTable, nTr, self.options.plugin_uuid+'_div'), 'details' );
98                 } else {
99                     this.removeClass("ui-icon-triangle-1-s").addClass("ui-icon-triangle-1-e");
100                     metaTable.fnClose(nTr);
101                 }
102             });
103
104             this.el('table_wrapper').css({
105                 'padding-top'   : '0em',
106                 'padding-bottom': '0em'
107             });
108
109         }, // init
110
111         /* UI management */
112
113         check_field: function(field)
114         {
115             this.el('check', field).attr('checked', true);
116         },
117
118         uncheck_field: function(field)
119         {
120             this.el('check', field).attr('checked', false);
121         },
122
123         update_filter_value: function(filter, removed)
124         {
125             removed = !(typeof removed === 'undefined'); // default = False
126
127             var key   = filter[0];
128             var op    = filter[1];
129             var value = filter[2];
130
131             var id = this.id_from_field(key);
132
133             if (op == '=') {
134                 var element = this.el(id);
135             } else {
136                 var suffix;
137                 if (op == '<') {
138                     this.el(id, 'max').val(value);
139                 } else if (op == '>') {
140                     this.el(id, 'min').val(value);
141                 } else {
142                     return;
143                 }
144                 var element = this.el(id, suffix);
145             }
146
147             element.val(removed?null:value);
148
149         },
150
151         /* Events */
152
153         on_filter_added: function(filter)
154         {
155             this.update_filter_value(filter);
156         },
157
158         on_filter_removed: function(filter)
159         {
160             this.update_filter_value(filter, true);
161         },
162
163         on_field_added: function(field)
164         {
165             this.check_field(field);
166         },
167
168         on_field_removed: function(field)
169         {
170             this.uncheck_field(field);
171         },
172
173         /* Former code not used at the moment */
174
175         print_field_description: function(field_header, div_id) 
176         { 
177             //var selected = all_headers[field_header];
178             var selected = getMetadata_field('resource',field_header);
179
180             field_header = div_id+"_"+field_header;
181
182             var output = "<div id='desc"+field_header+"'>";
183
184             output += "<div id='divinfo"+field_header+"'>";
185             output += '<p><span class="column-title">'+selected['title']+'</span></p></span>'; 
186             output += '<p><span class="column-detail">'+selected['description']+'</span></p></span>'; 
187
188             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>";
189
190             if (selected['value_type'] == 'string') {
191
192                 var values_select = "<p><select id='selectvalues"+field_header+"' MULTIPLE size=3>";
193
194                 output += '<p>Values: ';
195
196                 var values_list = selected['allowed_values'].split(",");
197
198                 for (var value_index = 0; value_index < values_list.length ; value_index++) {
199                     var value_desc = values_list[value_index].split("-");
200                     if (value_index > 0)
201                         output += ', ';
202                     output += '<span class="bold">'+value_desc[0]+'</span>';
203                     values_select += "<option value ='"+value_desc[0]+"'>&nbsp;"+value_desc[0];
204                     if (value_desc[1]!='') 
205                         output += ' ('+value_desc[1]+')';
206
207                     values_select += "&nbsp;</option>";
208                 }
209                 values_select += "</select>";
210             }
211             else
212                 output+='<p>Unit: '+selected['unit'];
213
214             output+= '</p>';
215
216             output += '<p>Source: <a class="source-url" target="source_window" href="'+selected['platform_url']+'">'+selected['platform']+'</a>';
217
218             //if (selected['via'] != '') 
219                 //output += ' via <a class="source-url" target="source_window" href="http://'+selected['via_url']+'">'+selected['via']+'</a>';
220
221             output += '</p>';
222             output += "</div>";
223
224     /*
225             output += "<div id='divgroup"+field_header+"'>";
226             output += "<p>Group resources with the same value <input type=checkbox></input>";
227             output += "<p>Select aggregator : <select><option>Count</option><option selected=true>Average</option><option>Maximum</option><option>Minimum</option></select>";
228             output += "</div>";
229             output += "<div id='divtime"+field_header+"'>";
230             output += "<p>Select timestamp : ";
231             output += period_select;
232             output += "</div>";
233     */
234             output += "</div>";
235
236             return output;
237         },
238
239         update_autocomplete: function(e, rows, current_query)
240         {
241             var d = data;
242             d.current_query = current_query;
243             var availableTags={};
244             jQuery.each (rows, function(index, obj) {                    
245                 jQuery.each(obj,function(key,value){                       
246                     value = get_value(value); 
247                     if(!availableTags.hasOwnProperty(key)){availableTags[key]=new Array();}
248                     //availableTags[key].push(value);
249                     var currentArray=availableTags[key];
250                     if(value!=null){
251                         if(jQuery.inArray(value,currentArray)==-1){availableTags[key].push(value);}
252                     }
253                 });                    
254             });
255             jQuery.each(availableTags, function(key, value){
256                 value.sort();
257                 jQuery("#"+options.plugin_uuid+"-filter-"+key).autocomplete({
258                             source: value,
259                             selectFirst: true,
260                             minLength: 0, // allows to browse items with no value typed in
261                             select: function(event, ui) {
262                                 var key=getKeySplitId(this.id,"-");
263                                 var op='=';
264                                 var val=ui.item.value;
265                                 
266                                 query=d.current_query;
267                                 query.update_filter(key,op,val);
268                                 // Publish the query changed, the other plugins with subscribe will get the changes
269                                 jQuery.publish('/query/' + query.uuid + '/changed', query);
270                                 //add_ActiveFilter(this.id,'=',ui.item.value,d);
271                             }
272                 });
273             });                
274         }, // update_autocomplete     
275
276         fnFormatDetails: function( metaTable, nTr, div_id ) 
277         {
278             var aData = metaTable.fnGetData( nTr );
279             var sOut = '<blockquote>';
280             //sOut += prepare_tab_description(aData[1].substr(21, aData[1].length-21-7), div_id);
281             sOut += this.print_field_description(aData[1].substring(3, aData[1].length-4), div_id);
282             sOut += '</blockquote>';
283          
284             return sOut;
285         }
286     });
287
288     $.plugin('QueryEditor', QueryEditor);
289
290 })(jQuery);