-
Notifications
You must be signed in to change notification settings - Fork 0
/
clientside.js
2727 lines (2576 loc) · 109 KB
/
clientside.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
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Libtables3: framework for building web-applications on relational databases *
* Version 3.0.0 / Copyright (C) 2023 Bart Noordervliet, MMVI *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Notes on variable names: *
* *
* r = table row iterator *
* c = table column iterator *
* i, j = generic iterators *
* attr = jQuery object built from HTML5 "data-" attributes *
* table, thead, tbody, tfoot, row, cell *
* = jQuery object wrapping the corresponding DOM element *
* data = object parsed from server JSON response *
* key = unique identifier string for the table *
* composed of <block>:<tag> *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
'use strict';
let ajaxUrl = "data.php";
let tables = {};
let lists = {};
let transl = {};
let lang = 0;
let $ = jQuery;
function tr(str) {
switch (navigator.language) {
case "nl":
case "nl-NL":
switch (str) {
case "Total": return "Totaal";
case "Page": return "Pagina";
case "Row": return "Document";
case "of": return "van";
case "Error": return "Fout";
case "Insert": return "Toevoegen";
case "Export as": return "Exporteren als";
case "Row has errors and cannot be inserted": return "Rij heeft fouten en kan niet worden toegevoegd";
case "Select": return "Selecteren";
case "rows for export": return "rijen om te exporteren";
case "Next": return "Volgende";
case "Previous": return "Vorige";
case "Field": return "Veld";
case "may not be empty": return "mag niet leeg zijn";
default: return str;
}
default: return str;
}
}
function escape(val) {
if (typeof val == 'string') return val.replace(/</g, '<').replace(/"/g, '"');
else return val;
}
function userError(msg) {
alert(tr('Error') + ': ' + tr(msg));
}
function appError(msg, context) {
console.log('Error: ' + msg);
if (context) console.log('Context:', context);
}
$(document).ready(function() {
load($(document), true);
window.setInterval(refreshAll, 30000);
$('BODY').on('keyup', '.lt-search', function(evt) {
if (evt.key == 'Enter') $(this).find('.lt-search-form-submit').click();
})
});
function load(el, visible) {
let tables, controls, searches;
if (visible) {
tables = el.find('.lt-div:visible');
controls = el.find('.lt-control:visible');
searches = el.find('.lt-search:visible');
}
else {
tables = el.find('.lt-div');
controls = el.find('.lt-control');
searches = el.find('.lt-search');
}
tables.each(function() {
let attr = $(this).data();
loadTable($(this), attr);
});
controls.each(function() {
let attr = $(this).data();
loadControl($(this), attr);
});
searches.each(function() {
let attr = $(this).data();
loadSearch($(this), attr);
});
el.find('.lt-div-text').each(function() {
let attr = $(this).data();
if (attr.embedded) $(this).html(atob(attr.embedded));
else refreshText($(this));
});
}
function refreshAll() {
$('.lt-table:visible').each(function() {
let table = $(this);
let key = $(this).attr('id');
if (!table.length || !tables[key]) return;
if (tables[key].data.rowcount) return; // rowcount is set for exports with nopreview=true
refreshTable(table, key);
});
$('.lt-div-text').each(function() {
refreshText($(this));
});
}
function refreshText(div) {
let attr = div.data();
if (!attr.source) return;
$.ajax({
dataType: "json",
url: ajaxUrl,
data: "mode=refreshtext&src=" + attr.source,
context: div,
success: function(data) {
if (data.error) appError(data.error, this);
else this.html(data.text);
}
});
}
function loadOrRefreshCollection(coll, sub) {
coll.each(function() {
let div = $(this);
if (div.hasClass('lt-div')) {
let attr = div.data();
let key = attr.source;
if (!tables[key] || !document.getElementById(key)) loadTable(div, attr, sub); // Using getElementById() because jQuery gets confused by the colon in the id
else refreshTable(div.find('table'), key, true);
}
else if (div.hasClass('lt-div-text')) refreshText(div);
else if (div.hasClass('lt-control')) {
if (div.is(':empty')) loadControl(div, div.data());
}
});
}
jQuery.fn.extend({
activate: function() {
return this.each(function() {
let el = $(this);
el.find('.lt-div').each(function() {
let div = $(this);
let attr = div.data();
let key = attr.source;
if (!tables[key] || !document.getElementById(key)) loadTable(div, attr); // Using getElementById() because jQuery gets confused by the colon in the id
else refreshTable(div.find('table'), key, true);
});
el.find('.lt-control').each(function() { loadControl($(this), $(this).data()); });
el.find('.lt-div-text').each(function() { refreshText($(this)); });
});
}
});
function doAction(button, addparam) {
button = $(button);
let table, thead, fullscreen = button.closest('#lt-fullscreen-div');
if (fullscreen.length) {
table = fullscreen.find('#lt-fullscreen-scroller table');
thead = fullscreen.find('thead');
}
else {
table = button.closest('table');
thead = button.closest('thead');
}
let key = table.attr('id');
let paramstr = "";
if (addparam) paramstr = btoa('[ "' + addparam + '" ]');
if (button.hasClass('lt-tableaction')) {
$.ajax({
method: 'post',
url: ajaxUrl,
dataType: 'json',
context: tables[key].data,
data: { mode: 'action', type: 'table', src: tables[key].data.block + ':' + tables[key].data.tag, params: paramstr },
success: function(data) {
let action = this.options.tableaction;
if (data.error) appError(data.error, table);
if (data.output) {
if (action.output == 'block') {
// $('#block_' + this.block).replaceWith(data.output);
let coll = $(data.output).replaceAll('#block_' + this.block);
loadOrRefreshCollection(coll.find('.lt-div,.lt-control'));
return;
}
if (action.output == 'location') {
window.location = data.output;
return;
}
if (action.output == 'alert') alert(data.output);
else if (action.output == 'function') {
if (!action.functionname) {
console.log('Source ' + tables[key].data.block + ':' + tables[key].data.tag + ' has an action with output type function without a functionname parameter');
return;
}
window[action.functionname](data.output);
}
}
refreshTable(table, key, true);
if (this.options.trigger) loadOrRefreshCollection($('#' + this.options.trigger));
// if (tables[key].data.options.tableaction.trigger) loadOrRefreshCollection($('#' + tables[key].data.options.tableaction.trigger));
// if (tables[key].data.options.tableaction.replacetext) thead.find('.lt-tableaction').val(tables[key].data.options.tableaction.replacetext);
}
});
}
else if (button.hasClass('lt-rowaction')) {
let actionid = button.parent().data('actionid');
let data = tables[key].data;
button.closest('tbody').find('.lt-row-active').removeClass('lt-row-active');
data.active = button.closest('.lt-row').addClass('lt-row-active').data('rowid');
window.activeid = data.active;
$.ajax({
method: 'post',
url: ajaxUrl,
dataType: 'json',
context: data,
data: { mode: 'action', type: 'row', src: data.block + ':' + data.tag, params: paramstr, row: data.active, action: actionid },
success: function(data) {
let action = Array.isArray(this.options.rowaction)?this.options.rowaction[actionid]:this.options.rowaction;
if (data.error) appError(data.error, table);
if (data.usererror) userError(data.usererror);
if (action.runjs) eval(action.runjs);
if (data.output) {
if (action.output == 'block') {
// $('#block_' + this.block).replaceWith(data.output);
let coll = $(data.output).replaceAll('#block_' + this.block);
loadOrRefreshCollection(coll.find('.lt-div,.lt-control'));
return;
}
if (action.output == 'location') {
window.location = data.output;
return;
}
if (action.output == 'alert') alert(data.output);
else if (action.output == 'function') {
if (!action.functionname) {
console.log('Source ' + tables[key].data.block + ':' + tables[key].data.tag + ' has an action with output type function without a functionname parameter');
return;
}
window[action.functionname](data.output);
}
else console.log('Action for source ' + tables[key].data.block + ':' + tables[key].data.tag + ' returned output: ' + data.output);
}
refreshTable(table, key, true);
if (this.options.trigger) loadOrRefreshCollection($('#' + this.options.trigger));
if (action.trigger) loadOrRefreshCollection($('#' + action.trigger));
// else if (data.redirect) window.location = data.redirect;
// else if (data.replace) {
// $('#block_' + tables[key].data.block).replaceWith(data.replace);
// let block = $('#block_' + tables[key].data.block); // Need to fetch the new version of the block
// loadOrRefreshCollection(block.find('.lt-div'));
// block.find('.lt-control:visible').each(function() {
// let attr = $(this).data();
// loadControl($(this), attr);
// });
// }
// else {
// refreshTable(table, key);
// if (data.alert) alert(data.alert);
// if (tables[key].data.options.trigger) loadOrRefreshCollection($('#' + tables[key].data.options.trigger));
// }
}
});
}
}
// function toggleTableFullscreen(table) {
// let div = table.closest('#lt-fullscreen-div');
// if (div.length) {
// let id = div.find('#lt-fullscreen-scroller table').attr('id').split(':');
// let origDiv = $('body').find('div#'+id[1]);
// let origTable = div.find('#lt-fullscreen-scroller table');
// origTable.prepend(table.find('thead'));
// origTable.append(div.find('tfoot'));
// origDiv.append(origTable);
// div.remove();
// $('body').children().show();
// return;
// }
// div = $('<div id="lt-fullscreen-div"/>');
// table.detach();
// let thead = $('<table class="lt-table"/>');
// table.find('thead').detach().appendTo(thead);
// let tfoot = $('<table class="lt-table"/>');
// table.find('tfoot').detach().appendTo(tfoot);
// let scroller = $('<div id="lt-fullscreen-scroller"/>');
// scroller.append(table);
// div.append(thead, scroller, tfoot);
// $('BODY').children().hide();
// $('BODY').append(div);
// scroller.css({ height: div.height()-thead.outerHeight()-tfoot.outerHeight() })
// syncColumnWidths(div);
// }
// function syncColumnWidths(div) {
// let head = div.find('thead .lt-head');
// let cell = div.find('tbody tr:first-child .lt-cell');
// for (let i = 0; i < head.length && i < cell.length; i++) {
// if (head[i].offsetWidth > cell[i].offsetWidth) {
// cell[i].style.minWidth = head[i].offsetWidth + 'px';
// head[i].style.removeProperty('minWidth');
// }
// else {
// head[i].style.minWidth = cell[i].offsetWidth + 'px';
// cell[i].style.removeProperty('minWidth');
// }
// }
// }
// function changeParams(div, params) {
// let attr = div.data();
// let key = attr.source + (attr.params?'_' + attr.params:'');
// if (typeof params === 'string') {
// if (params === attr.params) {
// refreshTable(div.find('table').first(), key);
// return;
// }
// attr.params = params;
// }
// else {
// let str = btoa(JSON.stringify(params));
// if (str === attr.params) {
// refreshTable(div.find('table').first(), key);
// return;
// }
// attr.params = str;
// }
// if (tables[key]) delete tables[key];
// div.html("Loading...");
// loadTable(div, attr);
// }
function loadSearch(div, attr) {
let options = JSON.parse(atob(attr.options));
let form = $('<div class="lt-search-form"/>');
let state = JSON.parse(sessionStorage.getItem('lt_search:' + attr.source) ?? '{}');
for (let field of options.fields) {
if (!field.name) {
console.log("Search field in " + attr.source + " has no name defined");
continue;
}
let label = $('<label for="' + field.name + '">' + field.label + '</label>');
let item;
if (field.options) {
item = $('<select class="lt-search-form-select" name="' + field.name + '" tabindex="1"/>');
for (let option of field.options) {
item.append($('<option value="' + option[1] + '">' + option[0] + '</option>'));
}
if (field.multiple) item.prop('multiple', true);
item.val(null);
}
else item = $('<input type="text" name="' + field.name + '" tabindex="1">');
if (state?.fields?.find((f) => f.name == field.name)) item.filter('input,select').val(state.fields.find((f) => f.name == field.name).value);
else if (field.prefill) item.filter('input').val(field.prefill);
if (field.placeholder) item.filter('input').prop('placeholder', field.placeholder);
let controls = $('<div class="lt-search-form-controls"/>');
if (typeof field.fullmatch === 'string') {
if (state?.fields?.find((f) => f.name == field.name)) field.fullmatch = (state.fields.find((f) => f.name == field.name).fullmatch?'checked':'unchecked');
controls.append('<input type="checkbox" tabindex="2" class="lt-search-form-fullmatch"' + (field.fullmatch=='checked'?' checked':'') + '>'
+ (options.controls?.fullmatch ?? 'Full match'));
}
form.append(label, item, controls);
}
let buttons = $('<div class="lt-search-form-buttons"/>');
buttons.append('<input type="button" class="lt-search-form-submit" tabindex="1" value="' + (options.controls?.submit ?? 'Search') + '">');
buttons.find('.lt-search-form-submit').on('click', doSearch);
if (options.controls?.clear) {
buttons.append('<input type="button" class="lt-search-form-clear" tabindex="1" value="' + options.controls.clear + '">');
buttons.find('.lt-search-form-clear').on('click', doSearchClear);
}
if (options.controls?.limit) {
let label = $('<label for="lt-search-limit">' + (options.controls.limit.label ?? 'Max. results') + ' </label>');
let input = $('<select class="lt-search-limit"/>');
for (let option of options.controls.limit.options) {
input.append('<option value="' + option + '">' + option + '</option>');
}
if (state?.limit) input.val(state.limit);
buttons.append(label, input);
}
form.append(buttons);
div.append(form);
}
function doSearch() {
let form = $(this).closest('.lt-search-form');
let options = JSON.parse(atob(form.parent().data().options));
let data = { mode: 'search', src: form.parent().data().source, fields: [] };
for (let field of options.fields) {
let input = form.find('input[name=' + field.name + ']');
if (!input.length) input = form.find('select[name=' + field.name + ']');
let val = input.val();
if (!val || !val.length) continue;
let content = { name: field.name, value: val };
let controls = input.next();
if (typeof field.fullmatch === 'string') content.fullmatch = controls.find('.lt-search-form-fullmatch').prop('checked');
data.fields.push(content);
}
let state = { fields: data.fields };
if (options.controls?.limit) {
let limit = form.find('.lt-search-limit').val();
if (limit) {
data.limit = limit;
state.limit = limit;
}
}
sessionStorage.setItem('lt_search:' + form.parent().data().source, JSON.stringify(state));
$.ajax({
method: 'post',
dataType: "json",
url: ajaxUrl,
data: data,
success: function(data) {
if (data.error) { appError(data.error, this); }
else {
loadOrRefreshCollection($('#' + options.target));
}
},
error: function(xhr, status) { }
});
}
function doSearchClear() {
let form = $(this).closest('.lt-search-form');
form.find('INPUT[type=text],SELECT').not('.lt-search-limit').val('').trigger('change');
sessionStorage.removeItem('lt_search:' + form.parent().data().source);
}
function loadControl(div, attr) {
let options = JSON.parse(atob(attr.options));
let classes = "lt-control-button";
if (options.class) classes += ' ' + options.class;
if (options.fields) {
for (let field of options.fields) {
if (field.length != 2) {
console.log('Invalid lt_control field option; ignoring', field);
continue;
}
div.append('<label>' + field[1] + ' <input type="text" class="lt-control-field" name="' + field[0] + '"></label>');
}
}
if (options.prev) {
if (typeof options.prev == 'object') {
div.append('<input type="button" class="' + classes + '" value="' + tr(options.prev[1]) + '" onclick="doNext(this, true)">');
}
else div.append('<input type="button" class="' + classes + '" value="' + tr('Previous') + '" onclick="doNext(this, true)">');
}
if (options.next) {
if (typeof options.next == 'object') {
div.append('<input type="button" class="' + classes + '" value="' + tr(options.next[1]) + '" onclick="doNext(this)">');
}
else div.append('<input type="button" class="' + classes + '" value="' + tr('Next') + '" onclick="doNext(this)">');
}
tables[attr.source] = {};
tables[attr.source].div = div;
tables[attr.source].options = options;
}
function loadTable(div, attr, sub) {
let key = attr.source;
let table = $('<table id="' + key + '" class="lt-table"/>');
if (attr.embedded) {
tables[key] = {};
tables[key].table = table;
let json = atob(attr.embedded.replace(/\n/g, ''));
let data = JSON.parse(json);
tables[key].data = data;
renderTable(table, data);
div.empty().append(tables[key].table);
div.removeAttr('embedded');
}
else if (tables[key] && tables[key].data && (tables[key].data.rowcount != -1) && tables[key].data.options && (tables[key].data.options.nocache !== true)) {
if (tables[key].doingajax) {
console.log('Skipping load for', key, '(already in progress)');
return;
}
tables[key].table = table;
console.log('Rendering table ' + key + ' from existing data');
renderTable(table, tables[key].data);
div.empty().append(tables[key].table);
refreshTable(table, key, true);
}
else {
tables[key] = {};
tables[key].table = table;
tables[key].start = Date.now();
tables[key].doingajax = true;
$.ajax({
dataType: "json",
url: ajaxUrl,
data: "mode=gettable&src=" + attr.source,
context: div,
success: function(data) {
if (data.error) {
this.empty().append('<p>Error from server while loading table. Technical information is available in the console log.</p>');
appError(data.error, this);
}
else {
data.downloadtime = Date.now() - tables[key].start - data.querytime;
if (this.data('active')) data.active = this.data('active');
tables[key].data = data;
renderTable(table, data, sub);
this.empty().append(tables[key].table);
if (data.options.callbacks && data.options.callbacks.load) window.setTimeout(data.options.callbacks.load.replace('#src', this.data('source')), 0);
}
tables[key].doingajax = false;
},
error: function(xhr, status) { this.empty().append('Error while loading table ' + this.data('source') + ' (' + status + ' from server)'); }
});
}
}
function refreshTable(table, key, force = false) {
if ((tables[key].data.options.autorefresh === false) && !force) return;
if (tables[key].doingajax) {
console.log('Skipping refresh on ' + key + ' (already in progress)');
return;
}
tables[key].start = Date.now();
tables[key].doingajax = true;
table.find('.lt-loading').show();
$.ajax({
dataType: "json",
url: ajaxUrl,
data: "mode=refreshtable&src=" + tables[key].data.block + ':' + tables[key].data.tag +
"&crc=" + tables[key].data.crc,
context: table,
success: function(data) {
let options = tables[key].data.options;
this.find('.lt-loading').hide();
if (data.error) appError(data.error, this);
else if (data.nochange); // No action
else {
tables[key].data.downloadtime = Date.now() - tables[key].start - data.querytime;
if (tables[key].data.headers.length != data.headers.length) {
console.log('Column count changed; reloading table');
tables[key].data.headers = data.headers;
tables[key].data.rows = data.rows;
tables[key].data.crc = data.crc;
tables[key].doingajax = false;
loadTable(this.parent(), this.parent().data());
return;
}
if (tables[key].data.options.showdiff === false) {
tables[key].data.rows = data.rows;
tables[key].data.crc = data.crc;
tables[key].data.total = data.total;
tables[key].data.querytime = data.querytime;
if (data.options?.selectany?.links) tables[key].data.options.selectany.links = data.options.selectany.links;
tables[key].doingajax = false;
renderTable(this.empty(), tables[key].data);
return;
}
let tbody = this.find('tbody');
if (!tbody.length) {
tbody = $('<tbody/>');
this.prepend(tbody);
}
if (data.rows.length) {
let thead = table.find('thead');
if (!thead.length) {
thead = $('<thead/>');
if (this.closest('.lt-div').data('sub') != 'true') thead.append(renderTitle(tables[key].data));
table.prepend(thead);
}
if (!thead.find('.lt-head').length && !tables[key].data.options.format) {
thead.append(renderHeaders(tables[key].data, this.attr('id')));
}
// else updateHeaders(thead, data); // BROKEN: doesn't support mouseover or other hidden columns
}
updateTable(tbody, tables[key].data, data.rows);
tables[key].data.rows = data.rows;
tables[key].data.crc = data.crc;
if (options.rowcount) {
let text = data.rows.length.toString();
if (data.total) text += ' ' + tr('of') + ' ' + data.total;
this.find('.lt-title > .lt-rowcount').text(text);
}
if (options.sum) updateSums(this.find('tfoot'), tables[key].data);
if (options.callbacks && options.callbacks.change) window.setTimeout(options.callbacks.change.replace('#src', this.parent().data('source')), 0);
}
if (options.tableaction && data.options && data.options.tableaction && ('sqlcondition' in data.options.tableaction)) {
options.tableaction.sqlcondition = data.options.tableaction.sqlcondition;
if (options.tableaction.sqlcondition) this.find('.lt-tableaction').show();
else this.find('.lt-tableaction').hide();
}
if (options.selectany?.links && data.options.selectany?.links) {
this.find('tbody').children().each(function() {
let id = Number(this.dataset.rowid);
if (data.options.selectany.links.indexOf(id) >= 0) $(this).children().first().find('input').prop('checked', true);
else $(this).children().first().find('input').prop('checked', false);
});
}
tables[key].doingajax = false;
}
});
}
function updateHeaders(thead, data) {
thead.find('.lt-head').each(function(i) {
let th = $(this);
if (th.html() != data.headers[i+1]) {
th.html(data.headers[i+1]).css('background-color', 'green');
setTimeout(function(th) { th.css('background-color', ''); }, 2000, th);
}
});
}
function sortOnColumn(a, b, index) {
if (a[index] === null) return -1;
if (a[index] === b[index]) return 0;
else if (a[index] < b[index]) return -1;
else return 1;
}
function colVisualToReal(data, idx) {
if (!data.options.mouseover && !data.options.hidecolumn && !data.options.selectone && !data.options.selectany && !data.options.showid && !data.options.groupby) return idx;
if (data.options.showid) idx--;
if (data.options.selectone) idx--;
if (data.options.selectany) idx--;
if (data.options.groupby) idx++;
for (let c = 0; c <= data.headers.length; c++) {
if (data.options.mouseover && data.options.mouseover[c]) idx++;
else if (data.options.hidecolumn && data.options.hidecolumn[c]) idx++;
if (c == idx) return c;
}
}
function sortBy(tableId, el) {
el = $(el);
let table = tables[tableId].table;
let data = tables[tableId].data;
if (data.options.sortby == el.html()) {
if (data.options.sortdir == 'ascending') data.options.sortdir = 'descending';
else data.options.sortdir = 'ascending';
}
else {
data.options.sortby = el.html();
data.options.sortdir = 'ascending';
}
console.log('Sort table ' + tableId + ' on column ' + el.html() + ' ' + data.options.sortdir);
let c = colVisualToReal(data, el.index()+1);
if (data.options.sortdir == 'ascending') {
data.rows.sort(function(a, b) { return sortOnColumn(a, b, c); });
el.siblings().removeClass('lt-sorted-asc lt-sorted-desc');
el.removeClass('lt-sorted lt-sorted-desc').addClass('lt-sorted-asc');
}
else {
data.rows.sort(function(a, b) { return sortOnColumn(b, a, c); });
el.siblings().removeClass('lt-sorted-asc lt-sorted-desc');
el.removeClass('lt-sorted lt-sorted-asc').addClass('lt-sorted-desc');
}
let tbody = table.find('tbody');
let rowcount = renderTbody(tbody, data);
let div = table.closest('#lt-fullscreen-div');
if (div.length) syncColumnWidths(div); // Table is in fullscreen mode
}
function goPage(tableId, which) {
let table = tables[tableId].table;
let data = tables[tableId].data;
let old = data.options.page;
if (isNaN(which)) {
if (which == 'prev') data.options.page -= 1;
else if (which == 'next') data.options.page += 1;
}
else data.options.page = which;
if ((data.options.page <= 0) || ((data.options.page-1) * data.options.limit > data.rows.length)) {
data.options.page = old;
return;
}
let rowcount = 1;
window.activeid = data.rows[data.options.page-1][0];
if (data.options.format) renderTableFormat(table.empty(), data);
else rowcount = renderTbody(table.find('tbody'), data);
if (data.options.limit) table.find('.lt-pages').html(tr('Page') + ' ' + data.options.page + ' ' + tr('of') + ' ' + Math.ceil(rowcount/data.options.limit));
}
function replaceHashes(str, row, returntype = false) {
if (str.indexOf('#') >= 0) {
str = str.replace(/#id/g, row[0]);
for (let c = row.length-1; c >= 0; c--) {
if (str.indexOf('#'+c) >= 0) {
if (returntype && (str == '#'+c)) return row[c];
let content;
if (row[c] === null) content = '';
else content = String(row[c]).replace('#', '\0');
str = str.replace(new RegExp('#'+c, 'g'), content);
}
}
}
return str.replace('\0', '#');
}
function renderTable(table, data, sub) {
let start = Date.now();
let filters = sessionStorage.getItem('lt_filters_' + data.block + '_' + data.tag);
if (filters) {
filters = JSON.parse(filters);
for (let i in filters) {
if (filters[i].startsWith('<') || filters[i].startsWith('>') || filters[i].startsWith('=')) continue;
filters[i] = new RegExp(filters[i], 'i');
}
data.filters = filters;
}
if (data.options.display && (data.options.display == 'list')) renderTableList(table, data, sub);
else if (data.options.display && (data.options.display == 'divs')) renderTableDivs(table, data, sub);
else if (data.options.display && (data.options.display == 'select')) renderTableSelect(table, data, sub);
else if (data.options.display && (data.options.display == 'vertical')) renderTableVertical(table, data, sub);
else if (data.options.format) renderTableFormat(table, data, sub);
else if (data.options.renderfunction) window[data.options.renderfunction](table, data);
else renderTableGrid(table, data, sub);
console.log('Load timings for ' + (sub?'sub':'') + 'table ' + data.tag + ': sql ' + (data.querytime?data.querytime:'n/a') +
' download ' + (data.downloadtime?data.downloadtime:'n/a') + ' render ' + (Date.now()-start) + ' ms');
}
// function renderTableVertical(table, data) {
// table.addClass('lt-insert');
// for (id in data.options.insert) {
// if (!$.isNumeric(id)) continue;
// let input = renderField(data.options.insert[id], table, data, id);
// let name;
// if (data.options.insert[id].name !== undefined) name = data.options.insert[id].name;
// else name = input.attr('name').split('.')[1];
// let label = '<label for="' + input.attr('name') + '">' + name + '</label>';
// let row = $('<tr><td class="lt-form-label">' + label + '</td><td class="lt-form-input"></td></tr>');
// row.find('.lt-form-input').append(input);
// table.append(row);
// }
// table.append('<tr><td colspan="2"><input type="button" class="lt-insert-button" value="' + tr('Insert') + '" onclick="doInsert(this)"></td></tr>');
// }
function renderTableSelect(table, data, sub) {
let section = $('<section class="lt-select"><h3>' + data.title + '</h3>');
let select;
if (data.options.selectone) {
if (typeof selectones == 'undefined') selectones = 1;
else selectones++;
select = '<select name="select' + selectones + '">';
}
else select = '<select>';
if (data.options.placeholder) select += '<option value="" disabled selected hidden>' + data.options.placeholder + '</option>';
for (let r = 0; r < data.rows.length; r++) { // Main loop over the data rows
if (!data.rows[r][2]) select += '<option value="' + data.rows[r][0] + '">' + escape(data.rows[r][1]) + '</option>';
else select += '<option value="' + data.rows[r][0] + '">' + escape(data.rows[r][1]) + ' (' + escape(data.rows[r][2]) + ')</option>';
}
select += '</select>';
section.append(select);
if (data.options.selectone && data.options.selectone.default) {
if (data.options.selectone.default == 'first') section.find('select').prop('selectedIndex', 0);
else if (data.options.selectone.default == 'last') section.find('select').prop('selectedIndex', data.rows.length-1);
}
else if (!data.options.placeholder) section.find('select').prop('selectedIndex', -1);
let key = table.attr('id');
tables[key].table = section;
}
function renderTableDivs(table, data, sub) {
let container = $('<div class="lt-div-table"/>');
container.attr('id', table.attr('id'));
if (data.options.class && data.options.class.table) container.addClass(data.options.class.table);
let items = '';
for (let r = 0; r < data.rows.length; r++) { // Main loop over the data rows
let classes = '';
if (Number.isInteger(data.options.classcolumn)) classes = ' ' + data.rows[r][data.options.classcolumn];
items += '<div class="lt-div-row' + classes + '" data-rowid="' + data.rows[r][0] + '">';
if (data.options.rowlink) items += '<a href="' + replaceHashes(data.options.rowlink, data.rows[r]) + '">';
for (let c = 1; c < data.rows[r].length; c++) { // Loop over the columns
if (data.options.hidecolumn && data.options.hidecolumn[c]) continue;
if (c === data.options.classcolumn) continue;
items += renderCell(data.options, data.rows[r], c, 'div');
}
if (data.options.appendcell) items += '<div class="lt-cell lt-append">' + replaceHashes(data.options.appendcell, data.rows[r]) + '</div>';
if (data.options.rowlink) items += '</a>';
items += '</div>';
}
container.append($(items));
tables[container.attr('id')].table = container;
}
function listClick(el) {
$(el).find('input').prop('checked', true);
}
function renderTableList(table, data, sub) {
let section = $('<section class="lt-list"><h3>' + data.title + '</h3>');
let ul = '<ul>';
if (data.options.selectone) {
if (typeof selectones == 'undefined') selectones = 1;
else selectones++;
}
for (let r = 0; r < data.rows.length; r++) { // Main loop over the data rows
let style;
if (data.options.style && data.options.style.list) style = ' style="' + replaceHashes(data.options.style.list, data.rows[r]) + '"';
else style = '';
ul += '<li data-rowid="' + data.rows[r][0] + '"' + style + ' onclick="listClick(this);">';
if (data.options.selectone) {
let trigger;
if (data.options.selectone.trigger) trigger = ' data-trigger="' + data.options.selectone.trigger + '"';
else trigger = '';
if (data.options.style && data.options.style.selectone) style = ' style="' + replaceHashes(data.options.style.selectone, data.rows[r]) + '"';
else style = '';
ul += '<span><input type="radio" name="select' + selectones + '" ' + trigger + style + '></span>';
}
ul += escape(data.rows[r][1]);
}
ul += '</ul>';
section.append(ul);
if (data.options.selectone && data.options.selectone.default) {
if (data.options.selectone.default == 'first') section.find('input[name^=select]:first').prop('checked', true);
else if (data.options.selectone.default == 'last') section.find('input[name^=select]:last').prop('checked', true);
}
let key = table.attr('id');
tables[key].table = section;
}
function renderTableFormat(table, data, sub) {
if (data.options.class && data.options.class.table) table.addClass(data.options.class.table);
let headstr;
if (data.options.hideheader) headstr = '';
else headstr = renderTitle(data);
if (window.activeid) { data.active = window.activeid; data.options.page = null; }
if (!data.options.page) {
if (data.active) {
for (let r = 0; data.rows[r]; r++) {
if (data.rows[r][0] == data.active) {
data.options.page = r+1;
break;
}
}
}
if (!data.options.page) data.options.page = 1;
}
let offset = data.options.page - 1;
if (data.rows && data.rows.length > 1) {
headstr += '<tr class="lt-limit"><th colspan="' + data.headers.length + '">';
headstr += '<a href="javascript:goPage(\'' + table.attr('id') + '\', \'prev\')"><span class="lt-page-control"><</span></a> ';
headstr += (data.options.pagename?data.options.pagename:tr('Row')) + ' ' + data.options.page + ' ' + tr('of') + ' ' + data.rows.length;
headstr += ' <a href="javascript:goPage(\'' + table.attr('id') + '\', \'next\')"><span class="lt-page-control">></span></a></th></tr>';
}
let thead = $('<thead>' + headstr + '</thead>');
let tbody, fmt;
if (data.options.format.indexOf('I') < 0) tbody = $('<tbody/>');
else tbody = $('<tbody class="lt-insert"/>');
if (data.options.pagetitle && data.rows && data.rows[offset]) {
document.title = replaceHashes(data.options.pagetitle, data.rows[offset]);
}
renderTableFormatBody(tbody, data, offset);
table.append(thead, tbody);
table.parent().data('crc', data.crc);
if (data.options.subtables) loadOrRefreshCollection(tbody.find('.lt-div'), true);
}
function renderTableFormatBody(tbody, data, offset) {
let headcount = 0;
let colcount = 0;
let inscount = 0;
let actcount = 0;
let appcount = 0;
let actions;
let colspan;
let rowspan = 0;
let fmt;
if (typeof(data.options.format) == 'string') fmt = data.options.format.split('\n');
else fmt = data.options.format;
if (data.options.rowaction) actions = $(renderActions(data.options.rowaction, data.rows[offset]));
for (let r = 0; fmt[r]; r++) {
let row = $('<tr class="lt-row" data-rowid="' + (data.rows && data.rows[offset]?data.rows[offset][0]:0) + '"/>');
for (let c = 0; fmt[r][c]; c++) {
if (fmt[r][c] == 'H') {
if (headcount++ >= data.headers.length) {
appError('Too many headers specified in format string for ' + data.block + ':' + data.tag, data.options.format);
break;
}
while (data.options.mouseover && data.options.mouseover[headcount]) headcount++;
while (data.options.hidecolumn && data.options.hidecolumn[headcount]) headcount++;
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
let tdstr = '<td class="lt-head"' + (colspan > 1?' colspan="' + colspan + '"':'') + (rowspan > 1?' rowspan="' + rowspan + '"':'') + '>';
tdstr += tr(data.headers[headcount]);
if (data.options.subheader && data.options.subheader[headcount]) tdstr += '<div class="lt-subhead">' + data.options.subheader[headcount] + '</div>';
tdstr += '</td>';
row.append(tdstr);
}
else if (fmt[r][c] == 'C') {
if (colcount++ >= data.rows[offset].length) {
appError('Too many columns specified in format string for ' + data.block + ':' + data.tag, data.options.format);
break;
}
while (data.options.mouseover && data.options.mouseover[colcount]) colcount++;
while (data.options.hidecolumn && data.options.hidecolumn[colcount]) colcount++;
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
let cell = $(renderCell(data.options, data.rows[offset], colcount));
if (colspan > 1) cell.attr('colspan', colspan);
if (rowspan > 1) cell.attr('rowspan', rowspan);
row.append(cell);
}
else if (fmt[r][c] == 'I') {
let insert;
inscount++;
let count = 0;
let colid;
for (let i in data.options.insert) {
if (!$.isNumeric(i)) continue;
if (++count === inscount) {
insert = data.options.insert[i];
colid = colcount+inscount;
break;
}
}
if (!insert) {
appError('Too many insert cells specified in format string for ' + data.block + ':' + data.tag, data.options.format);
break;
}
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
let td = $('<td class="lt-cell"' + (colspan > 1?' colspan="' + colspan + '"':'') + (rowspan > 1?' rowspan="' + rowspan + '"':'') + '/>');
let input = renderField(insert, table, data, colid);
if (input.prop('required')) td.addClass('lt-input-required');
td.append(input);
row.append(td);
}
else if (fmt[r][c] == 'S') {
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
row.append(renderInsertButton(data.options.insert, colspan, rowspan));
row.parent().find('INPUT[type=text],SELECT').on('keyup', function(e) { if (e.keyCode == 13) $(this).closest('tbody').find('.lt-insert-button').click(); });
}
else if ((fmt[r][c] == 'A') && data.options.appendcell) {
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
let tdstr = '<td class="lt-cell lt-append"' + (colspan > 1?' colspan="' + colspan + '"':'') + (rowspan > 1?' rowspan="' + rowspan + '"':'') + '>';
if ((appcount > 0) && (!data.options.appendcell[appcount])) {
appError('Too many append cells specified in format string for ' + data.block + ':' + data.tag, data.options.format);
break;
}
let cell = data.options.appendcell[appcount] || data.options.appendcell;
if (data.rows && data.rows[offset]) tdstr += replaceHashes(cell, data.rows[offset]) + '</td>';
else tdstr += cell + '</td>';
row.append(tdstr);
appcount++;
}
else if ((fmt[r][c] == 'R') && (actions[actcount])) {
for (rowspan = 1; fmt[r+rowspan] && fmt[r+rowspan][c] == '|'; rowspan++);
for (colspan = 1; fmt[r][c+colspan] == '-'; colspan++);
actions[actcount].colSpan = colspan;
actions[actcount].rowSpan = rowspan;
row.append(actions[actcount]);
actcount++;
}