2 * Description: display a query result in a datatables-powered <table>
3 * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
12 var Hazelnut = Plugin.extend({
14 init: function(options, element)
16 this._super(options, element);
18 /* Member variables */
19 // in general we expect 2 queries here
20 // query_uuid refers to a single object (typically a slice)
21 // query_all_uuid refers to a list (typically resources or users)
22 // these can return in any order so we keep track of which has been received yet
23 this.received_all_query = false;
24 this.received_query = false;
26 // an internal buffer for records that are 'in' and thus need to be checked
27 this.buffered_records_to_check = [];
28 // an internal buffer for keeping lines and display them in one call to fnAddData
29 this.buffered_lines = [];
32 // this.$element.on('show.Datatables', this.on_show);
33 this.elmt().on('show', this, this.on_show);
34 // Unbind all events using namespacing
36 // $(window).unbind('Hazelnut');
38 var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
39 this.method = query.object;
41 var keys = manifold.metadata.get_key(this.method);
42 this.key = (keys && keys.length == 1) ? keys[0] : null;
44 /* Setup query and record handlers */
45 this.listen_query(options.query_uuid);
46 this.listen_query(options.query_all_uuid, 'all');
48 /* GUI setup and event binding */
49 this.initialize_table();
58 self.table.fnAdjustColumnSizing()
60 /* Refresh dataTabeles if click on the menu to display it : fix dataTables 1.9.x Bug */
61 /* temp disabled... useful ? -- jordan
62 $(this).each(function(i,elt) {
63 if (jQuery(elt).hasClass('dataTables')) {
64 var myDiv=jQuery('#hazelnut-' + this.id).parent();
65 if(myDiv.height()==0) {
66 var oTable=$('#hazelnut-' + this.id).dataTable();
76 /* GUI MANIPULATION */
78 initialize_table: function()
80 /* Transforms the table into DataTable, and keep a pointer to it */
82 var actual_options = {
83 // Customize the position of Datatables elements (length,filter,button,...)
84 // we use a fluid row on top and another on the bottom, making sure we take 12 grid elt's each time
85 sDom: "<'row'<'col-xs-5'l><'col-xs-1'r><'col-xs-6'f>>t<'row'<'col-xs-5'i><'col-xs-7'p>>",
86 // XXX as of sept. 2013, I cannot locate a bootstrap3-friendly mode for now
87 // hopefully this would come with dataTables v1.10 ?
88 // in any case, search for 'sPaginationType' all over the code for more comments
89 sPaginationType: 'bootstrap',
90 // Handle the null values & the error : Datatables warning Requested unknown parameter
91 // http://datatables.net/forums/discussion/5331/datatables-warning-...-requested-unknown-parameter/p2
92 aoColumnDefs: [{sDefaultContent: '',aTargets: [ '_all' ]}],
93 // WARNING: this one causes tables in a 'tabs' that are not exposed at the time this is run to show up empty
94 // sScrollX: '100%', /* Horizontal scrolling */
95 bProcessing: true, /* Loading */
96 fnDrawCallback: function() { self._hazelnut_draw_callback.call(self); }
97 // XXX use $.proxy here !
99 // the intention here is that options.datatables_options as coming from the python object take precedence
100 // xxx DISABLED by jordan: was causing errors in datatables.js
101 // xxx turned back on by Thierry - this is the code that takes python-provided options into account
102 // check your datatables_options tag instead
103 // however, we have to accumulate in aoColumnDefs from here (above)
104 // and from the python wrapper (checkboxes management, plus any user-provided aoColumnDefs)
105 if ( 'aoColumnDefs' in this.options.datatables_options) {
106 actual_options['aoColumnDefs']=this.options.datatables_options['aoColumnDefs'].concat(actual_options['aoColumnDefs']);
107 delete this.options.datatables_options['aoColumnDefs'];
109 $.extend(actual_options, this.options.datatables_options );
110 this.table = this.elmt('table').dataTable(actual_options);
112 /* Setup the SelectAll button in the dataTable header */
113 /* xxx not sure this is still working */
114 var oSelectAll = $('#datatableSelectAll-'+ this.options.plugin_uuid);
115 oSelectAll.html("<span class='glyphicon glyphicon-ok' style='float:right;display:inline-block;'></span>Select All");
117 oSelectAll.css('font-size','11px');
118 oSelectAll.css('float','right');
119 oSelectAll.css('margin-right','15px');
120 oSelectAll.css('margin-bottom','5px');
121 oSelectAll.unbind('click');
122 oSelectAll.click(this._selectAll);
124 /* Add a filtering function to the current table
125 * Note: we use closure to get access to the 'options'
127 $.fn.dataTableExt.afnFiltering.push(function( oSettings, aData, iDataIndex ) {
128 /* No filtering if the table does not match */
129 if (oSettings.nTable.id != "hazelnut-" + self.options.plugin_uuid)
131 return this._hazelnut_filter.call(self, oSettings, aData, iDataIndex);
134 /* Processing hidden_columns */
135 $.each(this.options.hidden_columns, function(i, field) {
136 self.hide_column(field);
138 }, // initialize_table
141 * @brief Determine index of key in the table columns
145 getColIndex: function(key, cols) {
146 var tabIndex = $.map(cols, function(x, i) { if (x.sTitle == key) return i; });
147 return (tabIndex.length > 0) ? tabIndex[0] : -1;
150 checkbox_html : function (key, value)
153 // Prefix id with plugin_uuid
155 result += " class='hazelnut-checkbox'";
156 result += " id='" + this.flat_id(this.id('checkbox', value)) + "'";
157 result += " name='" + key + "'";
158 result += " type='checkbox'";
159 result += " autocomplete='off'";
160 result += " value='" + value + "'";
161 result += "></input>";
166 new_record: function(record)
168 // this models a line in dataTables, each element in the line describes a cell
171 // go through table headers to get column names we want
172 // in order (we have temporarily hack some adjustments in names)
173 var cols = this.table.fnSettings().aoColumns;
174 var colnames = cols.map(function(x) {return x.sTitle})
175 var nb_col = cols.length;
176 /* if we've requested checkboxes, then forget about the checkbox column for now */
177 if (this.options.checkboxes) nb_col -= 1;
179 /* fill in stuff depending on the column name */
180 for (var j = 0; j < nb_col; j++) {
181 if (typeof colnames[j] == 'undefined') {
183 } else if (colnames[j] == 'hostname') {
184 if (record['type'] == 'resource,link')
185 //TODO: we need to add source/destination for links
188 line.push(record['hostname']);
190 } else if (colnames[j] == 'hrn' && typeof(record) != 'undefined') {
191 line.push('<a href="../resource/'+record['urn']+'"><span class="glyphicon glyphicon-search"></span></a> '+record['hrn']);
193 if (record[colnames[j]])
194 line.push(record[colnames[j]]);
200 // catch up with the last column if checkboxes were requested
201 if (this.options.checkboxes) {
202 // Use a key instead of hostname (hard coded...)
203 line.push(this.checkbox_html(this.key, record[this.key]));
206 // adding an array in one call is *much* more efficient
207 // this.table.fnAddData(line);
208 this.buffered_lines.push(line);
212 clear_table: function()
214 this.table.fnClearTable();
217 redraw_table: function()
222 show_column: function(field)
224 var oSettings = this.table.fnSettings();
225 var cols = oSettings.aoColumns;
226 var index = this.getColIndex(field,cols);
228 this.table.fnSetColumnVis(index, true);
231 hide_column: function(field)
233 var oSettings = this.table.fnSettings();
234 var cols = oSettings.aoColumns;
235 var index = this.getColIndex(field,cols);
237 this.table.fnSetColumnVis(index, false);
240 set_checkbox: function(record, checked)
242 /* Default: checked = true */
243 if (checked === undefined) checked = true;
246 /* The function accepts both records and their key */
247 switch (manifold.get_type(record)) {
252 /* XXX Test the key before ? */
253 key_value = record[this.key];
256 throw "Not implemented";
261 var checkbox_id = this.flat_id(this.id('checkbox', key_value));
262 checkbox_id = '#' + checkbox_id;
263 // using dataTables's $ to search also in nodes that are not currently displayed
264 var element = this.table.$(checkbox_id);
265 if (debug) messages.debug("set_checkbox checked=" + checked + " id=" + checkbox_id + " matches=" + element.length);
266 element.attr('checked', checked);
269 /*************************** QUERY HANDLER ****************************/
271 on_filter_added: function(filter)
277 on_filter_removed: function(filter)
283 on_filter_clear: function()
289 on_field_added: function(field)
291 this.show_column(field);
294 on_field_removed: function(field)
296 this.hide_column(field);
299 on_field_clear: function()
301 alert('Hazelnut::clear_fields() not implemented');
304 /*************************** RECORD HANDLER ***************************/
306 on_new_record: function(record)
308 if (this.received_all_query) {
309 // if the 'all' query has been dealt with already we may turn on the checkbox
310 if (debug) messages.debug("turning on checkbox for record "+record[this.key]);
311 this.set_checkbox(record, true);
313 // otherwise we need to remember that and do it later on
314 if (debug) messages.debug ("Remembering record to check " + record[this.key]);
315 this.buffered_records_to_check.push(record);
319 on_clear_records: function()
323 // Could be the default in parent
324 on_query_in_progress: function()
329 on_query_done: function()
331 this.received_query = true;
332 // unspin once we have received both
333 if (this.received_all_query && this.received_query) this.unspin();
336 on_field_state_changed: function(data)
338 switch(data.request) {
339 case FIELD_REQUEST_ADD:
340 case FIELD_REQUEST_ADD_RESET:
341 this.set_checkbox(data.value, true);
343 case FIELD_REQUEST_REMOVE:
344 case FIELD_REQUEST_REMOVE_RESET:
345 this.set_checkbox(data.value, false);
354 on_all_new_record: function(record)
356 this.new_record(record);
359 on_all_clear_records: function()
365 on_all_query_in_progress: function()
369 }, // on_all_query_in_progress
371 on_all_query_done: function()
373 if (debug) messages.debug("1-shot initializing dataTables content with " + this.buffered_lines.length + " lines");
374 this.table.fnAddData (this.buffered_lines);
375 this.buffered_lines=[];
378 // if we've already received the slice query, we have not been able to set
379 // checkboxes on the fly at that time (dom not yet created)
380 $.each(this.buffered_records_to_check, function(i, record) {
381 if (debug) messages.debug ("delayed turning on checkbox " + i + " record= " + record);
382 self.set_checkbox(record, true);
384 this.buffered_records_to_check = [];
386 this.received_all_query = true;
387 // unspin once we have received both
388 if (this.received_all_query && this.received_query) this.unspin();
390 }, // on_all_query_done
392 /************************** PRIVATE METHODS ***************************/
395 * @brief Hazelnut filtering function
397 _hazelnut_filter: function(oSettings, aData, iDataIndex)
399 var cur_query = this.current_query;
400 if (!cur_query) return true;
403 /* We have an array of filters : a filter is an array (key op val)
404 * field names (unless shortcut) : oSettings.aoColumns = [ sTitle ]
405 * can we exploit the data property somewhere ?
406 * field values (unless formatting) : aData
407 * formatting should leave original data available in a hidden field
409 * The current line should validate all filters
411 $.each (cur_query.filters, function(index, filter) {
412 /* XXX How to manage checkbox ? */
415 var value = filter[2];
417 /* Determine index of key in the table columns */
418 var col = $.map(oSettings.aoColumns, function(x, i) {if (x.sTitle == key) return i;})[0];
420 /* Unknown key: no filtering */
421 if (typeof(col) == 'undefined')
424 col_value=unfold.get_value(aData[col]);
425 /* Test whether current filter is compatible with the column */
426 if (op == '=' || op == '==') {
427 if ( col_value != value || col_value==null || col_value=="" || col_value=="n/a")
429 }else if (op == '!=') {
430 if ( col_value == value || col_value==null || col_value=="" || col_value=="n/a")
433 if ( parseFloat(col_value) >= value || col_value==null || col_value=="" || col_value=="n/a")
436 if ( parseFloat(col_value) <= value || col_value==null || col_value=="" || col_value=="n/a")
438 } else if(op=='<=' || op=='≤') {
439 if ( parseFloat(col_value) > value || col_value==null || col_value=="" || col_value=="n/a")
441 } else if(op=='>=' || op=='≥') {
442 if ( parseFloat(col_value) < value || col_value==null || col_value=="" || col_value=="n/a")
445 // How to break out of a loop ?
446 alert("filter not supported");
454 _hazelnut_draw_callback: function()
457 * Handle clicks on checkboxes: reassociate checkbox click every time
458 * the table is redrawn
460 this.elts('hazelnut-checkbox').unbind('click').click(this, this._check_click);
465 /* Remove pagination if we show only a few results */
466 var wrapper = this.table; //.parent().parent().parent();
467 var rowsPerPage = this.table.fnSettings()._iDisplayLength;
468 var rowsToShow = this.table.fnSettings().fnRecordsDisplay();
469 var minRowsPerPage = this.table.fnSettings().aLengthMenu[0];
471 if ( rowsToShow <= rowsPerPage || rowsPerPage == -1 ) {
472 $('.hazelnut_paginate', wrapper).css('visibility', 'hidden');
474 $('.hazelnut_paginate', wrapper).css('visibility', 'visible');
477 if ( rowsToShow <= minRowsPerPage ) {
478 $('.hazelnut_length', wrapper).css('visibility', 'hidden');
480 $('.hazelnut_length', wrapper).css('visibility', 'visible');
484 _check_click: function(e)
490 // XXX this.value = key of object to be added... what about multiple keys ?
491 if (debug) messages.debug("hazelnut click handler checked=" + this.checked + " hrn=" + this.value);
492 manifold.raise_event(self.options.query_uuid, this.checked?SET_ADD:SET_REMOVED, this.value);
493 //return false; // prevent checkbox to be checked, waiting response from manifold plugin api
497 _selectAll: function()
499 // requires jQuery id
500 var uuid=this.id.split("-");
501 var oTable=$("#hazelnut-"+uuid[1]).dataTable();
502 // Function available in Hazelnut 1.9.x
503 // Filter : displayed data only
504 var filterData = oTable._('tr', {"filter":"applied"});
505 /* TODO: WARNING if too many nodes selected, use filters to reduce nuber of nodes */
506 if(filterData.length<=100){
507 $.each(filterData, function(index, obj) {
508 var last=$(obj).last();
509 var key_value=unfold.get_value(last[0]);
510 if(typeof($(last[0]).attr('checked'))=="undefined"){
511 $.publish('selected', 'add/'+key_value);
519 $.plugin('Hazelnut', Hazelnut);
521 /* define the 'dom-checkbox' type for sorting in datatables
522 http://datatables.net/examples/plug-ins/dom_sort.html
523 using trial and error I found that the actual column number
524 was in fact given as a third argument, and not second
525 as the various online resources had it - go figure */
526 $.fn.dataTableExt.afnSortData['dom-checkbox'] = function ( oSettings, _, iColumn ) {
527 return $.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr, i) {
528 return result=$('td:eq('+iColumn+') input', tr).prop('checked') ? '1' : '0';