2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
14 var QueryTable = Plugin.extend({
16 init: function(options, element) {
17 this._super(options, element);
19 /* Member variables */
20 // in general we expect 2 queries here
21 // query_uuid refers to a single object (typically a slice)
22 // query_all_uuid refers to a list (typically resources or users)
23 // these can return in any order so we keep track of which has been received yet
24 this.received_all_query = false;
25 this.received_query = false;
27 // // We need to remember the active filter for datatables filtering
28 // this.filters = Array();
30 // an internal buffer for records that are 'in' and thus need to be checked
31 this.buffered_records_to_check = [];
34 // this.$element.on('show.Datatables', this.on_show);
35 this.elmt().on('show', this, this.on_show);
36 // Unbind all events using namespacing
38 // $(window).unbind('QueryTable');
40 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
41 this.method = query.object;
43 // xxx beware that this.key needs to contain a key that all records will have
44 // in general query_all will return well populated records, but query
45 // returns records with only the fields displayed on startup.
46 this.key = (this.options.id_key);
48 // if not specified by caller, decide from metadata
49 var keys = manifold.metadata.get_key(this.method);
50 this.key = (keys && keys.length == 1) ? keys[0] : null;
52 if (! this.key) messages.warning("querytable.init could not kind valid key");
54 if (debug) messages.debug("querytable: key="+this.key);
56 /* Setup query and record handlers */
57 this.listen_query(options.query_uuid);
58 this.listen_query(options.query_all_uuid, 'all');
60 /* GUI setup and event binding */
61 this.initialize_table();
66 on_show: function(e) {
68 self.table.fnAdjustColumnSizing()
73 /* GUI MANIPULATION */
75 initialize_table: function() {
76 // compute columns based on columns and hidden_columns
77 this.slick_columns = [];
78 var all_columns = this.options.columns; // .concat(this.options.hidden_columns)
79 for (c in all_columns) {
80 var column=all_columns[c];
81 this.slick_columns.push ( {id:column, name:column, field:column, width:100, minWidth:40, });
84 // xxx should be extensible from caller with this.options.slickgrid_options
85 this.slick_options = {
86 enableCellNavigation: false,
87 enableColumnReorder: true,
92 var selector="#grid-"+this.options.domid;
94 messages.debug("slick grid selector is " + selector);
95 for (c in this.slick_columns) {
96 var col=this.slick_columns[c];
98 for (k in col) msg = msg+" col["+k+"]="+col[k];
99 messages.debug("slick_column["+c+"]:"+msg);
102 // add a checkbox column
103 var checkbox_selector = new Slick.CheckboxSelectColumn({
104 cssClass: "slick-cell-checkboxsel"
106 this.slick_columns.push(checkbox_selector.getColumnDefinition());
107 this.slick_grid = new Slick.Grid(selector, this.slick_data, this.slick_columns, this.slick_options);
108 this.slick_grid.setSelectionModel (new Slick.RowSelectionModel ({selectActiveRow: false}));
109 this.slick_grid.registerPlugin (checkbox_selector);
110 // autotooltips: for showing the full column name when ellipsed
111 var auto_tooltips = new Slick.AutoTooltips ({ enableForHeaderCells: true });
112 this.slick_grid.registerPlugin (auto_tooltips);
114 this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
116 }, // initialize_table
118 // Determine index of key in the table columns
119 getColIndex: function(key, cols) {
120 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
121 return (tabIndex.length > 0) ? tabIndex[0] : -1;
124 checkbox_html : function (key, value) {
125 if (debug_deep) messages.debug("checkbox_html, value="+value);
127 // Prefix id with plugin_uuid
129 result += " class='querytable-checkbox'";
130 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
131 result += " name='" + key + "'";
132 result += " type='checkbox'";
133 result += " autocomplete='off'";
134 if (value === undefined) {
135 messages.warning("querytable.checkbox_html - undefined value");
137 result += " value='" + value + "'";
139 result += "></input>";
143 new_record: function(record) {
144 this.slick_data.push(record);
147 clear_table: function() {
148 console.log("clear_table not implemented");
151 redraw_table: function() {
155 show_column: function(field) {
156 var oSettings = this.table.fnSettings();
157 var cols = oSettings.aoColumns;
158 var index = this.getColIndex(field,cols);
160 this.table.fnSetColumnVis(index, true);
163 hide_column: function(field) {
164 console.log("hide_column not implemented - field="+field);
167 set_checkbox: function(record, checked) {
168 console.log("set_checkbox not yet implemented with slickgrid");
170 /* Default: checked = true */
171 if (checked === undefined) checked = true;
174 /* The function accepts both records and their key */
175 switch (manifold.get_type(record)) {
180 /* XXX Test the key before ? */
181 id = record[this.key];
184 throw "Not implemented";
189 if (id === undefined) {
190 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
193 var checkbox_id = this.flat_id(this.id('checkbox', id));
194 // function escape_id(myid) is defined in portal/static/js/common.functions.js
195 checkbox_id = escape_id(checkbox_id);
196 // using dataTables's $ to search also in nodes that are not currently displayed
197 var element = this.table.$(checkbox_id);
199 messages.debug("set_checkbox checked=" + checked
200 + " id=" + checkbox_id + " matches=" + element.length);
201 element.attr('checked', checked);
204 /*************************** QUERY HANDLER ****************************/
206 on_filter_added: function(filter) {
207 this.filters.push(filter);
211 on_filter_removed: function(filter) {
212 // Remove corresponding filters
213 this.filters = $.grep(this.filters, function(x) {
219 on_filter_clear: function() {
223 on_field_added: function(field) {
224 this.show_column(field);
227 on_field_removed: function(field) {
228 this.hide_column(field);
231 on_field_clear: function() {
232 alert('QueryTable::clear_fields() not implemented');
235 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
236 /*************************** ALL QUERY HANDLER ****************************/
238 on_all_filter_added: function(filter) {
243 on_all_filter_removed: function(filter) {
248 on_all_filter_clear: function() {
253 on_all_field_added: function(field) {
254 this.show_column(field);
257 on_all_field_removed: function(field) {
258 this.hide_column(field);
261 on_all_field_clear: function() {
262 alert('QueryTable::clear_fields() not implemented');
266 /*************************** RECORD HANDLER ***************************/
268 on_new_record: function(record) {
269 if (this.received_all_query) {
270 // if the 'all' query has been dealt with already we may turn on the checkbox
271 this.set_checkbox(record, true);
273 // otherwise we need to remember that and do it later on
274 if (debug) messages.debug("Remembering record to check " + record[this.key]);
275 this.buffered_records_to_check.push(record);
279 on_clear_records: function() {
282 // Could be the default in parent
283 on_query_in_progress: function() {
287 on_query_done: function() {
288 this.received_query = true;
289 // unspin once we have received both
290 if (this.received_all_query && this.received_query) this.unspin();
293 on_field_state_changed: function(data) {
294 switch(data.request) {
295 case FIELD_REQUEST_ADD:
296 case FIELD_REQUEST_ADD_RESET:
297 this.set_checkbox(data.value, true);
299 case FIELD_REQUEST_REMOVE:
300 case FIELD_REQUEST_REMOVE_RESET:
301 this.set_checkbox(data.value, false);
308 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
310 on_all_field_state_changed: function(data) {
311 switch(data.request) {
312 case FIELD_REQUEST_ADD:
313 case FIELD_REQUEST_ADD_RESET:
314 this.set_checkbox(data.value, true);
316 case FIELD_REQUEST_REMOVE:
317 case FIELD_REQUEST_REMOVE_RESET:
318 this.set_checkbox(data.value, false);
325 on_all_new_record: function(record) {
326 this.new_record(record);
329 on_all_clear_records: function() {
334 on_all_query_in_progress: function() {
337 }, // on_all_query_in_progress
339 on_all_query_done: function() {
340 if (debug) messages.debug("1-shot initializing dataTables content with " + this.slick_data.length + " lines");
341 var start=new Date();
342 this.slick_grid.setData (this.slick_data, true);
343 this.slick_grid.render();
344 var duration=new Date()-start;
345 if (debug) messages.debug("setData+render took " + duration + " ms");
347 // show full contents of first row app
348 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
352 // if we've already received the slice query, we have not been able to set
353 // checkboxes on the fly at that time (dom not yet created)
354 $.each(this.buffered_records_to_check, function(i, record) {
355 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
356 self.set_checkbox(record, true);
358 this.buffered_records_to_check = [];
360 this.received_all_query = true;
361 // unspin once we have received both
362 if (this.received_all_query && this.received_query) this.unspin();
364 }, // on_all_query_done
366 /************************** PRIVATE METHODS ***************************/
369 * @brief QueryTable filtering function
371 _querytable_filter: function(oSettings, aData, iDataIndex) {
373 $.each (this.filters, function(index, filter) {
374 /* XXX How to manage checkbox ? */
377 var value = filter[2];
379 /* Determine index of key in the table columns */
380 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
382 /* Unknown key: no filtering */
383 if (typeof(col) == 'undefined')
386 col_value=unfold.get_value(aData[col]);
387 /* Test whether current filter is compatible with the column */
388 if (op == '=' || op == '==') {
389 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
391 }else if (op == '!=') {
392 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
395 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
398 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
400 } else if(op=='<=' || op=='≤') {
401 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
403 } else if(op=='>=' || op=='≥') {
404 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
407 // How to break out of a loop ?
408 alert("filter not supported");
416 _querytable_draw_callback: function() {
418 * Handle clicks on checkboxes: reassociate checkbox click every time
419 * the table is redrawn
421 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
426 /* Remove pagination if we show only a few results */
427 var wrapper = this.table; //.parent().parent().parent();
428 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
429 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
430 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
432 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
433 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
435 $('.querytable_paginate', wrapper).css('visibility', 'visible');
438 if ( rowsToShow <= minRowsPerPage ) {
439 $('.querytable_length', wrapper).css('visibility', 'hidden');
441 $('.querytable_length', wrapper).css('visibility', 'visible');
445 _check_click: function(e) {
450 // XXX this.value = key of object to be added... what about multiple keys ?
451 if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
452 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
453 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
457 _selectAll: function() {
458 // requires jQuery id
459 var uuid=this.id.split("-");
460 var oTable=$("#querytable-"+uuid[1]).dataTable();
461 // Function available in QueryTable 1.9.x
462 // Filter : displayed data only
463 var filterData = oTable._('tr', {"filter":"applied"});
464 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
465 if(filterData.length<=100){
466 $.each(filterData, function(index, obj) {
467 var last=$(obj).last();
468 var key_value=unfold.get_value(last[0]);
469 if(typeof($(last[0]).attr('checked'))=="undefined"){
470 $.publish('selected', 'add/'+key_value);
478 $.plugin('QueryTable', QueryTable);
480 // /* define the 'dom-checkbox' type for sorting in datatables
481 // http://datatables.net/examples/plug-ins/dom_sort.html
482 // using trial and error I found that the actual column number
483 // was in fact given as a third argument, and not second
484 // as the various online resources had it - go figure */
485 // $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
486 // return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
487 // return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';