-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathdatatables.js
1150 lines (1048 loc) · 42.9 KB
/
datatables.js
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function() {
// some helper functions: using a global object DTWidget so that it can be used
// in JS() code, e.g. datatable(options = list(foo = JS('code'))); unlike R's
// dynamic scoping, when 'code' is eval()'ed, JavaScript does not know objects
// from the "parent frame", e.g. JS('DTWidget') will not work unless it was made
// a global object
var DTWidget = {};
// 123456666.7890 -> 123,456,666.7890
var markInterval = function(d, digits, interval, mark, decMark, precision) {
x = precision ? d.toPrecision(digits) : d.toFixed(digits);
if (!/^-?[\d.]+$/.test(x)) return x;
var xv = x.split('.');
if (xv.length > 2) return x; // should have at most one decimal point
xv[0] = xv[0].replace(new RegExp('\\B(?=(\\d{' + interval + '})+(?!\\d))', 'g'), mark);
return xv.join(decMark);
};
DTWidget.formatCurrency = function(thiz, row, data, col, currency, digits, interval, mark, decMark, before) {
var d = parseFloat(data[col]);
if (isNaN(d)) return;
var res = markInterval(d, digits, interval, mark, decMark);
res = before ? (/^-/.test(res) ? '-' + currency + res.replace(/^-/, '') : currency + res) :
res + currency;
$(thiz.api().cell(row, col).node()).html(res);
};
DTWidget.formatString = function(thiz, row, data, col, prefix, suffix) {
var d = data[col];
if (d === null) return;
$(thiz.api().cell(row, col).node()).html(prefix + d + suffix);
};
DTWidget.formatPercentage = function(thiz, row, data, col, digits, interval, mark, decMark) {
var d = parseFloat(data[col]);
if (isNaN(d)) return;
$(thiz.api().cell(row, col).node())
.html(markInterval(d * 100, digits, interval, mark, decMark) + '%');
};
DTWidget.formatRound = function(thiz, row, data, col, digits, interval, mark, decMark) {
var d = parseFloat(data[col]);
if (isNaN(d)) return;
$(thiz.api().cell(row, col).node()).html(markInterval(d, digits, interval, mark, decMark));
};
DTWidget.formatSignif = function(thiz, row, data, col, digits, interval, mark, decMark) {
var d = parseFloat(data[col]);
if (isNaN(d)) return;
$(thiz.api().cell(row, col).node())
.html(markInterval(d, digits, interval, mark, decMark, true));
};
DTWidget.formatDate = function(thiz, row, data, col, method, params) {
var d = data[col];
if (d === null) return;
// (new Date('2015-10-28')).toDateString() may return 2015-10-27 because the
// actual time created could be like 'Tue Oct 27 2015 19:00:00 GMT-0500 (CDT)',
// i.e. the date-only string is treated as UTC time instead of local time
if (method === 'toDateString' && /^\d{4,}\D\d{2}\D\d{2}$/.test(d)) {
d = d.split(/\D/);
d = new Date(d[0], d[1] - 1, d[2]);
} else {
d = new Date(d);
}
$(thiz.api().cell(row, col).node()).html(d[method].apply(d, params));
};
window.DTWidget = DTWidget;
var transposeArray2D = function(a) {
return a.length === 0 ? a : HTMLWidgets.transposeArray2D(a);
};
var crosstalkPluginsInstalled = false;
function maybeInstallCrosstalkPlugins() {
if (crosstalkPluginsInstalled)
return;
crosstalkPluginsInstalled = true;
$.fn.dataTable.ext.afnFiltering.push(
function(oSettings, aData, iDataIndex) {
var ctfilter = oSettings.nTable.ctfilter;
if (ctfilter && !ctfilter[iDataIndex])
return false;
var ctselect = oSettings.nTable.ctselect;
if (ctselect && !ctselect[iDataIndex])
return false;
return true;
}
);
}
HTMLWidgets.widget({
name: "datatables",
type: "output",
renderOnNullValue: true,
initialize: function(el, width, height) {
$(el).html(' ');
return {
data: null,
ctfilterHandle: new crosstalk.FilterHandle(),
ctfilterSubscription: null,
ctselectHandle: new crosstalk.SelectionHandle(),
ctselectSubscription: null
};
},
renderValue: function(el, data, instance) {
if (el.offsetWidth === 0 || el.offsetHeight === 0) {
instance.data = data;
return;
}
instance.data = null;
var $el = $(el);
$el.empty();
if (data === null) {
$el.append(' ');
// clear previous Shiny inputs (if any)
for (var i in instance.clearInputs) instance.clearInputs[i]();
instance.clearInputs = {};
return;
}
var crosstalkOptions = data.crosstalkOptions;
if (!crosstalkOptions) crosstalkOptions = {
'key': null, 'group': null
};
if (crosstalkOptions.group) {
maybeInstallCrosstalkPlugins();
instance.ctfilterHandle.setGroup(crosstalkOptions.group);
instance.ctselectHandle.setGroup(crosstalkOptions.group);
}
// If we are in a flexdashboard scroll layout then we:
// (a) Always want to use pagination (otherwise we'll have
// a "double scroll bar" effect on the phone); and
// (b) Never want to fill the container (we want the pagination
// level to determine the size of the container)
if (window.FlexDashboard && !window.FlexDashboard.isFillPage()) {
data.options.bPaginate = true;
data.fillContainer = false;
}
// if we are in the viewer then we always want to fillContainer and
// and autoHideNavigation (unless the user has explicitly set these)
if (window.HTMLWidgets.viewerMode) {
if (!data.hasOwnProperty("fillContainer"))
data.fillContainer = true;
if (!data.hasOwnProperty("autoHideNavigation"))
data.autoHideNavigation = true;
}
// propagate fillContainer to instance (so we have it in resize)
instance.fillContainer = data.fillContainer;
var cells = data.data;
if (cells instanceof Array) cells = transposeArray2D(cells);
$el.append(data.container);
var $table = $el.find('table');
if (data.class) $table.addClass(data.class);
if (data.caption) $table.prepend(data.caption);
if (HTMLWidgets.shinyMode && data.selection.mode !== 'none' &&
data.selection.target === 'row+column') {
if ($table.children('tfoot').length === 0) {
$table.append($('<tfoot>'));
$table.find('thead tr').clone().appendTo($table.find('tfoot'));
}
}
// column filters
var filterRow;
switch (data.filter) {
case 'top':
$table.children('thead').append(data.filterHTML);
filterRow = $table.find('thead tr:last td');
break;
case 'bottom':
if ($table.children('tfoot').length === 0) {
$table.append($('<tfoot>'));
}
$table.children('tfoot').prepend(data.filterHTML);
filterRow = $table.find('tfoot tr:first td');
break;
}
var options = { searchDelay: 1000 };
if (cells !== null) $.extend(options, {
data: cells
});
// options for fillContainer
var bootstrapActive = typeof($.fn.popover) != 'undefined';
if (instance.fillContainer) {
// force scrollX/scrollY and turn off autoWidth
options.scrollX = true;
options.scrollY = "100px"; // can be any value, we'll adjust below
// if we aren't paginating then move around the info/filter controls
// to save space at the bottom and rephrase the info callback
if (data.options.bPaginate === false) {
// we know how to do this cleanly for bootstrap, not so much
// for other themes/layouts
if (bootstrapActive) {
options.dom = "<'row'<'col-sm-4'i><'col-sm-8'f>>" +
"<'row'<'col-sm-12'tr>>";
}
options.fnInfoCallback = function(oSettings, iStart, iEnd,
iMax, iTotal, sPre) {
return Number(iTotal).toLocaleString() + " records";
};
}
}
// auto hide navigation if requested
if (data.autoHideNavigation === true) {
if (bootstrapActive && data.options.bPaginate !== false) {
// strip all nav if length >= cells
if ((cells instanceof Array) && data.options.iDisplayLength >= cells.length)
options.dom = "<'row'<'col-sm-12'tr>>";
// alternatively lean things out for flexdashboard mobile portrait
else if (window.FlexDashboard && window.FlexDashboard.isMobilePhone())
options.dom = "<'row'<'col-sm-12'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12'p>>";
}
}
$.extend(true, options, data.options || {});
var searchCols = options.searchCols;
if (searchCols) {
searchCols = searchCols.map(function(x) {
return x === null ? '' : x.search;
});
// FIXME: this means I don't respect the escapeRegex setting
delete options.searchCols;
}
// server-side processing?
var server = options.serverSide === true;
// use the dataSrc function to pre-process JSON data returned from R
var DT_rows_all = [], DT_rows_current = [];
if (server && HTMLWidgets.shinyMode && typeof options.ajax === 'object' &&
/^session\/[\da-z]+\/dataobj/.test(options.ajax.url) && !options.ajax.dataSrc) {
options.ajax.dataSrc = function(json) {
DT_rows_all = $.makeArray(json.DT_rows_all);
DT_rows_current = $.makeArray(json.DT_rows_current);
return json.data;
};
}
var thiz = this;
if (instance.fillContainer) $table.on('init.dt', function(e) {
thiz.fillAvailableHeight(el, $(el).innerHeight());
});
var table = $table.DataTable(options);
$el.data('datatable', table);
// Unregister previous Crosstalk event subscriptions, if they exist
if (instance.ctfilterSubscription) {
instance.ctfilterHandle.off("change", instance.ctfilterSubscription);
instance.ctfilterSubscription = null;
}
if (instance.ctselectSubscription) {
instance.ctselectHandle.off("change", instance.ctselectSubscription);
instance.ctselectSubscription = null;
}
if (!crosstalkOptions.group) {
$table[0].ctfilter = null;
$table[0].ctselect = null;
} else {
var key = crosstalkOptions.key;
function keysToMatches(keys) {
if (!keys) {
return null;
} else {
var selectedKeys = {};
for (var i = 0; i < keys.length; i++) {
selectedKeys[keys[i]] = true;
}
var matches = {};
for (var j = 0; j < key.length; j++) {
if (selectedKeys[key[j]])
matches[j] = true;
}
return matches;
}
}
function applyCrosstalkFilter(e) {
$table[0].ctfilter = keysToMatches(e.value);
table.draw();
}
instance.ctfilterSubscription = instance.ctfilterHandle.on("change", applyCrosstalkFilter);
applyCrosstalkFilter({value: instance.ctfilterHandle.filteredKeys});
function applyCrosstalkSelection(e) {
if (e.sender !== instance.ctselectHandle) {
table
.rows('.' + selClass, {search: 'applied'})
.nodes()
.to$()
.removeClass(selClass);
if (selectedRows)
changeInput('rows_selected', selectedRows(), void 0, true);
}
if (e.sender !== instance.ctselectHandle && e.value && e.value.length) {
var matches = keysToMatches(e.value);
// persistent selection with plotly (& leaflet)
var ctOpts = crosstalk.var("plotlyCrosstalkOpts").get() || {};
if (ctOpts.persistent === true) {
var matches = $.extend(matches, $table[0].ctselect);
}
$table[0].ctselect = matches;
table.draw();
} else {
if ($table[0].ctselect) {
$table[0].ctselect = null;
table.draw();
}
}
}
instance.ctselectSubscription = instance.ctselectHandle.on("change", applyCrosstalkSelection);
// TODO: This next line doesn't seem to work when renderDataTable is used
applyCrosstalkSelection({value: instance.ctselectHandle.value});
}
var inArray = function(val, array) {
return $.inArray(val, $.makeArray(array)) > -1;
};
// encode + to %2B when searching in the table on server side, because
// shiny::parseQueryString() treats + as spaces, and DataTables does not
// encode + to %2B (or % to %25) when sending the request
var encode_plus = function(x) {
return server ? x.replace(/%/g, '%25').replace(/\+/g, '%2B') : x;
};
// search the i-th column
var searchColumn = function(i, value) {
var regex = false, ci = true;
if (options.search) {
regex = options.search.regex,
ci = options.search.caseInsensitive !== false;
}
return table.column(i).search(encode_plus(value), regex, !regex, ci);
};
if (data.filter !== 'none') {
filterRow.each(function(i, td) {
var $td = $(td), type = $td.data('type'), filter;
var $input = $td.children('div').first().children('input');
$input.prop('disabled', !table.settings()[0].aoColumns[i].bSearchable || type === 'disabled');
$input.on('input blur', function() {
$input.next('span').toggle(Boolean($input.val()));
});
// Bootstrap sets pointer-events to none and we won't be able to click
// the clear button
$input.next('span').css('pointer-events', 'auto').hide().click(function() {
$(this).hide().prev('input').val('').trigger('input').focus();
});
var searchCol; // search string for this column
if (searchCols && searchCols[i]) {
searchCol = searchCols[i];
$input.val(searchCol).trigger('input');
}
var $x = $td.children('div').last();
// remove the overflow: hidden attribute of the scrollHead
// (otherwise the scrolling table body obscures the filters)
var scrollHead = $(el).find('.dataTables_scrollHead,.dataTables_scrollFoot');
var cssOverflow = scrollHead.css('overflow');
if (cssOverflow === 'hidden') {
$x.on('show hide', function(e) {
scrollHead.css('overflow', e.type === 'show' ? '' : cssOverflow);
});
$x.css('z-index', 25);
}
if (inArray(type, ['factor', 'logical'])) {
$input.on({
click: function() {
$input.parent().hide(); $x.show().trigger('show'); filter[0].selectize.focus();
},
input: function() {
if ($input.val() === '') filter[0].selectize.setValue([]);
}
});
var $input2 = $x.children('select');
filter = $input2.selectize({
options: $input2.data('options').map(function(v, i) {
return ({text: v, value: v});
}),
plugins: ['remove_button'],
hideSelected: true,
onChange: function(value) {
if (value === null) value = []; // compatibility with jQuery 3.0
$input.val(value.length ? JSON.stringify(value) : '');
if (value.length) $input.trigger('input');
$input.attr('title', $input.val());
if (server) {
table.column(i).search(value.length ? encode_plus(JSON.stringify(value)) : '').draw();
return;
}
// turn off filter if nothing selected
$td.data('filter', value.length > 0);
table.draw(); // redraw table, and filters will be applied
}
});
if (searchCol) filter[0].selectize.setValue(JSON.parse(searchCol));
// an ugly hack to deal with shiny: for some reason, the onBlur event
// of selectize does not work in shiny
$x.find('div > div.selectize-input > input').on('blur', function() {
$x.hide().trigger('hide'); $input.parent().show(); $input.trigger('blur');
});
filter.next('div').css('margin-bottom', 'auto');
} else if (type === 'character') {
var fun = function() {
searchColumn(i, $input.val()).draw();
};
if (server) {
fun = $.fn.dataTable.util.throttle(fun, options.searchDelay);
}
$input.on('input', fun);
} else if (inArray(type, ['number', 'integer', 'date', 'time'])) {
var $x0 = $x;
$x = $x0.children('div').first();
$x0.css({
'background-color': '#fff',
'border': '1px #ddd solid',
'border-radius': '4px',
'padding': '20px 20px 10px 20px'
});
var $spans = $x0.children('span').css({
'margin-top': '10px',
'white-space': 'nowrap'
});
var $span1 = $spans.first(), $span2 = $spans.last();
var r1 = +$x.data('min'), r2 = +$x.data('max');
// when the numbers are too small or have many decimal places, the
// slider may have numeric precision problems (#150)
var scale = Math.pow(10, Math.max(0, +$x.data('scale') || 0));
r1 = Math.round(r1 * scale); r2 = Math.round(r2 * scale);
var scaleBack = function(x, scale) {
if (scale === 1) return x;
var d = Math.round(Math.log(scale) / Math.log(10));
// to avoid problems like 3.423/100 -> 0.034230000000000003
return (x / scale).toFixed(d);
};
$input.on({
focus: function() {
$x0.show().trigger('show');
// first, make sure the slider div leaves at least 20px between
// the two (slider value) span's
$x0.width(Math.max(160, $span1.outerWidth() + $span2.outerWidth() + 20));
// then, if the input is really wide, make the slider the same
// width as the input
if ($x0.outerWidth() < $input.outerWidth()) {
$x0.outerWidth($input.outerWidth());
}
// make sure the slider div does not reach beyond the right margin
if ($(window).width() < $x0.offset().left + $x0.width()) {
$x0.offset({
'left': $input.offset().left + $input.outerWidth() - $x0.outerWidth()
});
}
},
blur: function() {
$x0.hide().trigger('hide');
},
input: function() {
if ($input.val() === '') filter.val([r1, r2]);
},
change: function() {
var v = $input.val().replace(/\s/g, '');
if (v === '') return;
v = v.split('...');
if (v.length !== 2) {
$input.parent().addClass('has-error');
return;
}
if (v[0] === '') v[0] = r1;
if (v[1] === '') v[1] = r2;
$input.parent().removeClass('has-error');
// treat date as UTC time at midnight
var strTime = function(x) {
var s = type === 'date' ? 'T00:00:00Z' : '';
var t = new Date(x + s).getTime();
// add 10 minutes to date since it does not hurt the date, and
// it helps avoid the tricky floating point arithmetic problems,
// e.g. sometimes the date may be a few milliseconds earlier
// than the midnight due to precision problems in noUiSlider
return type === 'date' ? t + 3600000 : t;
};
if (inArray(type, ['date', 'time'])) {
v[0] = strTime(v[0]);
v[1] = strTime(v[1]);
}
if (v[0] != r1) v[0] *= scale;
if (v[1] != r2) v[1] *= scale;
filter.val(v);
}
});
var formatDate = function(d) {
d = scaleBack(d, scale);
if (type === 'number') return d;
if (type === 'integer') return parseInt(d);
var x = new Date(+d);
if (type === 'date') {
var pad0 = function(x) {
return ('0' + x).substr(-2, 2);
};
return x.getUTCFullYear() + '-' + pad0(1 + x.getUTCMonth())
+ '-' + pad0(x.getUTCDate());
} else {
return x.toISOString();
}
};
var opts = type === 'date' ? { step: 60 * 60 * 1000 } :
type === 'integer' ? { step: 1 } : {};
filter = $x.noUiSlider($.extend({
start: [r1, r2],
range: {min: r1, max: r2},
connect: true
}, opts));
if (scale > 1) (function() {
var t1 = r1, t2 = r2;
var val = filter.val();
while (val[0] > r1 || val[1] < r2) {
if (val[0] > r1) {
t1 -= val[0] - r1;
}
if (val[1] < r2) {
t2 += r2 - val[1];
}
filter = $x.noUiSlider($.extend({
start: [t1, t2],
range: {min: t1, max: t2},
connect: true
}, opts), true);
val = filter.val();
}
r1 = t1; r2 = t2;
})();
$span1.text(formatDate(r1)); $span2.text(formatDate(r2));
var updateSlider = function(e) {
var val = filter.val();
// turn off filter if in full range
$td.data('filter', val[0] > r1 || val[1] < r2);
var v1 = formatDate(val[0]), v2 = formatDate(val[1]), ival;
if ($td.data('filter')) {
ival = v1 + ' ... ' + v2;
$input.attr('title', ival).val(ival).trigger('input');
} else {
$input.attr('title', '').val('');
}
$span1.text(v1); $span2.text(v2);
if (e.type === 'slide') return; // no searching when sliding only
if (server) {
table.column(i).search($td.data('filter') ? ival : '').draw();
return;
}
table.draw();
};
filter.on({
set: updateSlider,
slide: updateSlider
});
}
// server-side processing will be handled by R (or whatever server
// language you use); the following code is only needed for client-side
// processing
if (server) {
// if a search string has been pre-set, search now
if (searchCol) searchColumn(i, searchCol).draw();
return;
}
var customFilter = function(settings, data, dataIndex) {
// there is no way to attach a search function to a specific table,
// and we need to make sure a global search function is not applied to
// all tables (i.e. a range filter in a previous table should not be
// applied to the current table); we use the settings object to
// determine if we want to perform searching on the current table,
// since settings.sTableId will be different to different tables
if (table.settings()[0] !== settings) return true;
// no filter on this column or no need to filter this column
if (typeof filter === 'undefined' || !$td.data('filter')) return true;
var r = filter.val(), v, r0, r1;
if (type === 'number' || type === 'integer') {
v = parseFloat(data[i]);
// how to handle NaN? currently exclude these rows
if (isNaN(v)) return(false);
r0 = parseFloat(scaleBack(r[0], scale))
r1 = parseFloat(scaleBack(r[1], scale));
if (v >= r0 && v <= r1) return true;
} else if (type === 'date' || type === 'time') {
v = new Date(data[i]);
r0 = new Date(r[0] / scale); r1 = new Date(r[1] / scale);
if (v >= r0 && v <= r1) return true;
} else if (type === 'factor') {
if (r.length === 0 || inArray(data[i], r)) return true;
} else if (type === 'logical') {
if (r.length === 0) return true;
if (inArray(data[i] === '' ? 'na' : data[i], r)) return true;
}
return false;
};
$.fn.dataTable.ext.search.push(customFilter);
// search for the preset search strings if it is non-empty
if (searchCol) {
if (inArray(type, ['factor', 'logical'])) {
filter[0].selectize.setValue(JSON.parse(searchCol));
} else if (type === 'character') {
$input.trigger('input');
} else if (inArray(type, ['number', 'integer', 'date', 'time'])) {
$input.trigger('change');
}
}
});
}
// highlight search keywords
var highlight = function() {
var body = $(table.table().body());
// removing the old highlighting first
body.unhighlight();
// don't highlight the "not found" row, so we get the rows using the api
if (table.rows({ filter: 'applied' }).data().length === 0) return;
// highlight gloal search keywords
body.highlight($.trim(table.search()).split(/\s+/));
// then highlight keywords from individual column filters
if (filterRow) filterRow.each(function(i, td) {
var $td = $(td), type = $td.data('type');
if (type !== 'character') return;
var $input = $td.children('div').first().children('input');
var column = table.column(i).nodes().to$(),
val = $.trim($input.val());
if (type !== 'character' || val === '') return;
column.highlight(val.split(/\s+/));
});
};
if (options.searchHighlight) {
table
.on('draw.dt.dth column-visibility.dt.dth column-reorder.dt.dth', highlight)
.on('destroy', function() {
// remove event handler
table.off('draw.dt.dth column-visibility.dt.dth column-reorder.dt.dth');
});
// initial highlight for state saved conditions and initial states
highlight();
}
// run the callback function on the table instance
if (typeof data.callback === 'function') data.callback(table);
// double click to edit the cell
if (data.editable) table.on('dblclick.dt', 'tbody td', function() {
var $input = $('<input type="text">');
var $this = $(this), value = table.cell(this).data(), html = $this.html();
var changed = false;
$input.val(value);
$this.empty().append($input);
$input.css('width', '100%').focus().on('change', function() {
changed = true;
var valueNew = $input.val();
if (valueNew != value) {
table.cell($this).data(valueNew);
if (HTMLWidgets.shinyMode) changeInput('cell_edit', cellInfo($this));
// for server-side processing, users have to call replaceData() to update the table
if (!server) table.draw(false);
} else {
$this.html(html);
}
$input.remove();
}).on('blur', function() {
if (!changed) $input.trigger('change');
});
});
// interaction with shiny
if (!HTMLWidgets.shinyMode && !crosstalkOptions.group) return;
var methods = {};
var shinyData = {};
methods.updateCaption = function(caption) {
if (!caption) return;
$table.children('caption').replaceWith(caption);
}
// register clear functions to remove input values when the table is removed
instance.clearInputs = {};
var changeInput = function(id, value, type, noCrosstalk) {
var event = id;
id = el.id + '_' + id;
if (type) id = id + ':' + type;
// do not update if the new value is the same as old value
if (shinyData.hasOwnProperty(id) && shinyData[id] === JSON.stringify(value))
return;
shinyData[id] = JSON.stringify(value);
if (HTMLWidgets.shinyMode) {
Shiny.onInputChange(id, value);
if (!instance.clearInputs[id]) instance.clearInputs[id] = function() {
Shiny.onInputChange(id, null);
}
}
// HACK
if (event === "rows_selected" && !noCrosstalk) {
if (crosstalkOptions.group) {
var keys = crosstalkOptions.key;
var selectedKeys = null;
if (value) {
selectedKeys = [];
for (var i = 0; i < value.length; i++) {
// The value array's contents use 1-based row numbers, so we must
// convert to 0-based before indexing into the keys array.
selectedKeys.push(keys[value[i] - 1]);
}
}
instance.ctselectHandle.set(selectedKeys);
}
}
};
var addOne = function(x) {
return x.map(function(i) { return 1 + i; });
};
var unique = function(x) {
var ux = [];
$.each(x, function(i, el){
if ($.inArray(el, ux) === -1) ux.push(el);
});
return ux;
}
// change the row index of a cell
var tweakCellIndex = function(cell) {
var info = cell.index();
if (server) {
info.row = DT_rows_current[info.row];
} else {
info.row += 1;
}
return {row: info.row, col: info.column};
}
var selMode = data.selection.mode, selTarget = data.selection.target;
if (inArray(selMode, ['single', 'multiple'])) {
var selClass = data.style === 'bootstrap' ? 'active' : 'selected';
var selected = data.selection.selected, selected1, selected2;
// selected1: row indices; selected2: column indices
if (selected === null) {
selected1 = selected2 = [];
} else if (selTarget === 'row') {
selected1 = $.makeArray(selected);
} else if (selTarget === 'column') {
selected2 = $.makeArray(selected);
} else if (selTarget === 'row+column') {
selected1 = $.makeArray(selected.rows);
selected2 = $.makeArray(selected.cols);
}
// After users reorder the rows or filter the table, we cannot use the table index
// directly. Instead, we need this function to find out the rows between the two clicks.
// If user filter the table again between the start click and the end click, the behavior
// would be undefined, but it should not be a problem.
var shiftSelRowsIndex = function(start, end) {
var indexes = server ? DT_rows_all : table.rows({ search: 'applied' }).indexes().toArray();
start = indexes.indexOf(start); end = indexes.indexOf(end);
// if start is larger than end, we need to swap
if (start > end) {
var tmp = end; end = start; start = tmp;
}
return indexes.slice(start, end + 1);
}
var serverRowIndex = function(clientRowIndex) {
return server ? DT_rows_current[clientRowIndex] : clientRowIndex + 1;
}
// row, column, or cell selection
var lastClickedRow;
if (inArray(selTarget, ['row', 'row+column'])) {
var selectedRows = function() {
var rows = table.rows('.' + selClass);
var idx = rows.indexes().toArray();
if (!server) return addOne(idx);
idx = idx.map(function(i) {
return DT_rows_current[i];
});
selected1 = selMode === 'multiple' ? unique(selected1.concat(idx)) : idx;
return selected1;
}
table.on('mousedown.dt', 'tbody tr', function(e) {
var $this = $(this), thisRow = table.row(this);
if (selMode === 'multiple') {
if (e.shiftKey && lastClickedRow !== undefined) {
// select or de-select depends on the last clicked row's status
var flagSel = !$this.hasClass(selClass);
var crtClickedRow = serverRowIndex(thisRow.index());
if (server) {
var rowsIndex = shiftSelRowsIndex(lastClickedRow, crtClickedRow);
// update current page's selClass
rowsIndex.map(function(i) {
var rowIndex = DT_rows_current.indexOf(i);
if (rowIndex >= 0) {
var row = table.row(rowIndex).nodes().to$();
var flagRowSel = !row.hasClass(selClass);
if (flagSel === flagRowSel) row.toggleClass(selClass);
}
});
// update selected1
if (flagSel) {
selected1 = unique(selected1.concat(rowsIndex));
} else {
selected1 = selected1.filter(function(index) {
return !inArray(index, rowsIndex);
});
}
} else {
// js starts from 0
shiftSelRowsIndex(lastClickedRow - 1, crtClickedRow - 1).map(function(value) {
var row = table.row(value).nodes().to$();
var flagRowSel = !row.hasClass(selClass);
if (flagSel === flagRowSel) row.toggleClass(selClass);
});
}
e.preventDefault();
} else {
$this.toggleClass(selClass);
}
} else {
if ($this.hasClass(selClass)) {
$this.removeClass(selClass);
} else {
table.$('tr.' + selClass).removeClass(selClass);
$this.addClass(selClass);
}
}
if (server && !$this.hasClass(selClass)) {
var id = DT_rows_current[thisRow.index()];
// remove id from selected1 since its class .selected has been removed
if (inArray(id, selected1)) selected1.splice($.inArray(id, selected1), 1);
}
changeInput('rows_selected', selectedRows());
changeInput('row_last_clicked', serverRowIndex(thisRow.index()));
lastClickedRow = serverRowIndex(thisRow.index());
});
changeInput('rows_selected', selected1);
var selectRows = function() {
table.$('tr.' + selClass).removeClass(selClass);
if (selected1.length === 0) return;
if (server) {
table.rows({page: 'current'}).every(function() {
if (inArray(DT_rows_current[this.index()], selected1)) {
$(this.node()).addClass(selClass);
}
});
} else {
var selected0 = selected1.map(function(i) { return i - 1; });
$(table.rows(selected0).nodes()).addClass(selClass);
}
}
selectRows(); // in case users have specified pre-selected rows
// restore selected rows after the table is redrawn (e.g. sort/search/page);
// client-side tables will preserve the selections automatically; for
// server-side tables, we have to *real* row indices are in `selected1`
if (server) table.on('draw.dt', selectRows);
methods.selectRows = function(selected) {
selected1 = selected ? selected : [];
selectRows();
changeInput('rows_selected', selected1);
}
}
if (inArray(selTarget, ['column', 'row+column'])) {
if (selTarget === 'row+column') {
$(table.columns().footer()).css('cursor', 'pointer');
}
table.on('click.dt', selTarget === 'column' ? 'tbody td' : 'tfoot tr th', function() {
var colIdx = selTarget === 'column' ? table.cell(this).index().column :
$.inArray(this, table.columns().footer()),
thisCol = $(table.column(colIdx).nodes());
if (colIdx === -1) return;
if (thisCol.hasClass(selClass)) {
thisCol.removeClass(selClass);
selected2.splice($.inArray(colIdx, selected2), 1);
} else {
if (selMode === 'single') $(table.cells().nodes()).removeClass(selClass);
thisCol.addClass(selClass);
selected2 = selMode === 'single' ? [colIdx] : unique(selected2.concat([colIdx]));
}
changeInput('columns_selected', selected2);
});
changeInput('columns_selected', selected2);
var selectCols = function() {
table.columns().nodes().flatten().to$().removeClass(selClass);
if (selected2.length > 0)
table.columns(selected2).nodes().flatten().to$().addClass(selClass);
}
selectCols(); // in case users have specified pre-selected columns
if (server) table.on('draw.dt', selectCols);
methods.selectColumns = function(selected) {
selected2 = selected ? selected : [];
selectCols();
changeInput('columns_selected', selected2);
}
}
if (selTarget === 'cell') {
var selected3;
if (selected === null) {
selected3 = [];
} else {
selected3 = selected;
}
var findIndex = function(ij) {
for (var i = 0; i < selected3.length; i++) {
if (ij[0] === selected3[i][0] && ij[1] === selected3[i][1]) return i;
}
return -1;
}
table.on('click.dt', 'tbody td', function() {
var $this = $(this), info = tweakCellIndex(table.cell(this));
if ($this.hasClass(selClass)) {
$this.removeClass(selClass);
selected3.splice(findIndex([info.row, info.col]), 1);
} else {
if (selMode === 'single') $(table.cells().nodes()).removeClass(selClass);
$this.addClass(selClass);
selected3 = selMode === 'single' ? [[info.row, info.col]] :
unique(selected3.concat([[info.row, info.col]]));
}
changeInput('cells_selected', transposeArray2D(selected3), 'shiny.matrix');
});
changeInput('cells_selected', transposeArray2D(selected3), 'shiny.matrix');
var selectCells = function() {
table.$('td.' + selClass).removeClass(selClass);
if (selected3.length === 0) return;
if (server) {
table.cells({page: 'current'}).every(function() {
var info = tweakCellIndex(this);
if (findIndex([info.row, info.col], selected3) > -1)
$(this.node()).addClass(selClass);
});
} else {
selected3.map(function(ij) {
$(table.cell(ij[0] - 1, ij[1]).node()).addClass(selClass);
});
}
};
selectCells(); // in case users have specified pre-selected columns
if (server) table.on('draw.dt', selectCells);
methods.selectCells = function(selected) {
selected3 = selected ? selected : [];
selectCells();
changeInput('cells_selected', transposeArray2D(selected3), 'shiny.matrix');
}
}
}
// expose some table info to Shiny
var updateTableInfo = function(e, settings) {
// TODO: is anyone interested in the page info?
// changeInput('page_info', table.page.info());
var updateRowInfo = function(id, modifier) {
var idx;
if (server) {