forked from fernandommota/table-bootstrap-component
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable-bootstrap-component.js
More file actions
661 lines (581 loc) · 21.8 KB
/
table-bootstrap-component.js
File metadata and controls
661 lines (581 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/*!
* Copyright 2002 - 2014 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
/*
* Function: fnLengthChange
* Purpose: Change the number of records on display
* Returns: array:
* Inputs: object:oSettings - DataTables settings object
* int:iDisplay - New display length
*/
// Ensure we load dataTables before this line. If not, just keep going
if($.fn.dataTableExt != undefined){
$.fn.dataTableExt.oApi.fnLengthChange = function ( oSettings, iDisplay )
{
oSettings._iDisplayLength = iDisplay;
oSettings.oApi._fnCalculateEnd( oSettings );
// If we have space to show extra rows backing up from the end point - then do so
if ( oSettings._iDisplayEnd == oSettings.aiDisplay.length )
{
oSettings._iDisplayStart = oSettings._iDisplayEnd - oSettings._iDisplayLength;
if ( oSettings._iDisplayStart < 0 )
{
oSettings._iDisplayStart = 0;
}
}
if ( oSettings._iDisplayLength == -1 )
{
oSettings._iDisplayStart = 0;
}
oSettings.oApi._fnDraw( oSettings );
$('select', oSettings.oFeatures.l).val( iDisplay );
};
/* Example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnLengthChange( 100 );
* } );
*/
/* If table elements have class 'numeric' and values are represented as strings (e.g. "234456.5675")
let's try and convert them to numeric values for sorting. Source based on version 1.7.5 of dataTables.js */
$.extend( $.fn.dataTableExt.oSort, {
"numeric-asc": function ( a, b ) {
a = (a=="-"||a=="") ? 0 : ($.isNumeric(a) ? a*1 : 0);
b = (b=="-"||b=="") ? 0 : ($.isNumeric(b) ? b*1 : 0);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"numeric-desc": function ( a, b ) {
a = (a=="-"||a=="") ? 0 : ($.isNumeric(a) ? a*1 :0);
b = (b=="-"||b=="") ? 0 : ($.isNumeric(b) ? b*1 :0);
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
}
/*
* DataTables 1.10 `two_button` pagination control compatibility file
*/
if(jQuery.fn.DataTable != undefined && jQuery.fn.DataTable.ext != undefined) {
jQuery.extend(jQuery.fn.DataTable.ext.classes, {
"sNoFooter" : "",
"sPagePrevEnabled": "paginate_enabled_previous",
"sPagePrevDisabled": "paginate_disabled_previous",
"sPageNextEnabled": "paginate_enabled_next",
"sPageNextDisabled": "paginate_disabled_next"
});
jQuery.extend(jQuery.fn.DataTable.ext.oJUIClasses, {
"sNoFooter" : "",
"sSortable" : "",
"sSortAsc" : "",
"sSortDesc" : "",
"sSortColumn" : "",
"sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left",
"sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled",
"sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right",
"sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled",
"sPageJUINext": "ui-icon ui-icon-circle-arrow-e",
"sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w"
});
jQuery.extend(jQuery.fn.DataTable.ext.pager, {
"two_button": {
"fnInit": function (oSettings, nPaging, fnCallbackDraw) {
var oLang = oSettings.oLanguage.oPaginate;
var oClasses = oSettings.oClasses;
var fnClickHandler = function (e) {
if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
fnCallbackDraw(oSettings);
}
};
var sAppend = (!oSettings.bJUI) ?
'<a class="' + oSettings.oClasses.sPagePrevDisabled + '" tabindex="' + oSettings.iTabIndex + '" role="button">' + oLang.sPrevious + '</a>' +
'<a class="' + oSettings.oClasses.sPageNextDisabled + '" tabindex="' + oSettings.iTabIndex + '" role="button">' + oLang.sNext + '</a>' :
'<a class="' + oSettings.oClasses.sPagePrevDisabled + '" tabindex="' + oSettings.iTabIndex + '" role="button"><span class="' + oSettings.oClasses.sPageJUIPrev + '"></span></a>' +
'<a class="' + oSettings.oClasses.sPageNextDisabled + '" tabindex="' + oSettings.iTabIndex + '" role="button"><span class="' + oSettings.oClasses.sPageJUINext + '"></span></a>';
$(nPaging).append(sAppend);
var els = $('a', nPaging);
var nPrevious = els[0],
nNext = els[1];
oSettings.oApi._fnBindAction(nPrevious, {
action: "previous"
}, fnClickHandler);
oSettings.oApi._fnBindAction(nNext, {
action: "next"
}, fnClickHandler);
/* ID the first elements only */
if (!oSettings.aanFeatures.p) {
nPaging.id = oSettings.sTableId + '_paginate';
nPrevious.id = oSettings.sTableId + '_previous';
nNext.id = oSettings.sTableId + '_next';
nPrevious.setAttribute('aria-controls', oSettings.sTableId);
nNext.setAttribute('aria-controls', oSettings.sTableId);
}
},
"fnUpdate": function (oSettings, fnCallbackDraw) {
if (!oSettings.aanFeatures.p) {
return;
}
var oClasses = oSettings.oClasses;
var an = oSettings.aanFeatures.p;
var nNode;
/* Loop over each instance of the pager */
for (var i = 0, iLen = an.length; i < iLen; i++) {
nNode = an[i].firstChild;
if (nNode) {
/* Previous page */
nNode.className = (oSettings._iDisplayStart === 0) ?
oClasses.sPagePrevDisabled : oClasses.sPagePrevEnabled;
/* Next page */
nNode = nNode.nextSibling;
nNode.className = (oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay()) ?
oClasses.sPageNextDisabled : oClasses.sPageNextEnabled;
}
}
}
}
});
}
var TableBootstrap = UnmanagedComponent.extend({
ph: undefined,
update: function() {
if(!this.preExec()){
return;
}
if(!this.htmlObject) {
return this.error("TableBootstrap requires an htmlObject");
}
try{
this.block();
this.setup();
if(this.chartDefinition.paginateServerside) {
this.paginatingUpdate();
} else {
/* The non-paging query handler only needs to concern itself
* with handling postFetch and calling the draw function
*/
var success = _.bind(function(data){
this.rawData = data;
this.processTableBootstrapResponse(data)
},this);
var handler = this.getSuccessHandler(success);
this.queryState.setAjaxOptions({async:true});
this.queryState.fetchData(this.parameters == undefined ? [] : this.parameters, handler);
}
} catch (e) {
/*
* Something went wrong and we won't have handlers firing in the future
* that will trigger unblock, meaning we need to trigger unblock manually.
*/
Dashboards.log(e,'exception');
this.unblock();
}
},
paginatingUpdate: function() {
var cd = this.chartDefinition;
this.extraOptions = this.extraOptions || [];
this.extraOptions.push(["bServerSide",true]);
this.extraOptions.push(["bProcessing",true]);
this.queryState.setPageSize(parseInt(cd.displayLength || 10));
var success = _.bind(function(values) {
changedValues = undefined;
if((typeof(this.postFetch)=='function')){
changedValues = this.postFetch(values);
}
if (changedValues != undefined) {
values = changedValues;
}
this.processTableBootstrapResponse(values);
},this);
this.queryState.setCallback(success);
this.queryState.setParameters(this.parameters);
this.queryState.setAjaxOptions({async:true});
this.queryState.fetchData(this.parameters, success);
},
/* Initial setup: clearing out the htmlObject and building the query object */
setup: function() {
var cd = this.chartDefinition;
if (cd == undefined){
Dashboards.log("Fatal - No chart definition passed","error");
return;
}
cd["tableId"] = this.htmlObject + "Table";
// Clear previous table
this.ph = $("#"+this.htmlObject).empty();
// remove drawCallback from the parameters, or
// it'll be called before we have an actual table...
var croppedCd = $.extend({},cd);
croppedCd.drawCallback = undefined;
this.queryState = Dashboards.getQuery(croppedCd);
this.query = this.queryState; // for analogy with ccc component's name
// make sure to clean sort options
var sortBy = this.chartDefinition.sortBy || [],
sortOptions = [];
for (var i = 0; i < sortBy.length; i++) {
var col = sortBy[i][0];
var dir = sortBy[i][1];
sortOptions.push( col + (dir == "asc" ? "A" : "D"));
}
this.queryState.setSortBy(sortOptions);
},
pagingCallback: function(url, params,callback,dataTable) {
function p( sKey ) {
for ( var i=0, iLen=params.length ; i<iLen ; i++ ) {
if ( params[i].name == sKey ) {
return params[i].value;
}
}
return null;
}
var sortingCols = p("order"),sort = [];
if(sortingCols.length > 0) {
for(var i = 0; i < sortingCols.length; i++ ) {
var col = sortingCols[i].column;
var dir = sortingCols[i].dir;
sort.push(col + (dir == "asc" ? "A" : "D"));
}
}
var query = this.queryState,
myself = this;
query.setSortBy(sort.join(","));
query.setPageSize(parseInt(p("length")));
query.setPageStartingAt(p("start"));
query.setSearchPattern(p("search") ? p("search") : "");
query.fetchData(function(d) {
if (myself.postFetch){
var mod = myself.postFetch(d,dataTable);
if (typeof mod !== "undefined") {
d = mod;
}
}
var response = {
iTotalRecords: d.queryInfo.totalRows,
iTotalDisplayRecords: d.queryInfo.totalRows
};
response.aaData = d.resultset;
response.sEcho = p("sEcho");
myself.rawData = d;
callback(response);
});
},
/*
* Callback for when the table is finished drawing. Called every time there
* is a redraw event (so not only updates, but also pagination and sorting).
* We handle addIns and such things in here.
*/
fnDrawCallback: function(dataTableSettings) {
var dataTable = dataTableSettings.oInstance,
cd = this.chartDefinition,
myself = this,
handleAddIns = _.bind(this.handleAddIns,this);
this.ph.find("tbody tr").each(function(row,tr){
/*
* Reject rows that are not actually part
* of the datatable (e.g. nested tables)
*/
if (dataTable.fnGetPosition(tr) == null) {
return true;
}
$(tr).children("td").each(function(col,td){
var foundAddIn = handleAddIns(dataTable, td);
/*
* Process column format for those columns
* where we didn't find a matching addIn
*/
if(!foundAddIn && cd.colFormats) {
var position = dataTable.fnGetPosition(td);
if(position && typeof position[0] == "number"){
var rowIdx = position[0],
colIdx = position[2],
format = cd.colFormats[colIdx],
value = myself.rawData.resultset[rowIdx][colIdx];
if (format && (typeof value != "undefined" && value !== null)) {
$(td).text(sprintf(format,value));
}
}
}
});
});
/* Old urlTemplate code. This needs to be here for backward compatibility */
if(cd.urlTemplate != undefined){
var td =$("#" + myself.htmlObject + " td:nth-child(1)");
td.addClass('cdfClickable');
td.bind("click", function(e){
var regex = new RegExp("{"+cd.parameterName+"}","g");
var f = cd.urlTemplate.replace(regex,$(this).text());
eval(f);
});
}
/* Handle post-draw callback the user might have provided */
if(typeof cd.drawCallback == 'function'){
cd.drawCallback.apply(myself,arguments);
}
},
/*
* Handler for when the table finishes initialising. This only happens once,
* when the table *initialises* ,as opposed to every time the table is drawn,
* so it provides us with a good place to add the postExec callback.
*/
fnInitComplete: function() {
this.postExec();
this.unblock();
},
/*
* Resolve and call addIns for the given td in the context of the given
* dataTable. Returns true if there was an addIn and it was successfully
* called, or false otherwise.
*/
handleAddIns: function(dataTable, td) {
var cd = this.chartDefinition,
position = dataTable.fnGetPosition(td);
if(position && typeof position[0] != "number"){
return false;
}
rowIdx = position[0],
colIdx = position[2],
colType = cd.colTypes[colIdx],
addIn = this.getAddIn("colType",colType),
state = {},
target = $(td),
results = this.rawData;
if (!addIn) {
return false;
}
try {
if(!(target.parents('tbody').length)) {
return;
} else if (target.get(0).tagName != 'TD') {
target = target.closest('td');
}
state.rawData = results;
state.tableData = dataTable.fnGetData();
state.colIdx = colIdx;
state.rowIdx = rowIdx;
state.series = results.resultset[state.rowIdx][0];
state.category = results.metadata[state.colIdx].colName;
state.value = results.resultset[state.rowIdx][state.colIdx];
if(cd.colFormats) {
state.colFormat = cd.colFormats[state.colIdx];
}
state.target = target;
addIn.call(td,state,this.getAddInOptions("colType",addIn.getName()));
return true;
} catch (e) {
Dashboards.log(e,'exception');
return false;
}
},
processTableBootstrapResponse : function(json) {
var myself = this,
cd = this.chartDefinition,
extraOptions = {};
this.ph.trigger('cdfTableBootstrapProcessResponse');
// Set defaults for headers / types
if(typeof cd.colHeaders === "undefined" || cd.colHeaders.length == 0)
cd.colHeaders = json.metadata.map(function(i){return i.colName});
if(typeof cd.colTypes === "undefined" || cd.colTypes.length == 0)
cd.colTypes = json.metadata.map(function(i){return i.colType.toLowerCase()});
var dtData0 = TableBootstrap.getDataTableOptions(cd);
// Build a default config from the standard options
$.each(this.extraOptions ? this.extraOptions : {}, function(i,e){
extraOptions[e[0]] = e[1];
});
var dtData = $.extend(cd.dataTableOptions,dtData0,extraOptions);
/* Configure the table event handlers */
dtData.fnDrawCallback = _.bind(this.fnDrawCallback,this);
dtData.fnInitComplete = _.bind(this.fnInitComplete,this);
/* fnServerData is required for server-side pagination */
if (dtData.bServerSide) {
var myself = this;
dtData.fnServerData = function(u,p,c) {
myself.pagingCallback(u,p,c,this);
};
}
/* We need to make sure we're getting data from the right place,
* depending on whether we're using CDA
*/
if (json) {
dtData.aaData = json.resultset;
}
var tableClassName = dtData.tableStyle == "bootstrap" ? 'table table-striped table-bordered form-inline table-responsive' : 'tableComponent';
this.ph.html("<table id='" + this.htmlObject + "Table' class='" + tableClassName +"' width='100%'></table>");
/*
* We'll first initialize a blank table so that we have a
* table handle to work with while the table is redrawing
*/
this.dataTable = $("#"+this.htmlObject+'Table').dataTable(dtData);
// We'll create an Array to keep track of the open expandable rows.
this.dataTable.anOpen = [];
myself.ph.find ('table').bind('click',function(e) {
if (typeof cd.clickAction === 'function' || myself.expandOnClick) {
var state = {},
target = $(e.target),
results = myself.rawData;
if(!(target.parents('tbody').length)) {
return;
} else if (target.get(0).tagName != 'TD') {
target = target.closest('td');
}
var position = myself.dataTable.fnGetPosition(target.get(0));
state.rawData = myself.rawData;
state.tableData = myself.dataTable.fnGetData();
state.colIdx = position[2];
state.rowIdx = position[0];
state.series = results.resultset[state.rowIdx][0];
state.category = results.metadata[state.colIdx].colName;
state.value = results.resultset[state.rowIdx][state.colIdx];
state.colFormat = cd.colFormats[state.colIdx];
state.target = target;
if ( myself.expandOnClick ) {
myself.handleExpandOnClick(state);
}
if ( cd.clickAction ){
cd.clickAction.call(myself,state);
}
}
});
myself.ph.trigger('cdfTableBootstrapFinishRendering');
},
handleExpandOnClick: function(event) {
var myself = this,
detailContainerObj = myself.expandContainerObject,
activeclass = "expandingClass";
if(typeof activeclass === 'undefined'){
activeclass = "activeRow";
}
var obj = event.target.closest("tr"),
a = event.target.closest("a");
if (a.hasClass ('info')) {
return;
} else {
var row = obj.get(0),
value = event.series,
htmlContent = $("#" + detailContainerObj).html(),
anOpen = myself.dataTable.anOpen,
i = $.inArray( row, anOpen );
if( obj.hasClass(activeclass) ){
obj.removeClass(activeclass);
myself.dataTable.fnClose( row );
anOpen.splice(i,1);
} else {
// Closes all open expandable rows .
for ( var j=0; j < anOpen.length; j++ ) {
$(anOpen[j]).removeClass(activeclass);
myself.dataTable.fnClose( anOpen[j] );
anOpen.splice(j ,1);
}
obj.addClass(activeclass);
anOpen.push( row );
// Since the switch to async, we need to open it first
myself.dataTable.fnOpen( row, htmlContent, activeclass );
//Read parameters and fire changes
var results = myself.queryState.lastResults();
$(myself.expandParameters).each(function f(i, elt) {
Dashboards.fireChange(elt[1], results.resultset[event.rowIdx][parseInt(elt[0],10)]);
});
};
};
$("td.expandingClass").click(
function(event){
//Does nothing but it prevents problems on expandingClass clicks!
event.stopPropagation();
return;
}
);
}
},
{
getDataTableOptions : function(options) {
var dtData = {};
if(options.tableStyle == "themeroller"){
dtData.bJQueryUI = true;
}
dtData.bInfo = options.info;
dtData.iDisplayLength = options.displayLength;
dtData.bLengthChange = options.lengthChange;
dtData.bPaginate = options.paginate;
dtData.bSort = options.sort;
dtData.bFilter = options.filter;
dtData.sPaginationType = options.paginationType;
dtData.aaSorting = options.sortBy;
dtData.tableStyle = options.tableStyle;
//sDom configurations, need for booststrap layout
if (typeof options.sDom == "string"){
dtData.sDom = options.sDom;//TODO: er...
}
else {
dtData.sDom = "CT<'clear'>lfrtip<'row'<'col-xs-6'><'col-xs-6'>><'row'<'col-xs-6'><'col-xs-6'>>";
}
if (typeof options.oLanguage == "string"){
dtData.oLanguage = eval("(" + options.oLanguage + ")");//TODO: er...
}
else {
dtData.oLanguage = options.oLanguage;
}
if (typeof options.oColVis == "string"){
dtData.oColVis = eval("(" + options.oColVis + ")");//TODO: er...
}
else {
dtData.oColVis = options.oColVis;
}
if (typeof options.language == "string"){
dtData.language = eval("(" + options.language + ")");//TODO: er...
} else {
dtData.language = options.language;
}
if(options.colHeaders != undefined){
dtData.aoColumns = new Array(options.colHeaders.length);
for(var i = 0; i< options.colHeaders.length; i++){
dtData.aoColumns[i]={}
dtData.aoColumns[i].sClass="column"+i;
};
$.each(options.colHeaders,function(i,val){
dtData.aoColumns[i].sTitle=val;
if(val == "") dtData.aoColumns[i].bVisible=false;
}); // colHeaders
if(options.colTypes!=undefined){
$.each(options.colTypes,function(i,val){
var col = dtData.aoColumns[i];
// Specific case: hidden cols
if(val == "hidden") col.bVisible=false;
col.sClass+=" "+val;
col.sType=val;
})
}; // colTypes
if(options.colFormats!=undefined){
// Changes are made directly to the json
}; // colFormats
var bAutoWidth = true;
if(options.colWidths!=undefined){
$.each(options.colWidths,function(i,val){
if (val!=null){
dtData.aoColumns[i].sWidth=val;
bAutoWidth = false;
}
})
}; //colWidths
dtData.bAutoWidth = bAutoWidth;
if(options.colSortable!=undefined){
$.each(options.colSortable,function(i,val){
if (val!=null && ( !val || val == "false" ) ){
dtData.aoColumns[i].bSortable=false
}
})
}; //colSortable
if(options.colSearchable!=undefined){
$.each(options.colSearchable,function(i,val){
if (val!=null && ( !val || val == "false" ) ){
dtData.aoColumns[i].bSearchable=false
}
})
}; //colSearchable
}
return dtData;
}
});