-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.js
More file actions
1487 lines (1332 loc) · 67.3 KB
/
code.js
File metadata and controls
1487 lines (1332 loc) · 67.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
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
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const fileInput = document.getElementById('fileInput');
const loadButton = document.getElementById('loadButton');
const clearButton = document.getElementById('clearButton');
const searchInput = document.getElementById('searchInput');
const columnSelect = document.getElementById('columnSelect');
const searchButton = document.getElementById('searchButton');
const loadedFilesList = document.getElementById('loadedFilesList');
const searchResultsDiv = document.getElementById('searchResults');
const resultsCountDiv = document.getElementById('resultsCount');
const downloadTsvButton = document.getElementById('downloadTsvButton');
const downloadCsvButton = document.getElementById('downloadCsvButton');
const browseModeRadio = document.getElementById('browseMode');
const searchModeRadio = document.getElementById('searchMode');
const browseControlsSection = document.getElementById('browseControlsSection');
const searchControlsSection = document.getElementById('searchControlsSection');
const browseFileSelect = document.getElementById('browseFileSelect');
const browseSearchInput = document.getElementById('browseSearchInput');
const browseSearchButton = document.getElementById('browseSearchButton');
const browseSearchClearButton = document.getElementById('browseSearchClearButton');
const resultsHeader = document.getElementById('resultsHeader');
// --- Flags ---
let columnsToggleListenerAdded = false;
const LOCAL_STORAGE_KEY = 'localTxtFileData_v2';
const GITHUB_REPO = 'AMRverse/AMRrules';
const GITHUB_BRANCH = 'genome_summary_report_dev';
const GITHUB_RULES_PATH = 'rules';
const GITHUB_API_URL = `https://api.github.com/repos/${GITHUB_REPO}/contents/${GITHUB_RULES_PATH}?ref=${GITHUB_BRANCH}`;
const GITHUB_RAW_URL = `https://raw.githubusercontent.com/${GITHUB_REPO}/${GITHUB_BRANCH}/${GITHUB_RULES_PATH}`;
let DEFAULT_FILES = []; // Will be populated dynamically
const FIXED_HEADER_ORDER = [
'ruleID', 'txid', 'organism', 'gene', 'nodeID', 'protein accession',
'HMM accession', 'nucleotide accession', 'ARO accession',
'mutation', 'variation type', 'gene context',
'drug', 'drug class', 'phenotype', 'clinical category', 'breakpoint',
'breakpoint standard', 'breakpoint condition', 'PMID', 'evidence code',
'evidence grade', 'evidence description', 'evidence limitations', 'rule curation note'
];
const ACCESSION_URLS = {
'protein accession': 'https://www.ncbi.nlm.nih.gov/protein/',
'nucleotide accession': 'https://www.ncbi.nlm.nih.gov/nuccore/',
'PMID': 'https://pubmed.ncbi.nlm.nih.gov/',
'ARO accession': 'https://card.mcmaster.ca/aro/',
'evidence code': 'https://evidenceontology.org/term/',
'nodeID': 'https://www.ncbi.nlm.nih.gov/pathogens/genehierarchy/#',
'HMM accession': 'https://www.ncbi.nlm.nih.gov/pathogens/hmm/#'
};
const HEADER_TOOLTIPS = {
'ruleID': 'Unique identifier for the rule',
'txid': 'Taxonomy ID for the organism the rule applies to (NCBI)',
'organism': 'Name of the organism the rule applies to',
'gene': 'Name of the gene the rule applies to',
'nodeID': 'Node ID for the gene the rule applies (NCBI reference gene hierarchy)',
'protein accession': 'Protein sequence accession for the gene the rule applies to (NCBI)',
'HMM accession': 'HMM accession for the gene the rule applies to (NCBI)',
'nucleotide accession': 'Nucleotide sequence accession for the gene the rule applies to (NCBI)',
'ARO accession': 'Gene accession for the gene the rule applies to (CARD ARO)',
'mutation': 'Specific mutation within the gene (HGVS nomenclature)',
'variation type': 'Type of genetic variation',
'gene context': 'Context of this gene within the species (core/acquired)',
'drug': 'Name of the drug the rule applies to (CARD ARO term)',
'drug class': 'Name of the drug class the rule applies to (CARD ARO term)',
'phenotype': 'Phenotype defined by comparison to epidemiological cutoff (ECOFF)',
'clinical category': 'Clinical category (S/I/R) defined by comparison to breakpoints',
'breakpoint': 'Breakpoint value used to define clinical category',
'breakpoint standard': 'Source of the breakpoint (e.g., EUCAST, CLSI)',
'breakpoint condition': 'Specific condition to which this breakpoint applies',
'PMID': 'PubMed ID for article/s supporting this rule',
'evidence code': 'Type of evidence supporting this rule (ECO ontology)',
'evidence grade': 'Evidence grade, summarising expert curators assessment of the available evidence for this rule',
'evidence description': 'Description of the evidence',
'evidence limitations': 'Limitations of the available evidence',
'rule curation note': 'Curators note explaining the genetic mechanism and/or reasoning for the rule'
};
const EVIDENCE_GRADE_TOOLTIPS = {
'high': 'The curators are confident in the categorisation, and believe that the likelihood that the effect will be substantially different from this is low.',
'moderate': 'The curators believe that the categorisation most likely reflects the true effect, and the likelihood that the effect will be substantially different is moderate.',
'low': 'The curators believe that the categorisation might not reflect the true effect, and the likelihood that the effect will be substantially different is high.',
'very low': 'The curators have no confidence that the categorisation reflects the true effect, and the likelihood that the effect will be substantially different is high.'
};
// --- State Variables ---
let currentDataForDisplayAndDownload = [];
let currentHeadersForDisplay = [];
let sortColumnKey = '';
let sortDirection = 'asc';
let originalBrowseData = []; // Track original browse data before filtering
let currentBrowseSearchTerm = ''; // Track current browse search term for URL updates
let DRUG_ARO_MAP = {}; // Maps drug names to ARO IDs
let CLASS_ARO_MAP = {}; // Maps drug class names to ARO IDs
// --- Initialization ---
(async () => {
await fetchAndParseCardMapping(); // Load CARD mapping first
initializeApplication();
})();
// --- Helper Functions for GitHub File Fetching ---
// Mapping for common typos and variations
const TYPO_CORRECTIONS = {
'penicillin beta-lactam antibiotc': 'penicillin beta-lactam',
'sulfonamides': 'sulfonamide antibiotic',
'aminoglycosides': 'aminoglycoside antibiotic',
'kanamycin': 'kanamycin a'
};
// Normalize strings for case-insensitive and hyphen-space matching
function normalizeKey(str) {
let normalized = String(str)
.toLowerCase()
.replace(/-/g, ' ') // Replace hyphens with spaces
.replace(/\s+/g, ' ') // Collapse multiple spaces
.trim();
// Apply typo corrections
if (TYPO_CORRECTIONS[normalized]) {
normalized = TYPO_CORRECTIONS[normalized];
}
return normalized;
}
async function fetchAndParseCardMapping() {
try {
// Try loading from GitHub first
const response = await fetch('https://raw.githubusercontent.com/amrverse/AMRrulebrowser/main/card_drug_names.tsv');
if (!response.ok) throw new Error(`Failed to fetch CARD mapping: ${response.statusText}`);
const content = await response.text();
const lines = content.split('\n');
let drugCount = 0;
let classCount = 0;
lines.forEach((line, index) => {
if (line.trim() === '') return; // Skip empty lines
if (index === 0) return; // Skip header line
const parts = line.split('\t');
if (parts.length < 3) return;
const aroId = parts[0].trim();
if (aroId === '-' || !aroId) return; // Skip entries without ARO ID
const aroNumber = aroId.replace('ARO:', '');
const drugName = parts[1].trim();
const className = parts[2].trim();
// If it's a drug entry
if (drugName && drugName !== '-') {
const normalizedDrug = normalizeKey(drugName);
DRUG_ARO_MAP[normalizedDrug] = aroNumber;
drugCount++;
}
// If it's a class entry
if (className && className !== '-') {
const normalizedClass = normalizeKey(className);
CLASS_ARO_MAP[normalizedClass] = aroNumber;
classCount++;
}
});
console.log(`Loaded ${drugCount} drug entries and ${classCount} class entries from CARD mapping`);
} catch (error) {
console.error("Error loading CARD drug/class mapping from GitHub:", error);
// Continue without the mappings - links won't be created for drugs and classes
}
}
async function fetchDefaultFilesFromGitHub() {
try {
const response = await fetch(GITHUB_API_URL);
if (!response.ok) throw new Error(`GitHub API error: ${response.statusText}`);
const files = await response.json();
// Filter for .txt files and build URLs
DEFAULT_FILES = files
.filter(file => file.name.endsWith('.txt'))
.map(file => ({
name: file.name,
url: `${GITHUB_RAW_URL}/${file.name}`
}));
console.log(`Found ${DEFAULT_FILES.length} txt files from GitHub repository`);
return DEFAULT_FILES;
} catch (error) {
console.error("Error fetching file list from GitHub:", error);
alert("Could not fetch file list from GitHub repository. Check console for details.");
return [];
}
}
// Helper function to format file names (remove .txt and replace _ with space)
function formatFileName(fileName) {
return fileName.replace(/\.txt$/, '').replace(/_/g, ' ');
}
// --- Event Listeners ---
loadButton.addEventListener('click', () => {
const files = fileInput.files;
if (files.length === 0) {
alert('Please select at least one file.');
return;
}
handleFileUploads(files);
});
clearButton.addEventListener('click', () => {
if (confirm('Are you sure you want to clear all loaded data (including defaults)? This will remove them from your browser\'s local storage for this page.')) {
localStorage.removeItem(LOCAL_STORAGE_KEY);
resetUIAfterClear();
alert('All data cleared. Default files will need to be re-fetched if you refresh or can be re-loaded manually if needed.');
}
});
browseModeRadio.addEventListener('change', handleModeChange);
searchModeRadio.addEventListener('change', handleModeChange);
browseFileSelect.addEventListener('change', triggerBrowse);
browseSearchButton.addEventListener('click', performBrowseSearch);
browseSearchInput.addEventListener('keyup', (event) => {
if (event.key === 'Enter') performBrowseSearch();
});
browseSearchClearButton.addEventListener('click', clearBrowseSearch);
searchButton.addEventListener('click', performSearch);
searchInput.addEventListener('keyup', (event) => {
if (event.key === 'Enter') performSearch();
});
downloadTsvButton.addEventListener('click', () => downloadCurrentData('tsv'));
downloadCsvButton.addEventListener('click', () => downloadCurrentData('csv'));
// --- Core Functions ---
async function initializeApplication() {
let storedData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {};
// First, fetch the list of available files from GitHub
resultsCountDiv.textContent = `Fetching file list from GitHub repository...`;
const defaultFilesFromGitHub = await fetchDefaultFilesFromGitHub();
if (defaultFilesFromGitHub.length === 0) {
resultsCountDiv.textContent = "Error: Could not fetch files from GitHub.";
updateUIAfterDataLoad(storedData);
handleModeChange();
return;
}
// Check which files are already stored
const defaultFileNamesInStorage = defaultFilesFromGitHub.filter(df => storedData[df.name]);
const defaultFilesToFetch = defaultFilesFromGitHub.filter(df => !storedData[df.name]);
if (defaultFilesToFetch.length > 0) {
resultsCountDiv.textContent = `Loading ${defaultFilesToFetch.length} default file(s) from GitHub...`;
try {
await Promise.all(defaultFilesToFetch.map(async (fileObj) => {
const response = await fetch(fileObj.url);
if (!response.ok) throw new Error(`Failed to fetch ${fileObj.name}: ${response.statusText}`);
const content = await response.text();
const parsed = parseTSV(content);
storedData[fileObj.name] = {
name: fileObj.name,
content: content, // Store raw content
headerLineIndex: parsed.headerLineIndex,
headers: parsed.headers,
rows: parsed.rows,
type: 'text/plain',
lastModified: new Date().toLocaleDateString() // Placeholder
};
}));
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(storedData));
resultsCountDiv.textContent = `Loaded ${defaultFilesToFetch.length} file(s) from GitHub. ${defaultFileNamesInStorage.length > 0 ? (defaultFileNamesInStorage.length + ' previously loaded files also available.') : ''}`;
} catch (error) {
console.error("Error loading default files from GitHub:", error);
alert("Could not load some files from GitHub. Check console for details.");
resultsCountDiv.textContent = "Error loading files from GitHub.";
}
} else if (Object.keys(storedData).length > 0) {
resultsCountDiv.textContent = "Loaded data from previous session.";
}
updateUIAfterDataLoad(storedData);
// After UI is ready, handle any deep-link in the URL (path or query)
try {
handleInitialQuery(storedData);
} catch (e) {
console.warn('Error processing initial URL query/path', e);
}
handleModeChange(); // Set initial mode and display
}
function resetUIAfterClear() {
updateLoadedFilesList([]);
updateColumnSelector([]);
updateBrowseFileDropdown([]);
searchResultsDiv.innerHTML = '';
resultsCountDiv.textContent = 'No data loaded.';
currentDataForDisplayAndDownload = [];
currentHeadersForDisplay = [];
toggleDownloadButtons(false);
// Consider if you want to immediately try to reload default files here
// or just inform the user they will load on next refresh/visit.
// For now, it's cleared. A refresh will trigger initializeApplication again.
}
function updateUIAfterDataLoad(dataObject) {
const fileNames = Object.keys(dataObject);
const allHeaders = new Set();
Object.values(dataObject).forEach(fileData => {
if (fileData.headers) {
fileData.headers.forEach(h => allHeaders.add(h));
}
});
updateLoadedFilesList(fileNames.sort());
updateColumnSelector(Array.from(allHeaders).sort());
updateBrowseFileDropdown(fileNames.sort());
}
// Find a file key in storedData matching an organism-like query
function findFileKeyByOrganismParam(param, storedData) {
if (!param) return null;
const cleaned = String(param).replace(/\.txt$/i, '').replace(/_/g, ' ');
const normParam = normalizeKey(cleaned);
for (const key of Object.keys(storedData)) {
const base = key.replace(/\.txt$/i, '');
const formatted = formatFileName(key);
if (normalizeKey(base) === normParam) return key;
if (normalizeKey(formatted) === normParam) return key;
// also allow partial matches
if (normalizeKey(base).includes(normParam) || normalizeKey(formatted).includes(normParam)) return key;
}
// If no filename matches, search inside file rows for an organism column matching the param
for (const key of Object.keys(storedData)) {
const fileData = storedData[key];
if (!fileData || !Array.isArray(fileData.rows)) continue;
for (const r of fileData.rows) {
let v = r['organism'] || '';
if (typeof v === 'string') {
v = v.trim().replace(/^"|"$/g, '');
if (v.startsWith('s__')) v = v.substring(3);
if (normalizeKey(v) === normParam) return key;
}
}
}
return null;
}
// Process URL query parameters and pathname to pre-select organism or run a search
function handleInitialQuery(storedData) {
if (typeof window === 'undefined' || !window.location) return;
const path = window.location.pathname || '';
const pathSegments = path.split('/').filter(s => s && s.trim() !== '');
let pathCandidate = '';
if (pathSegments.length > 0) {
pathCandidate = decodeURIComponent(pathSegments[pathSegments.length - 1]);
if (/\.html?$/.test(pathCandidate) || pathCandidate.toLowerCase().endsWith('examples')) {
pathCandidate = '';
}
}
const raw = window.location.search ? window.location.search.slice(1) : '';
// Prefer path-based organism deep-link if present
if (pathCandidate) {
const fileKey = findFileKeyByOrganismParam(pathCandidate, storedData);
if (fileKey) {
browseModeRadio.checked = true;
handleModeChange();
// Try to find an organism-specific option whose normalized organism matches the pathCandidate
let matchedOptionValue = null;
const opts = Array.from(browseFileSelect.querySelectorAll('option'));
const targetNorm = normalizeKey(pathCandidate);
for (const o of opts) {
if (!o.value) continue;
if (!o.value.startsWith(fileKey + '::')) continue;
const parts = o.value.split('::');
const enc = parts.slice(1).join('::');
try {
const orgRaw = decodeURIComponent(enc);
if (normalizeKey(orgRaw) === targetNorm) {
matchedOptionValue = o.value;
break;
}
} catch (e) {
// ignore decode errors
}
}
if (matchedOptionValue) browseFileSelect.value = matchedOptionValue;
else browseFileSelect.value = fileKey;
triggerBrowse();
return;
}
}
// If no '=' present treat as organism shorthand (e.g. ?escherichia_coli)
if (raw && raw.indexOf('=') === -1) {
const param = decodeURIComponent(raw);
const fileKey = findFileKeyByOrganismParam(param, storedData);
if (fileKey) {
browseModeRadio.checked = true;
handleModeChange();
browseFileSelect.value = fileKey;
triggerBrowse();
}
return;
}
const params = new URLSearchParams(raw);
if (params.has('organism') || params.has('org') || params.has('o')) {
const val = params.get('organism') || params.get('org') || params.get('o');
if (val) {
const fileKey = findFileKeyByOrganismParam(val, storedData);
if (fileKey) {
browseModeRadio.checked = true;
handleModeChange();
// Try to select an organism-specific option if available
const rawParam = String(val);
const targetNorm = normalizeKey(rawParam.replace(/_/g, ' '));
let matchedOptionValue = null;
const opts = Array.from(browseFileSelect.querySelectorAll('option'));
for (const o of opts) {
if (!o.value) continue;
if (!o.value.startsWith(fileKey + '::')) continue;
const parts = o.value.split('::');
const enc = parts.slice(1).join('::');
try {
const orgRaw = decodeURIComponent(enc);
if (normalizeKey(orgRaw) === targetNorm) {
matchedOptionValue = o.value;
break;
}
} catch (e) {
// ignore decode errors
}
}
if (matchedOptionValue) browseFileSelect.value = matchedOptionValue;
else browseFileSelect.value = fileKey;
triggerBrowse();
}
}
}
if (params.has('drug') || params.has('gene') || params.has('ruleID') || params.has('rule') || params.has('search') || params.has('q')) {
const searchVal = params.get('drug') || params.get('gene') || params.get('ruleID') || params.get('rule') || params.get('search') || params.get('q');
if (searchVal) {
// Always stay in browse mode - apply search to browse results instead
browseModeRadio.checked = true;
handleModeChange();
// Set organism if provided, otherwise use 'all'
if (params.has('organism') || params.has('org') || params.has('o')) {
const orgVal = params.get('organism') || params.get('org') || params.get('o');
const fileKey = findFileKeyByOrganismParam(orgVal, storedData);
if (fileKey) {
const rawParam = String(orgVal);
const targetNorm = normalizeKey(rawParam.replace(/_/g, ' '));
let matchedOptionValue = null;
const opts = Array.from(browseFileSelect.querySelectorAll('option'));
for (const o of opts) {
if (!o.value) continue;
if (!o.value.startsWith(fileKey + '::')) continue;
const parts = o.value.split('::');
const enc = parts.slice(1).join('::');
try {
const orgRaw = decodeURIComponent(enc);
if (normalizeKey(orgRaw) === targetNorm) {
matchedOptionValue = o.value;
break;
}
} catch (e) {}
}
if (matchedOptionValue) browseFileSelect.value = matchedOptionValue;
else browseFileSelect.value = fileKey;
}
} else {
browseFileSelect.value = 'all';
}
// Trigger browse to load data, then apply search
triggerBrowse();
browseSearchInput.value = searchVal;
currentBrowseSearchTerm = searchVal.toLowerCase();
performBrowseSearch();
}
}
}
function handleFileUploads(files) {
let existingData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {};
let filesProcessed = 0;
const totalFiles = files.length;
Array.from(files).forEach(file => {
const reader = new FileReader();
reader.onload = (event) => {
const content = event.target.result;
const parsed = parseTSV(content);
existingData[file.name] = {
name: file.name,
content: content,
headerLineIndex: parsed.headerLineIndex,
headers: parsed.headers,
rows: parsed.rows,
type: file.type,
lastModified: file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'N/A'
};
filesProcessed++;
if (filesProcessed === totalFiles) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(existingData));
updateUIAfterDataLoad(existingData);
alert(`${totalFiles} file(s) processed and stored.`);
fileInput.value = ''; // Reset file input
if (browseModeRadio.checked) {
triggerBrowse(); // Refresh browse view if in browse mode
}
}
};
reader.onerror = () => {
alert(`Error reading file: ${file.name}`);
filesProcessed++;
if (filesProcessed === totalFiles) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(existingData)); // Save what was processed
updateUIAfterDataLoad(existingData);
}
};
reader.readAsText(file);
});
}
function handleModeChange() {
sortColumnKey = ''; // Reset sort when mode changes
sortDirection = 'asc';
if (browseModeRadio.checked) {
browseControlsSection.style.display = 'block';
searchControlsSection.style.display = 'none';
resultsHeader.textContent = 'Browse results:';
searchInput.value = ''; // Clear search input
triggerBrowse();
} else { // Search mode
browseControlsSection.style.display = 'none';
searchControlsSection.style.display = 'block';
resultsHeader.textContent = 'Search results:';
searchResultsDiv.innerHTML = '<p>Enter search criteria above and click Search.</p>';
resultsCountDiv.textContent = '';
currentDataForDisplayAndDownload = [];
toggleDownloadButtons(false);
}
}
function triggerBrowse() {
const selectedFileName = browseFileSelect.value;
const storedData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {};
let dataToBrowse = [];
let distinctHeaders = new Set();
if (Object.keys(storedData).length === 0) {
searchResultsDiv.innerHTML = '<p>No organisms loaded to browse.</p>';
resultsCountDiv.textContent = '';
currentDataForDisplayAndDownload = [];
currentHeadersForDisplay = [];
toggleDownloadButtons(false);
renderTable([], []); // Clear table
return;
}
if (selectedFileName === 'all') {
resultsHeader.textContent = 'Browsing: all organisms';
Object.values(storedData).forEach(fileData => {
if (fileData && fileData.rows) dataToBrowse.push(...fileData.rows);
if (fileData && fileData.headers) fileData.headers.forEach(h => distinctHeaders.add(h));
});
} else if (selectedFileName.includes('::')) {
// option encoded as fileName::encodedOrganism
const parts = selectedFileName.split('::');
const fileKey = parts[0];
const org = decodeURIComponent(parts.slice(1).join('::'));
if (storedData[fileKey] && storedData[fileKey].rows) {
resultsHeader.textContent = `Browsing: ${org}`;
// filter rows for organism, removing s__ prefix and trimming/quotes
dataToBrowse = storedData[fileKey].rows.filter(r => {
let v = r['organism'] || '';
if (typeof v !== 'string') v = String(v);
v = v.trim().replace(/^"|"$/g, '');
if (v.startsWith('s__')) v = v.substring(3);
return normalizeKey(v) === normalizeKey(org);
});
if (storedData[fileKey].headers) storedData[fileKey].headers.forEach(h => distinctHeaders.add(h));
}
} else if (storedData[selectedFileName] && storedData[selectedFileName].rows) {
resultsHeader.textContent = `Browsing: ${formatFileName(selectedFileName)}`;
dataToBrowse = storedData[selectedFileName].rows;
if (storedData[selectedFileName].headers) {
storedData[selectedFileName].headers.forEach(h => distinctHeaders.add(h));
}
}
currentHeadersForDisplay = FIXED_HEADER_ORDER.filter(h => distinctHeaders.has(h));
if (currentHeadersForDisplay.length === 0 && distinctHeaders.size > 0) {
currentHeadersForDisplay = Array.from(distinctHeaders).sort();
}
originalBrowseData = dataToBrowse;
currentDataForDisplayAndDownload = dataToBrowse;
browseSearchInput.value = ''; // Clear browse search input when switching organisms
currentBrowseSearchTerm = ''; // Clear search term when switching organisms
sortColumnKey = ''; // Reset sort when browsing new data
sortDirection = 'asc';
sortAndDisplayData();
resultsCountDiv.textContent = `Displaying ${dataToBrowse.length} row(s).`;
toggleDownloadButtons(dataToBrowse.length > 0);
// Update URL to reflect current browse selection
try {
updateUrlForBrowseSelection(selectedFileName);
} catch (e) {
console.warn('Could not update URL for browse selection', e);
}
}
function updateUrlForBrowseSelection(selectedValue, searchTerm) {
if (typeof window === 'undefined' || !window.history || !window.location) return;
// Build base path (directory hosting the app). Keep trailing slash.
let base = window.location.pathname || '/';
if (base.endsWith('index.html')) base = base.slice(0, -'index.html'.length);
if (!base.endsWith('/')) base = base.replace(/[^\/]*$/, '');
// Use provided searchTerm or current state variable
const activeTerm = searchTerm !== undefined ? searchTerm : currentBrowseSearchTerm;
if (!selectedValue || selectedValue === 'all') {
// If search term exists, include it
if (activeTerm) {
const newUrl = base + '?search=' + encodeURIComponent(activeTerm);
history.replaceState(null, '', newUrl);
} else {
// Clear organism-specific part
const newUrl = base;
history.replaceState(null, '', newUrl);
}
return;
}
if (selectedValue.includes('::')) {
const parts = selectedValue.split('::');
const fileKey = parts[0];
const orgEncoded = parts.slice(1).join('::');
let orgRaw = orgEncoded;
try { orgRaw = decodeURIComponent(orgEncoded); } catch (e) {}
// Use query param ?organism= so multi-organism selections are linkable and consistent
const orgForParam = orgRaw.replace(/\s+/g, '_');
// Include search term if present
let newUrl = base + '?organism=' + encodeURIComponent(orgForParam);
if (activeTerm) {
newUrl += '&search=' + encodeURIComponent(activeTerm);
}
history.replaceState(null, '', newUrl);
return;
}
// file-level selection: set an organism query param so it's linkable
const fileBase = selectedValue.replace(/\.txt$/i, '');
const fileForParam = fileBase.replace(/\s+/g, '_');
let newUrl = base + '?organism=' + encodeURIComponent(fileForParam);
if (activeTerm) {
newUrl += '&search=' + encodeURIComponent(activeTerm);
}
history.replaceState(null, '', newUrl);
}
function performBrowseSearch() {
const searchTerm = browseSearchInput.value.trim().toLowerCase();
currentBrowseSearchTerm = searchTerm; // Track for URL updates
if (!searchTerm) {
alert('Please enter a search term.');
return;
}
let matchedRows = [];
originalBrowseData.forEach(row => {
if (Object.values(row).some(val => String(val).toLowerCase().includes(searchTerm))) {
matchedRows.push(row);
}
});
currentDataForDisplayAndDownload = matchedRows;
sortColumnKey = ''; // Reset sort for new search
sortDirection = 'asc';
sortAndDisplayData();
resultsCountDiv.textContent = `Found ${matchedRows.length} match(es) in browse results.`;
toggleDownloadButtons(matchedRows.length > 0);
if (matchedRows.length === 0) {
searchResultsDiv.innerHTML = '<p>No results found.</p>';
}
// Update URL to reflect current browse state (organism + search term)
try {
updateUrlForBrowseSelection(browseFileSelect.value, searchTerm);
} catch (e) {
console.warn('Could not update URL for browse search', e);
}
}
function clearBrowseSearch() {
browseSearchInput.value = '';
currentBrowseSearchTerm = ''; // Clear search term
currentDataForDisplayAndDownload = originalBrowseData;
sortColumnKey = '';
sortDirection = 'asc';
sortAndDisplayData();
resultsCountDiv.textContent = `Displaying ${originalBrowseData.length} row(s).`;
toggleDownloadButtons(originalBrowseData.length > 0);
// Update URL to remove search term
try {
updateUrlForBrowseSelection(browseFileSelect.value);
} catch (e) {
console.warn('Could not update URL for browse clear', e);
}
}
function performSearch() {
const searchTerm = searchInput.value.trim().toLowerCase();
const selectedSearchCol = columnSelect.value; // Renamed to avoid conflict
if (!searchTerm) {
alert('Please enter a search term.');
searchResultsDiv.innerHTML = '<p>Please enter a search term.</p>';
resultsCountDiv.textContent = '';
currentDataForDisplayAndDownload = [];
currentHeadersForDisplay = [];
toggleDownloadButtons(false);
renderTable([], []);
return;
}
const storedData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (!storedData || Object.keys(storedData).length === 0) {
alert('No files loaded to search.');
return;
}
let matchedRows = [];
let distinctHeadersInMatches = new Set();
Object.values(storedData).forEach(fileData => {
const fileHeaders = fileData.headers || [];
const fileRows = fileData.rows || [];
fileRows.forEach(row => {
let rowMatched = false;
if (selectedSearchCol === 'all') {
if (Object.values(row).some(val => String(val).toLowerCase().includes(searchTerm))) {
rowMatched = true;
}
} else {
if (row.hasOwnProperty(selectedSearchCol) && String(row[selectedSearchCol]).toLowerCase().includes(searchTerm)) {
rowMatched = true;
}
}
if (rowMatched) {
matchedRows.push(row);
fileHeaders.forEach(h => distinctHeadersInMatches.add(h));
}
});
});
currentHeadersForDisplay = FIXED_HEADER_ORDER.filter(h => distinctHeadersInMatches.has(h));
if (currentHeadersForDisplay.length === 0 && distinctHeadersInMatches.size > 0) {
currentHeadersForDisplay = Array.from(distinctHeadersInMatches).sort();
}
currentDataForDisplayAndDownload = matchedRows;
sortColumnKey = ''; // Reset sort for new search
sortDirection = 'asc';
sortAndDisplayData();
resultsCountDiv.textContent = `Found ${matchedRows.length} match(es).`;
// update URL to reflect search
try {
updateUrlForSearch(searchTerm, selectedSearchCol);
} catch (e) {
console.warn('Could not update URL for search', e);
}
toggleDownloadButtons(matchedRows.length > 0);
if (matchedRows.length === 0) {
searchResultsDiv.innerHTML = '<p>No results found.</p>';
}
}
function updateUrlForSearch(term, column) {
if (typeof window === 'undefined' || !window.history || !window.location) return;
let base = window.location.pathname || '/';
if (base.endsWith('index.html')) base = base.slice(0, -'index.html'.length);
if (!base.endsWith('/')) base = base.replace(/[^\/]*$/, '');
const encoded = encodeURIComponent(term);
let q = '';
if (column && column !== 'all') {
if (column === 'ruleID') q = `?rule=${encoded}`;
else q = `?${encodeURIComponent(column)}=${encoded}`;
} else {
q = `?q=${encoded}`;
}
history.replaceState(null, '', base + q);
}
function updateLoadedFilesList(fileNames) {
loadedFilesList.innerHTML = '';
if (fileNames.length === 0) {
loadedFilesList.innerHTML = '<li>No files loaded.</li>';
} else {
fileNames.forEach(name => {
const li = document.createElement('li');
li.textContent = name;
loadedFilesList.appendChild(li);
});
}
}
function updateBrowseFileDropdown(fileNames) {
browseFileSelect.innerHTML = '<option value="all">All organisms</option>';
const storedData = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || {};
fileNames.forEach(name => {
const fileData = storedData[name];
// If file has an 'organism' header and multiple distinct organisms, show organism-level options
if (fileData && fileData.headers && fileData.headers.includes('organism') && Array.isArray(fileData.rows)) {
const orgSet = new Set();
fileData.rows.forEach(r => {
let v = r['organism'] || '';
if (typeof v === 'string') {
v = v.trim().replace(/^"|"$/g, '');
if (v.startsWith('s__')) v = v.substring(3);
if (v !== '') orgSet.add(v);
}
});
if (orgSet.size > 1) {
// Create an option per organism (value encodes file and organism)
Array.from(orgSet).sort().forEach(org => {
const option = document.createElement('option');
option.value = `${name}::${encodeURIComponent(org)}`;
option.textContent = org.replace(/_/g, ' ');
browseFileSelect.appendChild(option);
});
return; // skip adding file-level option
}
}
// Default: add file-level option
const option = document.createElement('option');
option.value = name;
option.textContent = formatFileName(name);
browseFileSelect.appendChild(option);
});
}
function updateColumnSelector(headers) {
columnSelect.innerHTML = '<option value="all">All Columns</option>';
FIXED_HEADER_ORDER.forEach(fixedHeader => {
if (headers.includes(fixedHeader)) {
const option = document.createElement('option');
option.value = fixedHeader;
option.textContent = fixedHeader;
columnSelect.appendChild(option);
}
});
headers.forEach(header => {
if (!FIXED_HEADER_ORDER.includes(header) && header.trim() !== '') {
const option = document.createElement('option');
option.value = header;
option.textContent = header;
columnSelect.appendChild(option);
}
});
}
function parseTSV(content) {
const lines = content.split('\n');
let headerLineIndex = -1;
let headers = [];
for (let i = 0; i < lines.length; i++) {
if (lines[i].trim() !== '') {
headerLineIndex = i;
headers = lines[i].split('\t').map(h => h.trim());
break;
}
}
if (headerLineIndex === -1) return { headers: [], rows: [], headerLineIndex: -1 };
const dataRows = lines.slice(headerLineIndex + 1);
const rows = dataRows.map(line => {
const values = line.split('\t');
const rowObject = {};
headers.forEach((header, index) => {
// Comprehensive trimming to remove all leading/trailing whitespace
let value = values[index] || '';
value = value.trim().replace(/\s+$/g, '').replace(/^\s+/g, '');
rowObject[header] = value;
});
return rowObject;
}).filter(row => {
// Filter out specific ruleIDs (handle potential quote characters)
const ruleID = String(row.ruleID || '').trim().replace(/"/g, '');
const blockedRuleIDs = [];
if (blockedRuleIDs.includes(ruleID)) {
return false;
}
return Object.values(row).some(val => val && String(val).trim() !== '');
});
return { headers, rows, headerLineIndex };
}
function escapeHtml(unsafe) {
if (typeof unsafe !== 'string') {
unsafe = String(unsafe); // Ensure it's a string
}
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Create a single shared custom tooltip element for fast, responsive header tooltips
const customTooltip = document.createElement('div');
customTooltip.className = 'custom-tooltip';
document.body.appendChild(customTooltip);
let tooltipShowTimer = null;
let tooltipHideTimer = null;
const TOOLTIP_SHOW_DELAY = 120; // ms
const TOOLTIP_HIDE_DELAY = 50; // ms to allow quick re-entry without flicker
// Mapping of column headers to spec documentation URLs for the info icon
const INFO_LINKS = {
'variation type': 'https://amrrules.readthedocs.io/en/genome_summary_report_dev/specification.html#variation-type',
'evidence code': 'https://amrrules.readthedocs.io/en/genome_summary_report_dev/specification.html#evidence-codes',
'mutation': 'https://amrrules.readthedocs.io/en/genome_summary_report_dev/specification.html#syntax-for-mutations',
'evidence grade': 'https://amrrules.readthedocs.io/en/genome_summary_report_dev/specification.html#evidence-grade',
'evidence limitations': 'https://amrrules.readthedocs.io/en/genome_summary_report_dev/specification.html#evidence-limitations'
};
function generateLink(headerKey, value, rowData) {
let sValue = String(value).trim(); // Trim immediately when converting to string
// Remove "s__" prefix from organism column
if (headerKey === 'organism' && sValue.startsWith('s__')) {
sValue = sValue.substring(3);
}
// Remove surrounding double quotes from rule curation note
if (headerKey === 'rule curation note') {
sValue = sValue.replace(/^"|"$/g, '');
}
if (!sValue || sValue === '-' || sValue.trim() === '') {
return sValue; // Return original non-values as is
}
// Handle organism column: create link using txid from row data
if (headerKey === 'organism' && rowData && rowData.txid) {
const txidValue = String(rowData.txid).trim();
if (txidValue && txidValue !== '-') {
const TXID_URL = 'https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?id=';
return `<a href="${TXID_URL}${encodeURIComponent(txidValue)}" target="_blank">${escapeHtml(sValue)}</a>`;
}
}
// Skip linking for txid column
if (headerKey === 'txid') {
return escapeHtml(sValue);
}
// Handle drug and drug class fields with CARD mappings (using normalized lookups)
if (headerKey === 'drug') {
const normalizedDrug = normalizeKey(sValue);
if (DRUG_ARO_MAP[normalizedDrug]) {
const aroNumber = DRUG_ARO_MAP[normalizedDrug];
return `<a href="https://card.mcmaster.ca/aro/${aroNumber}" target="_blank">${escapeHtml(sValue)}</a>`;
}
}
if (headerKey === 'drug class') {
const normalizedClass = normalizeKey(sValue);
if (CLASS_ARO_MAP[normalizedClass]) {
const aroNumber = CLASS_ARO_MAP[normalizedClass];
return `<a href="https://card.mcmaster.ca/aro/${aroNumber}" target="_blank">${escapeHtml(sValue)}</a>`;