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