-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
1509 lines (1320 loc) · 46 KB
/
index.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
/**
* @fileOverview This implements DataHarmonizer, a browser-based spreadsheet
* application that operates off of LinkML templates. Currently can be run
* locally without a webserver, thus providing ease-of-use and security.
* Functionality for uploading, downloading and validating data.
* Implemented with https://handsontable.com/ "handsontable" widget.
*
* NOTE: If you are using Chrome javascript debugger console: using this
* tool disables double clicking on HandsonTable cells, so you won't see
* column help or cell insert/delete row actions, and it seems to disable
* the createHot afterRender event/method.
*
* templates/menu.js provides a list of templates available for this widget,
* which will be displayed in a menu. A template can also be accessed by adding
* it as a folder name in the URL parameter. This enables testing of a template
* even if it hasn't been incorporated into the menu.
*
* main.html?template=MIxS/soil
*
* MIxS example schemas are available at:
* https://github.com/GenomicsStandardsConsortium/mixs-source/tree/main/model/schema
*
*/
const VERSION = '1.0.0';
const VERSION_TEXT = 'DataHarmonizer provenance: v' + VERSION;
let DataHarmonizer = {
//An instance of DataHarmonizer has a schema, a domElement, and a handsontable .hot object
dhGrid: null,
dhFooter: null,
schema_name: null,
template_name: null,
template_path: null,
schema: null, // Schema holding all templates
template: null, // Specific template from schema
table: null, // Table data.
hot: null,
hot_settings: null,
menu: null,
export_formats: {}, // Formats that a given template can export to.
invalid_cells: null,
// Currently selected cell range[row,col,row2,col2]
current_selection: [null,null,null,null],
field_settings: {},
init: function(dhGrid, dhFooter=null, menu=null) {
this.dhGrid = dhGrid;
this.dhFooter = dhFooter;
this.menu = menu;
this.self = this;
// Field descriptions. Need to account for dynamically rendered cells.
$(this.dhGrid).on('dblclick', '.secondary-header-cell', (e) => {
const innerText = e.target.innerText;
const field = this.getFields().filter(field => field.title === innerText)[0];
$('#field-description-text').html(this.getComment(field));
$('#field-description-modal').modal('show');
});
// Add more rows. Here because it needs referenc to self.hot
$(this.dhFooter).find('.add-rows-button').click((e) => {
this.runBehindLoadingScreen(function() {
const numRows = $(this.dhFooter).find('.add-rows-input').val();
this.hot.alter('insert_row', this.hot.countRows()-1 + numRows, numRows);
});
});
},
useSchema: async function(template_folder) {
if (!this.schema || this.schema.folder != template_folder) {
try {
this.schema_name = template_folder;
return (await this.reloadJs('schema.js'));
}
catch (err) {
// Problem loading schema
return false;
}
}
return this.schema_name
},
/**
* Determines template_path from a URL parameter ?template=Folder/name,
* or a default value from first template in menu.js
*/
getTemplate: function () {
let template_path = null;
if (window.URLSearchParams) {
let params = new URLSearchParams(location.search);
template_path = params.get('template');
}
else {//low-tech way:
template_path = location.search.split("template=")[1];
}
// Validate path if not null:
if (template_path) {
[template_folder, template_name] = template_path.split('/',2);
if (!(template_folder in this.menu || template_name in this.menu[template_folder]) ) {
return false;
}
}
// If null, do default template setup - the first one in menu
else {
// Default template is first key in menu structure
const template_folder = Object.keys(this.menu)[0];
const template_name = Object.keys(this.menu[template_folder])[0];
template_path = template_folder + '/' + template_name;
}
return template_path;
},
/**
* Revise user interface elements to match template path, and trigger
* load of schema.js and export.js scripts (if necessary).
*
* @param {String} template_path: path of template starting from app's
* template/ folder.
*/
useTemplate: async function(template_path) {
if (!template_path)
return false; // Error condition: no template path provided
[template_folder, template_name] = template_path.split('/',2);
this.schema_name = template_folder;
this.template_name = template_name;
this.template_path = template_path;
try {
// Loading this template may require loading the SCHEMA it is under.
const schema_loaded = await this.useSchema(template_folder);
//if (!schema_loaded)
// return false;
this.processTemplate(template_name);
this.createHot();
// Asynchronous. Since SCHEMA loaded, export.js should succeed as well.
await this.reloadJs('export.js');
return template_name;
}
catch(err) {
console.log(err);
$('#missing-template-msg').text(`Unable to load template at path "${template_path}". Path should consist of [template folder name]/[template name] with correct capitalization.`);
$('#missing-template-modal').modal('show');
return false;
}
},
/**
* Open file specified by user.
* Only opens `xlsx`, `xlsx`, `csv` and `tsv` files. Will launch the specify
* headers modal if the file's headers do not match the grid's headers.
* @param {File} file User file.
* @param {Object} xlsx SheetJS variable.
* @return {Promise<>} Resolves after loading data or launching specify headers
* modal.
*/
/**
* Loads a given javascript file.
*
* @param {String} file_name: File in templates/[current schema]/ to load.
*/
openFile: async function(dh, file_name) {
try {
let contentBuffer = await dh.readFileAsync(file_name);
dh.loadSpreadsheetData (contentBuffer);
}
catch(err) {
console.log(err);
}
},
validate: function(){
this.invalid_cells = this.getInvalidCells();
this.hot.render();
},
newHotFile: function () {
let self = this;
//this.runBehindLoadingScreen( () => {
self.createHot();
//});
},
/**
* Create a blank instance of Handsontable.
* @param {Object} template.
* @return {Object} Handsontable instance.
*/
createHot: function () {
const self = this;
this.invalid_cells = {};
if (this.hot) {
this.hot.destroy(); // handles already existing data
this.hot = null;
}
let fields = this.getFields();
if (fields.length) {
this.hot_settings = {
data: [], // Enables true reset
nestedHeaders: this.getNestedHeaders(),
columns: this.getColumns(),
colHeaders: true,
rowHeaders: true,
manualColumnResize: true,
//colWidths: [100], //Just fixes first column width
contextMenu: ["remove_row","row_above","row_below"],
minRows: 100,
minSpareRows: 100,
width: '100%',
height: '75vh',
fixedColumnsLeft: 1,
hiddenColumns: {
copyPasteEnabled: true,
indicators: true,
columns: [],
},
hiddenRows: {
rows: [],
},
// Handsontable's validation is extremely slow with large datasets
invalidCellClassName: '',
licenseKey: 'non-commercial-and-evaluation',
// beforeChange source: https://handsontable.com/docs/8.1.0/tutorial-using-callbacks.html#page-source-definition
beforeChange: function(changes, source) {
if (!changes) return;
// When a change in one field triggers a change in another field.
let triggered_changes = [];
for (const change of changes) {
const column = change[1];
// Check field change rules
self.fieldChangeRules(change, fields, triggered_changes);
}
// Add any indirect field changes onto end of existing changes.
if (triggered_changes)
changes.push(...triggered_changes);
},
afterInit: () => {
$('#next-error-button, #no-error-button').hide();
},
afterSelection: (row, column, row2, column2, preventScrolling, selectionLayerLevel) => {
self.current_selection = [row, column, row2, column2];
},
afterRender: (isForced) => {
$('.data-harmonizer-header').css('visibility', 'visible');
$('.data-harmonizer-footer').css('visibility', 'visible');
// Bit of a hackey way to RESTORE classes to secondary headers. They are
// removed by Handsontable when re-rendering main table.
$('.secondary-header-text').each((_, e) => {
const $cellElement = $(e).closest('th');
$cellElement.addClass('secondary-header-cell');
if ($(e).hasClass('required')) {
$cellElement.addClass('required');
} else if ($(e).hasClass('recommended')) {
$cellElement.addClass('recommended');
}
});
},
afterRenderer: (TD, row, col) => {
if (self.invalid_cells.hasOwnProperty(row)) {
if (self.invalid_cells[row].hasOwnProperty(col)) {
const msg = self.invalid_cells[row][col];
$(TD).addClass(msg ? 'empty-invalid-cell' : 'invalid-cell');
}
}
},
};
this.hot = Handsontable(this.dhGrid, this.hot_settings);
this.enableMultiSelection();
}
else {
console.log("This template had no sections and fields: " + this.template_path)
}
},
/**
* Modify visibility of columns in grid. This function should only be called
* after clicking a DOM element used to toggle column visibilities.
* @param {String} id Id of element clicked to trigger this function. Defaults to show all.
* @param {Object} data See TABLE.
* @param {Object} hot Handsontable instance of grid.
*/
changeColVisibility: function (id = 'show-all-cols-dropdown-item') {
// Grid becomes sluggish if viewport outside visible grid upon re-rendering
this.hot.scrollViewportTo(0, 1);
const domEl = $('#' + id);
// Un-hide all currently hidden cols
const hiddenColsPlugin = this.hot.getPlugin('hiddenColumns');
hiddenColsPlugin.showColumns(hiddenColsPlugin.hiddenColumns);
// Hide user-specied cols
const hiddenColumns = [];
// If accessed by menu, disable that menu item, and enable the others
$('#show-all-cols-dropdown-item, #show-required-cols-dropdown-item, #show-recommended-cols-dropdown-item, .show-section-dropdown-item')
.removeClass('disabled');
domEl.addClass('disabled');
//Request may be for only required fields, or required+recommended fields
let required = (id === 'show-required-cols-dropdown-item');
let recommended = (id === 'show-recommended-cols-dropdown-item');
if (required || recommended) {
this.getFields().forEach(function(field, i) {
if (required && !field.required)
hiddenColumns.push(i);
else
if (recommended && !(field.required || field.recommended))
hiddenColumns.push(i);
});
}
// prefix of ID indicates if it is a command to show just one section.
else if (id.indexOf('show-section-') === 0) {
const section_name = domEl.text();
let column_ptr = 0;
for (section of this.template) {
for (column of section.children) {
// First condition ensures first (row identifier) column is not hidden
if (column_ptr > 0 && section.title != section_name) {
hiddenColumns.push(column_ptr)
}
column_ptr ++;
}
};
}
hiddenColsPlugin.hideColumns(hiddenColumns);
this.hot.render();
},
/**
* Modify visibility of rows in grid. This function should only be called
* after clicking a DOM element used to toggle row visibilities.
* @param {String} id Id of element clicked to trigger this function.
* @param {Object<Number, Set<Number>>} invalidCells See `getInvalidCells`
* return value.
* @param {Object} hot Handsontable instance of grid.
*/
changeRowVisibility: function (id, invalidCells) {
// Grid becomes sluggish if viewport outside visible grid upon re-rendering
this.hot.scrollViewportTo(0, 1);
// Un-hide all currently hidden cols
const hiddenRowsPlugin = this.hot.getPlugin('hiddenRows');
hiddenRowsPlugin.showRows(hiddenRowsPlugin.hiddenRows);
// Hide user-specified rows
const rows = [...Array(this.hot.countRows()).keys()];
const emptyRows = rows.filter(row => this.hot.isEmptyRow(row));
let hiddenRows = [];
if (id === 'show-valid-rows-dropdown-item') {
hiddenRows = Object.keys(this.invalid_cells).map(Number);
hiddenRows = [...hiddenRows, ...emptyRows];
}
else if (id === 'show-invalid-rows-dropdown-item') {
const invalidRowsSet = new Set(Object.keys(this.invalid_cells).map(Number));
hiddenRows = rows.filter(row => !invalidRowsSet.has(row));
hiddenRows = [...hiddenRows, ...emptyRows];
}
hiddenRowsPlugin.hideRows(hiddenRows);
this.hot.render();
},
/**
* Presents reference guide in a popup.
* @param {String} mystyle simple css stylesheet commands to override default.
*/
renderReference: function(mystyle = null) {
let schema_template = this.schema.classes[this.template_name]
let style = `
body {
font-family: arial;
margin:5% 5% 5% 5%;
}
table {
width: 100%;
table-layout: fixed;
}
table tr.section {
background-color:#f0f0f0;
padding:10px;
font-size:1.5rem;
}
table th {font-weight: bold; text-align: left; font-size:1.3rem;}
table th.label {font-weight:bold; width: 25%}
table th.description {width: 20%}
table th.guidance {width: 30%}
table th.example {width: 15%}
table th.data_status {width: 15%}
table td {vertical-align: top; padding:5px;border-bottom:1px dashed silver;}
table td.label {font-weight:bold;}
ul { padding: 0; }
`;
if (mystyle != null)
style = mystyle;
let row_html = '';
for (section of this.template) {
row_html +=
`<tr class="section">
<td colspan="5"><h3>${section.title || section.name}</h3></td>
</tr>
`
for (slot of section.children) {
const slot_dict = this.getCommentDict(slot);
row_html +=
`<tr>
<td class="label">${slot_dict.title}</td>
<td>${slot_dict.description}</td>
<td>${slot_dict.guidance}</td>
<td>${slot_dict.examples}</td>
<td>${slot_dict.sources || ''}</td>
</tr>
`
}
}
var win = window.open("", "Reference", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=1000,height=600");
win.document.head.innerHTML = `
<meta charset="utf-8">
<title>Reference guide for "${schema_template.title || schema_template.name}" template</title>
<meta name="description" content="${schema_template.description || ''}">
<style>${style}</style>
`
win.document.body.innerHTML = `
<div>
<h2>Reference guide for "${schema_template.title || schema_template.name}" template</h2>
<hr size="2"/>
<p>${schema_template.description || ''}</p>
<table>
<thead>
<tr>
<th class="label">Field</th>
<th class="description">Description</th>
<th class="guidance">Guidance</th>
<th class="example">Examples</th>
<th class="data_status">Menus</th>
</tr>
</thead>
<tbody>
${row_html}
</tbody>
</table>
</div>
</body>
</html>
`
return false;
},
/**
* Get the 0-based y-index of every field on the grid.
* @param {Object} data See TABLE.
* @return {Object<String, Number>} Fields mapped to their 0-based y-index on
* the grid.
*/
getFieldYCoordinates: function () {
const ret = {};
for (const [i, field] of this.getFields().entries()) {
ret[field.title] = i;
}
return ret;
},
getColumnCoordinates: function () {
const ret = {};
let column_ptr = 0;
for (section of this.template) {
ret[section.title] = column_ptr;
for (column of section.children) {
ret[' . . ' + column.title] = column_ptr;
column_ptr ++;
}
}
return ret;
},
/**
* Scroll grid to specified column.
* @param {String} row 0-based index of row to scroll to.
* @param {String} column 0-based index of column to scroll to.
* @param {Object} data See TABLE.
* @param {Object} hot Handsontable instance of grid.
*/
scrollTo: function (row, column) {
const hiddenCols = this.hot.getPlugin('hiddenColumns').hiddenColumns;
if (hiddenCols.includes(column))
// If user wants to scroll to a hidden column, make all columns unhidden
this.changeColVisibility(undefined);
this.hot.selectCell(parseInt(row), parseInt(column), parseInt(row), parseInt(column), true);
//Ensures field is positioned on left side of screen.
this.hot.scrollViewportTo(row, column);
},
/**
* Run void function behind loading screen.
* Adds function to end of call queue. Does not handle functions with return
* vals, unless the return value is a promise. Even then, it only waits for the
* promise to resolve, and does not actually do anything with the value
* returned from the promise.
* @param {function} fn - Void function to run.
* @param {Array} [args=[]] - Arguments for function to run.
*/
runBehindLoadingScreen: async function(fn, args=[]) {
await $('#loading-screen').show('fast', 'swing');
await this.wait(200); // Enough of a visual cue that something is happening
if (args.length)
await fn.apply(this, args);
else {
await fn.apply(this);
}
await $('#loading-screen').hide();
return
},
// wait ms milliseconds
wait: function (ms) {
return new Promise(r => setTimeout(r, ms));
},
/***************************** PRIVATE functions *************************/
// https://simon-schraeder.de/posts/filereader-async/
readFileAsync: function (file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
};
reader.onerror = reject;
reader.readAsBinaryString(file);
//reader.readAsArrayBuffer(file);
})
},
loadSpreadsheetData: function (data) {
const workbook = XLSX.read(data, {
type: 'binary',
raw: true,
cellDates: true, // Ensures date formatted as YYYY-MM-DD dates
dateNF: 'yyyy-mm-dd' //'yyyy/mm/dd;@'
});
const worksheet = this.updateSheetRange(workbook.Sheets[workbook.SheetNames[0]]);
const matrix = (XLSX.utils.sheet_to_json(
worksheet,
{
header: 1,
raw: false,
range: 0
}
));
const headerRowData = this.compareMatrixHeadersToGrid(matrix);
if (headerRowData > 0) {
this.hot.loadData(this.matrixFieldChangeRules(matrix.slice(headerRowData)));
}
else {
this.launchSpecifyHeadersModal(matrix);
}
},
/**
* Improve `XLSX.utils.sheet_to_json` performance for Libreoffice Calc files.
* Ensures sheet range is accurate. See
* https://github.com/SheetJS/sheetjs/issues/764 for more detail.
* @param {Object} worksheet SheetJs object.
* @returns {Object} SheetJs worksheet with correct range.
*/
updateSheetRange: function (worksheet) {
const range = {s:{r:20000000, c:20000000},e:{r:0,c:0}};
Object.keys(worksheet)
.filter((x) => {return x.charAt(0) !== '!'})
.map(XLSX.utils.decode_cell).forEach((x) => {
range.s.c = Math.min(range.s.c, x.c);
range.s.r = Math.min(range.s.r, x.r);
range.e.c = Math.max(range.e.c, x.c);
range.e.r = Math.max(range.e.r, x.r);
});
worksheet['!ref'] = XLSX.utils.encode_range(range);
return worksheet;
},
/**
* Ask user to specify row in matrix containing secondary headers before load.
* Calls `alertOfUnmappedHeaders` if necessary.
* @param {Array<Array<String>} matrix Data that user must specify headers for.
* @param {Object} hot Handsontable instance of grid.
* @param {Object} data See `data.js`.
*/
launchSpecifyHeadersModal: function(matrix) {
let flatHeaders = this.getFlatHeaders();
const self = this;
if (flatHeaders) {
$('#field-mapping').prepend('<col></col>'.repeat(flatHeaders[1].length+1));
$('#expected-headers-tr')
.html('<td><b>Expected second row</b></td> <td>' + flatHeaders[1].join('</td><td>') + '</td>');
$('#actual-headers-tr')
.html('<td><b>Imported second row</b></td> <td>' + matrix[1].join('</td><td>') + '</td>');
flatHeaders[1].forEach(function (item, i) {
if (item != matrix[1][i])
$('#field-mapping col').get(i+1).style.backgroundColor = "orange";
});
$('#specify-headers-modal').modal('show');
$('#specify-headers-confirm-btn').click(() => {
const specifiedHeaderRow = parseInt($('#specify-headers-input').val());
if (!this.isValidHeaderRow(matrix, specifiedHeaderRow)) {
$('#specify-headers-err-msg').show();
}
else {
const mappedMatrixObj = self.mapMatrixToGrid(matrix, specifiedHeaderRow-1);
$('#specify-headers-modal').modal('hide');
this.runBehindLoadingScreen(() => {
self.hot.loadData(self.matrixFieldChangeRules(mappedMatrixObj.matrix.slice(2)));
if (mappedMatrixObj.unmappedHeaders.length) {
const unmappedHeaderDivs = mappedMatrixObj.unmappedHeaders.map(header => `<li>${header}</li>`);
$('#unmapped-headers-list').html(unmappedHeaderDivs);
$('#unmapped-headers-modal').modal('show');
}
});
}
});
}
},
/**
* Determine if first or second row of a matrix has the same headers as the
* grid's secondary (2nd row) headers. If neither, return false.
* @param {Array<Array<String>>} matrix
* @param {Object} data See `data.js`.
* @return {Integer} row that data starts on, or false if no exact header row
* recognized.
*/
compareMatrixHeadersToGrid: function (matrix) {
const expectedSecondRow = this.getFlatHeaders()[1];
const actualFirstRow = matrix[0];
const actualSecondRow = matrix[1];
if (JSON.stringify(expectedSecondRow) === JSON.stringify(actualFirstRow))
return 1;
if (JSON.stringify(expectedSecondRow) === JSON.stringify(actualSecondRow))
return 2;
return false;
},
/**
* Validates `$('#specify-headers-input')` input.
* @param {Array<Array<String>>} matrix
* @param {number} row 1-based index used to indicate header row in matrix.
*/
isValidHeaderRow: function (matrix, row) {
return Number.isInteger(row) && row > 0 && row <= matrix.length;
},
/**
* Create a matrix containing the grid's headers. Empty strings are used to
* indicate merged cells.
* @return {Array<Array<String>>} Grid headers.
*/
getFlatHeaders: function() {
const rows = [[], []];
for (const parent of this.template) {
let min_cols = parent.children.length;
if (min_cols < 1) {
// Close current dialog and switch to error message
//$('specify-headers-modal').modal('hide');
//$('#unmapped-headers-modal').modal('hide');
const errMsg = `The template for the loaded file has a configuration error:<br/>
<strong>${parent.title}</strong><br/>
This is a field that has no parent, or a section that has no fields.`;
$('#unmapped-headers-list').html(errMsg);
$('#unmapped-headers-modal').modal('show');
return false;
}
rows[0].push(parent.title);
// pad remainder of first row columns with empty values
if (min_cols > 1)
rows[0].push(...Array(min_cols-1).fill(''));
// Now add 2nd row child titles
rows[1].push(...parent.children.map(child => child.title));
}
return rows;
},
/**
* Map matrix columns to grid columns.
* Currently assumes mapped columns will have the same label, but allows them
* to be in a different order. If the matrix is missing a column, a blank
* column is used.
* @param {Array<Array<String>>} matrix
* @param {Number} matrixHeaderRow Row containing matrix's column labels.
* @return {MappedMatrixObj} Mapped matrix and details.
*/
mapMatrixToGrid: function (matrix, matrixHeaderRow) {
const expectedHeaders = this.getFlatHeaders();
const expectedSecondaryHeaders = expectedHeaders[1];
const actualSecondaryHeaders = matrix[matrixHeaderRow];
// Map current column indices to their indices in matrix to map
const headerMap = {};
const unmappedHeaders = [];
for (const [i, expectedVal] of expectedSecondaryHeaders.entries()) {
headerMap[i] = actualSecondaryHeaders.findIndex((actualVal) => {
return actualVal === expectedVal;
});
if (headerMap[i] === -1) unmappedHeaders.push(expectedVal);
}
const dataRows = matrix.slice(matrixHeaderRow + 1);
const mappedDataRows = [];
// Iterate over non-header-rows in matrix to map
for (const i of dataRows.keys()) {
mappedDataRows[i] = [];
// Iterate over columns in current validator version
for (const j of expectedSecondaryHeaders.keys()) {
// -1 means the matrix to map does not have this column
if (headerMap[j] === -1) {
mappedDataRows[i][j] = '';
}
else {
mappedDataRows[i][j] = dataRows[i][headerMap[j]];
}
}
}
return {
matrix: [...expectedHeaders, ...mappedDataRows],
unmappedHeaders: unmappedHeaders,
};
},
/**
* Download matrix to file.
* Note that BOM and UTF-8 can create problems on some systems when importing
* file. See "Supported Output Formats" and "UTF-16 Unicode Text" sections of
* https://reactian.com/sheetjs-community-edition-spreadsheet-data-toolkit/
* and https://github.com/SheetJS/sheetjs
* Solution at bottom of: https://github.com/SheetJS/sheetjs/issues/943
* The "Comma Separated Values" format is actually UTF-8 with BOM prefix.
* @param {Array<Array<String>>} matrix Matrix to download.
* @param {String} baseName Basename of downloaded file.
* @param {String} ext Extension of downloaded file.
*/
exportFile: function (matrix, baseName, ext) {
const worksheet = XLSX.utils.aoa_to_sheet(matrix);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
switch (ext) {
case 'xlsx':
XLSX.writeFile(workbook, `${baseName}.xlsx`);
break;
case 'xls':
XLSX.writeFile(workbook, `${baseName}.xls`);
break;
case 'tsv':
XLSX.writeFile(workbook, `${baseName}.tsv`, {bookType: 'csv', FS: '\t'});
break;
case 'csv':
XLSX.writeFile(workbook, `${baseName}.csv`, {bookType: 'csv', FS: ','});
break;
case 'tsv (UTF-16)':
XLSX.writeFile(workbook, `${baseName}.tsv`, {bookType: 'txt', FS: '\t'});
break;
case 'csv (UTF-16)':
XLSX.writeFile(workbook, `${baseName}.csv`, {bookType: 'txt', FS: ','});
break;
case 'csv (UTF-8, no BOM)':
//Customization: skips BOM prefix '\uFEFF'
const csv = XLSX.utils.sheet_to_csv(worksheet, {FS: ','});
const blob = new Blob([csv], {type: 'text/plain;charset=UTF-8'});
//A FileSaver module call, avoids {autoBom: true} parameter
saveAs(blob, `${baseName}.csv`);
break;
case 'csv (ASCII)':
//Customization: skips BOM prefix, as above.
const csv2 = XLSX.utils.sheet_to_csv(worksheet, {FS: ','});
const blob2 = new Blob([csv2], {type: 'text/plain;charset=us-ascii'});
saveAs(blob2, `${baseName}.csv`);
break;
}
},
/**
* Get a flat array of all fields (slot definitions) in TEMPLATE.
* @return {Array<Object>} Array of all objects under `children` in TEMPLATE.
*/
getFields: function() {
return Array.prototype.concat.apply([], this.template.map(section => section.children));
},
/**
* Create a matrix containing the nested headers supplied to Handsontable.
* These headers are HTML strings, with useful selectors for the primary and
* secondary header cells.
* @return {Array<Array>} Nested headers for Handontable grid.
*/
getNestedHeaders: function() {
const rows = [[], []];
for (const parent of this.template) {
rows[0].push({
label: `<h5 class="pt-2 pl-1">${parent.title}</h5>`,
colspan: parent.children.length
});
for (const child of parent.children) {
const required = child.required ? ' required' : '';
const recommended = child.recommended ? ' recommended' : '';
rows[1].push(`<div class="secondary-header-text${required}${recommended}">${child.title}</div>`);
}
}
return rows;
},
/**
* Create an array of cell properties specifying data type for all grid columns.
* AVOID EMPLOYING VALIDATION LOGIC HERE -- HANDSONTABLE'S VALIDATION
* PERFORMANCE IS AWFUL. WE MAKE OUR OWN IN `VALIDATE_GRID`.
* @param {Object} data See TABLE.
* @return {Array<Object>} Cell properties for each grid column.
*/
getColumns: function () {
let ret = [];
for (let field of this.getFields()) {
const col = {};
if (field.required) {
col.required = field.required;
}
if (field.recommended) {
col.recommended = field.recommended;
}
col.source = null;
if (field.flatVocabulary) {
col.source = field.flatVocabulary;
if (field.multivalued === true) {
col.editor = 'text';
col.renderer = 'autocomplete';
}
else {
col.type = 'autocomplete';
// ISSUE: provide trimDropdown if field is using flatVocabulary just for accepting null values
if (!field.sources.includes('null value menu') || field.sources.length > 1)
col.trimDropdown = false;
}
}
// OBSOLETE: metadata_status is now merged with flatVocabulary
//if (field.metadata_status) {
// col.source.push(...field.metadata_status);
//}
if (field.datatype == 'xsd:date') {
col.type = 'date';
// This controls calendar popup date format, default is mm/dd/yyyy
// See https://handsontable.com/docs/8.3.0/Options.html#correctFormat
col.dateFormat = 'YYYY-MM-DD';
// If correctFormat = true, then on import and on data
// entry of cell will convert date values like "2020" to "2020-01-01"
// automatically.
col.correctFormat = false;
}
if (typeof field.getColumn === 'function') {
col = field.getColumn(this, col);
}
ret.push(col);
}
return ret;
},
/**
* Enable multiselection on select rows.
* Indentation workaround: multiples of " " double space before label are
* taken to be indentation levels.
* @param {Object} hot Handonstable grid instance.
* @param {Object} data See TABLE.
* @return {Object} Grid instance with multiselection enabled on columns
* specified as such in the vocabulary.
*/
enableMultiSelection: function () {
const fields = this.getFields();
this.hot.updateSettings({
afterBeginEditing: function(row, col) {
if (fields[col].multivalued === true) {
const value = this.getDataAtCell(row, col);
let selections = value && value.split(';') || [];
selections = selections.map(x => x.trim());
selections2 = selections.filter(function (el) {return el != ''});
// Cleanup of empty values that can occur with leading/trailing or double ";"
if (selections.length != selections2.length)
this.setDataAtCell(row, col, selections2.join('; '), 'thisChange');
const self = this;
let content = '';
if (fields[col].flatVocabulary)
fields[col].flatVocabulary.forEach(function(field, i) {
const field_trim = field.trim();
let selected = selections.includes(field_trim) ? 'selected="selected"' : '';
let indentation = field.search(/\S/) * 8; // pixels
content += `<option value="${field_trim}" ${selected}' style="padding-left:${indentation}px">${field}</option>`;
})
$('#field-description-text').html(`${fields[col].title}<select multiple class="multiselect" rows="15">${content}</select>`);
$('#field-description-modal').modal('show');
$('#field-description-text .multiselect')
.chosen() // must be rendered when html is visible
.change(function () {
let newValCsv = $('#field-description-text .multiselect').val().join('; ')
self.setDataAtCell(row, col, newValCsv, 'thisChange');
});
}
},
});
},
fillColumn: function (colname, value) {
const fieldYCoordinates = this.getFieldYCoordinates();
// ENSURE colname hasn't been tampered with (the autocomplete allows
// other text)
if (colname in fieldYCoordinates) {
let changes = [];
for (let row=0; row < this.hot.countRows(); row++) {
if (!this.hot.isEmptyRow(row)) {
let col = fieldYCoordinates[colname];
if (this.hot.getDataAtCell(row, col) !== value)
changes.push([row, col, value]);
}
}
if (changes.length > 0) {
this.hot.setDataAtCell(changes);
this.hot.render();
}
}
},
/**
* Loads a given javascript file.
*
* @param {String} file_name: File in templates/[current schema]/ to load.
*/
reloadJs: async function(file_name) {