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);
111 this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
113 }, // initialize_table
115 // Determine index of key in the table columns
116 getColIndex: function(key, cols) {
117 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
118 return (tabIndex.length > 0) ? tabIndex[0] : -1;
121 checkbox_html : function (key, value) {
122 if (debug_deep) messages.debug("checkbox_html, value="+value);
124 // Prefix id with plugin_uuid
126 result += " class='querytable-checkbox'";
127 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
128 result += " name='" + key + "'";
129 result += " type='checkbox'";
130 result += " autocomplete='off'";
131 if (value === undefined) {
132 messages.warning("querytable.checkbox_html - undefined value");
134 result += " value='" + value + "'";
136 result += "></input>";
140 new_record: function(record) {
141 this.slick_data.push(record);
144 clear_table: function() {
145 console.log("clear_table not implemented");
148 redraw_table: function() {
152 show_column: function(field) {
153 var oSettings = this.table.fnSettings();
154 var cols = oSettings.aoColumns;
155 var index = this.getColIndex(field,cols);
157 this.table.fnSetColumnVis(index, true);
160 hide_column: function(field) {
161 console.log("hide_column not implemented - field="+field);
164 set_checkbox: function(record, checked) {
165 console.log("set_checkbox not yet implemented with slickgrid");
167 /* Default: checked = true */
168 if (checked === undefined) checked = true;
171 /* The function accepts both records and their key */
172 switch (manifold.get_type(record)) {
177 /* XXX Test the key before ? */
178 id = record[this.key];
181 throw "Not implemented";
186 if (id === undefined) {
187 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
190 var checkbox_id = this.flat_id(this.id('checkbox', id));
191 // function escape_id(myid) is defined in portal/static/js/common.functions.js
192 checkbox_id = escape_id(checkbox_id);
193 // using dataTables's $ to search also in nodes that are not currently displayed
194 var element = this.table.$(checkbox_id);
196 messages.debug("set_checkbox checked=" + checked
197 + " id=" + checkbox_id + " matches=" + element.length);
198 element.attr('checked', checked);
201 /*************************** QUERY HANDLER ****************************/
203 on_filter_added: function(filter) {
204 this.filters.push(filter);
208 on_filter_removed: function(filter) {
209 // Remove corresponding filters
210 this.filters = $.grep(this.filters, function(x) {
216 on_filter_clear: function() {
220 on_field_added: function(field) {
221 this.show_column(field);
224 on_field_removed: function(field) {
225 this.hide_column(field);
228 on_field_clear: function() {
229 alert('QueryTable::clear_fields() not implemented');
232 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
233 /*************************** ALL QUERY HANDLER ****************************/
235 on_all_filter_added: function(filter) {
240 on_all_filter_removed: function(filter) {
245 on_all_filter_clear: function() {
250 on_all_field_added: function(field) {
251 this.show_column(field);
254 on_all_field_removed: function(field) {
255 this.hide_column(field);
258 on_all_field_clear: function() {
259 alert('QueryTable::clear_fields() not implemented');
263 /*************************** RECORD HANDLER ***************************/
265 on_new_record: function(record) {
266 if (this.received_all_query) {
267 // if the 'all' query has been dealt with already we may turn on the checkbox
268 this.set_checkbox(record, true);
270 // otherwise we need to remember that and do it later on
271 if (debug) messages.debug("Remembering record to check " + record[this.key]);
272 this.buffered_records_to_check.push(record);
276 on_clear_records: function() {
279 // Could be the default in parent
280 on_query_in_progress: function() {
284 on_query_done: function() {
285 this.received_query = true;
286 // unspin once we have received both
287 if (this.received_all_query && this.received_query) this.unspin();
290 on_field_state_changed: function(data) {
291 switch(data.request) {
292 case FIELD_REQUEST_ADD:
293 case FIELD_REQUEST_ADD_RESET:
294 this.set_checkbox(data.value, true);
296 case FIELD_REQUEST_REMOVE:
297 case FIELD_REQUEST_REMOVE_RESET:
298 this.set_checkbox(data.value, false);
305 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
307 on_all_field_state_changed: function(data) {
308 switch(data.request) {
309 case FIELD_REQUEST_ADD:
310 case FIELD_REQUEST_ADD_RESET:
311 this.set_checkbox(data.value, true);
313 case FIELD_REQUEST_REMOVE:
314 case FIELD_REQUEST_REMOVE_RESET:
315 this.set_checkbox(data.value, false);
322 on_all_new_record: function(record) {
323 this.new_record(record);
326 on_all_clear_records: function() {
331 on_all_query_in_progress: function() {
334 }, // on_all_query_in_progress
336 on_all_query_done: function() {
337 if (debug) messages.debug("1-shot initializing dataTables content with " + this.slick_data.length + " lines");
338 var start=new Date();
339 this.slick_grid.setData (this.slick_data, true);
340 this.slick_grid.render();
341 var duration=new Date()-start;
342 if (debug) messages.debug("setData+render took " + duration + " ms");
344 // show full contents of first row app
345 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
349 // if we've already received the slice query, we have not been able to set
350 // checkboxes on the fly at that time (dom not yet created)
351 $.each(this.buffered_records_to_check, function(i, record) {
352 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
353 self.set_checkbox(record, true);
355 this.buffered_records_to_check = [];
357 this.received_all_query = true;
358 // unspin once we have received both
359 if (this.received_all_query && this.received_query) this.unspin();
361 }, // on_all_query_done
363 /************************** PRIVATE METHODS ***************************/
366 * @brief QueryTable filtering function
368 _querytable_filter: function(oSettings, aData, iDataIndex) {
370 $.each (this.filters, function(index, filter) {
371 /* XXX How to manage checkbox ? */
374 var value = filter[2];
376 /* Determine index of key in the table columns */
377 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
379 /* Unknown key: no filtering */
380 if (typeof(col) == 'undefined')
383 col_value=unfold.get_value(aData[col]);
384 /* Test whether current filter is compatible with the column */
385 if (op == '=' || op == '==') {
386 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
388 }else if (op == '!=') {
389 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
392 if ( parseFloat(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")
397 } else if(op=='<=' || op=='≤') {
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")
404 // How to break out of a loop ?
405 alert("filter not supported");
413 _querytable_draw_callback: function() {
415 * Handle clicks on checkboxes: reassociate checkbox click every time
416 * the table is redrawn
418 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
423 /* Remove pagination if we show only a few results */
424 var wrapper = this.table; //.parent().parent().parent();
425 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
426 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
427 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
429 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
430 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
432 $('.querytable_paginate', wrapper).css('visibility', 'visible');
435 if ( rowsToShow <= minRowsPerPage ) {
436 $('.querytable_length', wrapper).css('visibility', 'hidden');
438 $('.querytable_length', wrapper).css('visibility', 'visible');
442 _check_click: function(e) {
447 // XXX this.value = key of object to be added... what about multiple keys ?
448 if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
449 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
450 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
454 _selectAll: function() {
455 // requires jQuery id
456 var uuid=this.id.split("-");
457 var oTable=$("#querytable-"+uuid[1]).dataTable();
458 // Function available in QueryTable 1.9.x
459 // Filter : displayed data only
460 var filterData = oTable._('tr', {"filter":"applied"});
461 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
462 if(filterData.length<=100){
463 $.each(filterData, function(index, obj) {
464 var last=$(obj).last();
465 var key_value=unfold.get_value(last[0]);
466 if(typeof($(last[0]).attr('checked'))=="undefined"){
467 $.publish('selected', 'add/'+key_value);
475 $.plugin('QueryTable', QueryTable);
477 // /* define the 'dom-checkbox' type for sorting in datatables
478 // http://datatables.net/examples/plug-ins/dom_sort.html
479 // using trial and error I found that the actual column number
480 // was in fact given as a third argument, and not second
481 // as the various online resources had it - go figure */
482 // $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
483 // return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
484 // return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';