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,
88 explicitInitialization: true,
93 var selector="#grid-"+this.options.domid;
95 messages.debug("slick grid selector is " + selector);
96 for (c in this.slick_columns) {
97 var col=this.slick_columns[c];
99 for (k in col) msg = msg+" col["+k+"]="+col[k];
100 messages.debug("slick_column["+c+"]:"+msg);
103 // add a checkbox column
104 var checkbox_selector = new Slick.CheckboxSelectColumn({
105 cssClass: "slick-cell-checkboxsel"
107 this.slick_columns.push(checkbox_selector.getColumnDefinition());
108 this.slick_grid = new Slick.Grid(selector, this.slick_data, this.slick_columns, this.slick_options);
109 this.slick_grid.setSelectionModel (new Slick.RowSelectionModel ({selectActiveRow: false}));
110 this.slick_grid.registerPlugin (checkbox_selector);
112 this.columnpicker = new Slick.Controls.ColumnPicker (this.slick_columns, this.slick_grid, this.slick_options)
114 }, // initialize_table
116 // Determine index of key in the table columns
117 getColIndex: function(key, cols) {
118 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
119 return (tabIndex.length > 0) ? tabIndex[0] : -1;
122 checkbox_html : function (key, value) {
123 if (debug_deep) messages.debug("checkbox_html, value="+value);
125 // Prefix id with plugin_uuid
127 result += " class='querytable-checkbox'";
128 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
129 result += " name='" + key + "'";
130 result += " type='checkbox'";
131 result += " autocomplete='off'";
132 if (value === undefined) {
133 messages.warning("querytable.checkbox_html - undefined value");
135 result += " value='" + value + "'";
137 result += "></input>";
141 new_record: function(record) {
142 this.slick_data.push(record);
145 clear_table: function() {
146 console.log("clear_table not implemented");
149 redraw_table: function() {
153 show_column: function(field) {
154 var oSettings = this.table.fnSettings();
155 var cols = oSettings.aoColumns;
156 var index = this.getColIndex(field,cols);
158 this.table.fnSetColumnVis(index, true);
161 hide_column: function(field) {
162 console.log("hide_column not implemented - field="+field);
165 set_checkbox: function(record, checked) {
166 console.log("set_checkbox not yet implemented with slickgrid");
168 /* Default: checked = true */
169 if (checked === undefined) checked = true;
172 /* The function accepts both records and their key */
173 switch (manifold.get_type(record)) {
178 /* XXX Test the key before ? */
179 id = record[this.key];
182 throw "Not implemented";
187 if (id === undefined) {
188 messages.warning("querytable.set_checkbox record has no id to figure which line to tick");
191 var checkbox_id = this.flat_id(this.id('checkbox', id));
192 // function escape_id(myid) is defined in portal/static/js/common.functions.js
193 checkbox_id = escape_id(checkbox_id);
194 // using dataTables's $ to search also in nodes that are not currently displayed
195 var element = this.table.$(checkbox_id);
197 messages.debug("set_checkbox checked=" + checked
198 + " id=" + checkbox_id + " matches=" + element.length);
199 element.attr('checked', checked);
202 /*************************** QUERY HANDLER ****************************/
204 on_filter_added: function(filter) {
205 this.filters.push(filter);
209 on_filter_removed: function(filter) {
210 // Remove corresponding filters
211 this.filters = $.grep(this.filters, function(x) {
217 on_filter_clear: function() {
221 on_field_added: function(field) {
222 this.show_column(field);
225 on_field_removed: function(field) {
226 this.hide_column(field);
229 on_field_clear: function() {
230 alert('QueryTable::clear_fields() not implemented');
233 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
234 /*************************** ALL QUERY HANDLER ****************************/
236 on_all_filter_added: function(filter) {
241 on_all_filter_removed: function(filter) {
246 on_all_filter_clear: function() {
251 on_all_field_added: function(field) {
252 this.show_column(field);
255 on_all_field_removed: function(field) {
256 this.hide_column(field);
259 on_all_field_clear: function() {
260 alert('QueryTable::clear_fields() not implemented');
264 /*************************** RECORD HANDLER ***************************/
266 on_new_record: function(record) {
267 if (this.received_all_query) {
268 // if the 'all' query has been dealt with already we may turn on the checkbox
269 this.set_checkbox(record, true);
271 // otherwise we need to remember that and do it later on
272 if (debug) messages.debug("Remembering record to check " + record[this.key]);
273 this.buffered_records_to_check.push(record);
277 on_clear_records: function() {
280 // Could be the default in parent
281 on_query_in_progress: function() {
285 on_query_done: function() {
286 this.received_query = true;
287 // unspin once we have received both
288 if (this.received_all_query && this.received_query) this.unspin();
291 on_field_state_changed: function(data) {
292 switch(data.request) {
293 case FIELD_REQUEST_ADD:
294 case FIELD_REQUEST_ADD_RESET:
295 this.set_checkbox(data.value, true);
297 case FIELD_REQUEST_REMOVE:
298 case FIELD_REQUEST_REMOVE_RESET:
299 this.set_checkbox(data.value, false);
306 /* XXX TODO: make this generic a plugin has to subscribe to a set of Queries to avoid duplicated code ! */
308 on_all_field_state_changed: function(data) {
309 switch(data.request) {
310 case FIELD_REQUEST_ADD:
311 case FIELD_REQUEST_ADD_RESET:
312 this.set_checkbox(data.value, true);
314 case FIELD_REQUEST_REMOVE:
315 case FIELD_REQUEST_REMOVE_RESET:
316 this.set_checkbox(data.value, false);
323 on_all_new_record: function(record) {
324 this.new_record(record);
327 on_all_clear_records: function() {
332 on_all_query_in_progress: function() {
335 }, // on_all_query_in_progress
337 on_all_query_done: function() {
338 if (debug) messages.debug("1-shot initializing dataTables content with " + this.slick_data.length + " lines");
339 var start=new Date();
340 this.slick_grid.setData (this.slick_data, true);
341 this.slick_grid.init();
342 var duration=new Date()-start;
343 if (debug) messages.debug("setData+render took " + duration + " ms");
345 // show full contents of first row app
346 for (k in this.slick_data[0]) messages.debug("slick_data[0]["+k+"]="+this.slick_data[0][k]);
350 // if we've already received the slice query, we have not been able to set
351 // checkboxes on the fly at that time (dom not yet created)
352 $.each(this.buffered_records_to_check, function(i, record) {
353 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
354 self.set_checkbox(record, true);
356 this.buffered_records_to_check = [];
358 this.received_all_query = true;
359 // unspin once we have received both
360 if (this.received_all_query && this.received_query) this.unspin();
362 }, // on_all_query_done
364 /************************** PRIVATE METHODS ***************************/
367 * @brief QueryTable filtering function
369 _querytable_filter: function(oSettings, aData, iDataIndex) {
371 $.each (this.filters, function(index, filter) {
372 /* XXX How to manage checkbox ? */
375 var value = filter[2];
377 /* Determine index of key in the table columns */
378 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
380 /* Unknown key: no filtering */
381 if (typeof(col) == 'undefined')
384 col_value=unfold.get_value(aData[col]);
385 /* Test whether current filter is compatible with the column */
386 if (op == '=' || op == '==') {
387 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
389 }else if (op == '!=') {
390 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
393 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
396 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
398 } else if(op=='<=' || op=='≤') {
399 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
401 } else if(op=='>=' || op=='≥') {
402 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
405 // How to break out of a loop ?
406 alert("filter not supported");
414 _querytable_draw_callback: function() {
416 * Handle clicks on checkboxes: reassociate checkbox click every time
417 * the table is redrawn
419 this.elts('querytable-checkbox').unbind('click').click(this, this._check_click);
424 /* Remove pagination if we show only a few results */
425 var wrapper = this.table; //.parent().parent().parent();
426 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
427 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
428 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
430 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
431 $('.querytable_paginate', wrapper).css('visibility', 'hidden');
433 $('.querytable_paginate', wrapper).css('visibility', 'visible');
436 if ( rowsToShow <= minRowsPerPage ) {
437 $('.querytable_length', wrapper).css('visibility', 'hidden');
439 $('.querytable_length', wrapper).css('visibility', 'visible');
443 _check_click: function(e) {
448 // XXX this.value = key of object to be added... what about multiple keys ?
449 if (debug) messages.debug("querytable click handler checked=" + this.checked + " hrn=" + this.value);
450 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
451 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
455 _selectAll: function() {
456 // requires jQuery id
457 var uuid=this.id.split("-");
458 var oTable=$("#querytable-"+uuid[1]).dataTable();
459 // Function available in QueryTable 1.9.x
460 // Filter : displayed data only
461 var filterData = oTable._('tr', {"filter":"applied"});
462 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
463 if(filterData.length<=100){
464 $.each(filterData, function(index, obj) {
465 var last=$(obj).last();
466 var key_value=unfold.get_value(last[0]);
467 if(typeof($(last[0]).attr('checked'))=="undefined"){
468 $.publish('selected', 'add/'+key_value);
476 $.plugin('QueryTable', QueryTable);
478 // /* define the 'dom-checkbox' type for sorting in datatables
479 // http://datatables.net/examples/plug-ins/dom_sort.html
480 // using trial and error I found that the actual column number
481 // was in fact given as a third argument, and not second
482 // as the various online resources had it - go figure */
483 // $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
484 // return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
485 // return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';