ref-solver 0.3.0

Solve reference genome identification from BAM/SAM headers
Documentation
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
/**
 * @fileoverview Main Application Entry Point
 * Coordinates all managers and sets up global event handlers
 * @module main
 */

import { ConfigurationManager } from './managers/ConfigurationManager.js';
import { TabManager } from './managers/TabManager.js';
import { ResultsManager, HelpSystem } from './managers/ResultsManager.js';
import { SplitViewManager } from './managers/SplitViewManager.js';
import {
    escapeHtml,
    examples,
    validateFileSize,
    formatFileSize,
    clamp,
    MAX_TEXT_FILE_SIZE
} from './utils/helpers.js';
import { extractBamHeader, isBamFile } from './utils/headerExtractor.js';

/**
 * @typedef {'text'|'assembly'|'vcf'|'binary'} FileFormatType
 * Supported file format types for upload
 */

/**
 * @typedef {'md5-jaccard'|'name-length'|'md5-coverage'|'order-score'} WeightType
 * Weight type identifiers used in UI
 */

// Create global manager instances
/** @type {ConfigurationManager} */
const configManager = new ConfigurationManager();

/** @type {TabManager} */
const tabManager = new TabManager();

/** @type {ResultsManager} */
const resultsManager = new ResultsManager();

/** @type {HelpSystem} */
const helpSystem = new HelpSystem();

/** @type {SplitViewManager} */
const splitViewManager = new SplitViewManager();

// Expose managers to window for inline event handlers
window.configManager = configManager;
window.tabManager = tabManager;
window.resultsManager = resultsManager;
window.helpSystem = helpSystem;
window.splitViewManager = splitViewManager;

// Event handler functions (exposed globally for inline handlers)

/**
 * Switch to a different input format tab
 * @param {string} tabId - ID of the tab to switch to
 * @returns {void}
 */
function showTab(tabId) {
    tabManager.switchTab(tabId);
}

/**
 * Toggle the help panel visibility
 * @returns {void}
 */
function toggleHelp() {
    helpSystem.toggle();
}

/**
 * Show a specific help tab
 * @param {string} tabId - ID of the help tab to show
 * @returns {void}
 */
function showHelpTab(tabId) {
    helpSystem.showTab(tabId);
}

/**
 * Update the score threshold value
 * @param {string|number} value - New threshold value (0-100)
 * @returns {void}
 */
function updateThreshold(value) {
    const parsed = parseInt(value, 10);
    const validated = isNaN(parsed) ? configManager.scoreThreshold : clamp(parsed, 0, 100);
    configManager.scoreThreshold = validated;
    document.getElementById('threshold-value').textContent = validated + '%';
    configManager.saveConfig();
}

/**
 * Update a scoring weight value
 * @param {WeightType} type - Weight type identifier
 * @param {string|number} value - New weight value (0-100)
 * @returns {void}
 */
function updateWeight(type, value) {
    const mapping = {
        'md5-jaccard': 'md5Jaccard',
        'name-length': 'nameLength',
        'md5-coverage': 'md5Coverage',
        'order-score': 'orderScore'
    };

    const key = mapping[type];
    if (!key) return;

    const parsed = parseInt(value, 10);
    const validated = isNaN(parsed) ? configManager.scoringWeights[key] : clamp(parsed, 0, 100);
    configManager.scoringWeights[key] = validated;
    document.getElementById(type + '-value').textContent = validated + '%';
    configManager.saveConfig();
}

/**
 * Toggle the advanced options panel visibility
 * @returns {void}
 */
function toggleAdvanced() {
    const options = document.getElementById('advanced-options');
    const arrow = document.getElementById('advanced-arrow');

    if (options.classList.contains('expanded')) {
        options.classList.remove('expanded');
        arrow.textContent = 'â–¶';
    } else {
        options.classList.add('expanded');
        arrow.textContent = 'â–¼';
    }
}

/**
 * Toggle expansion of a result row details
 * @param {number} index - Index of the result to toggle
 * @returns {void}
 */
function toggleResultDetails(index) {
    resultsManager.toggleExpansion(index);
}

/**
 * Toggle the input section collapse state
 * @returns {void}
 */
function toggleInputSection() {
    const inputSection = document.getElementById('input-section');
    const arrow = document.getElementById('input-collapse-arrow');

    if (inputSection.classList.contains('collapsed')) {
        inputSection.classList.remove('collapsed');
        arrow.textContent = 'â–¼';
    } else {
        inputSection.classList.add('collapsed');
        arrow.textContent = 'â–²';
    }
}

/**
 * Collapse the input section after running identify
 * @returns {void}
 */
function collapseInputAfterIdentify() {
    const inputSection = document.getElementById('input-section');
    const arrow = document.getElementById('input-collapse-arrow');

    inputSection.classList.add('collapsed');
    arrow.textContent = 'â–²';
}

/**
 * Show an error message to the user
 * @param {string} message - Error message to display
 * @returns {void}
 */
function showUploadError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error';
    errorDiv.style.cssText = 'position: fixed; top: 20px; right: 20px; background: var(--error); color: white; padding: 1rem; border-radius: 6px; z-index: 10000; max-width: 400px;';
    errorDiv.textContent = message;
    document.body.appendChild(errorDiv);

    setTimeout(() => {
        if (errorDiv.parentNode) {
            errorDiv.parentNode.removeChild(errorDiv);
        }
    }, 5000);
}

/**
 * Show a status message during header extraction
 * @param {string} message
 */
function showExtractionStatus(message) {
    let statusDiv = document.getElementById('extraction-status');
    if (!statusDiv) {
        statusDiv = document.createElement('div');
        statusDiv.id = 'extraction-status';
        statusDiv.className = 'extraction-status';
        const preview = document.getElementById('binary-preview');
        if (preview && preview.parentNode) {
            preview.parentNode.insertBefore(statusDiv, preview);
        }
    }
    statusDiv.textContent = message;
    statusDiv.style.display = 'block';
}

/**
 * Hide the extraction status message
 */
function hideExtractionStatus() {
    const statusDiv = document.getElementById('extraction-status');
    if (statusDiv) {
        statusDiv.style.display = 'none';
    }
}

/**
 * Handle file upload and preview
 * @param {HTMLInputElement} input - File input element
 * @param {FileFormatType} format - Expected file format
 * @returns {void}
 */
async function handleFileUpload(input, format) {
    const file = input.files[0];
    if (!file) return;

    // For BAM files, try to extract just the header client-side
    if (format === 'binary' && isBamFile(file.name)) {
        try {
            showExtractionStatus('Extracting header from BAM file...');
            const result = await extractBamHeader(file);
            if (result) {
                // Store as a synthetic text file for form submission
                const headerBlob = new Blob([result.header], { type: 'text/plain' });
                const headerFile = new File(
                    [headerBlob], file.name + '.header.sam', { type: 'text/plain' }
                );
                tabManager.setCurrentFile(headerFile, 'text');

                // Show the extracted header in the binary preview area
                document.getElementById('binary-preview').style.display = 'block';
                document.getElementById('binary-filename').textContent =
                    `${file.name} (header extracted, ${formatFileSize(result.header.length)})`;

                hideExtractionStatus();
                tabManager.validateFormat();
                return;
            }
        } catch (err) {
            console.warn('Client-side BAM header extraction failed, falling back to upload:', err);
            hideExtractionStatus();
            // Fall through to server-side streaming upload
        }
    }

    // Validate file size for text formats only; binary uploads are streamed
    // server-side (only the header is read), so no client-side limit is needed.
    if (format !== 'binary') {
        const validation = validateFileSize(file, MAX_TEXT_FILE_SIZE);
        if (!validation.valid) {
            showUploadError(validation.error);
            input.value = ''; // Clear the file input
            return;
        }
    }

    tabManager.currentFile = file;
    tabManager.currentFormat = format;

    // Show preview for text-based formats
    if (['text', 'assembly', 'vcf'].includes(format)) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const content = e.target.result;

            if (format === 'text') {
                document.getElementById('header-input').value = content;
                tabManager.validateFormat();
            } else if (format === 'assembly') {
                document.getElementById('assembly-input').value = content;
                tabManager.validateFormat();
            } else if (format === 'vcf') {
                document.getElementById('vcf-input').value = content;
                tabManager.validateFormat();
            }
        };
        reader.readAsText(file);
    } else if (format === 'binary') {
        document.getElementById('binary-preview').style.display = 'block';
        document.getElementById('binary-filename').textContent = file.name;
        tabManager.validateFormat();
    }
}

/**
 * Load example data into the current tab's textarea
 * @param {string} tabType - Tab type identifier (sam-dict, assembly-report, vcf)
 * @returns {void}
 */
function loadExample(tabType) {
    const example = examples[tabType];
    if (!example) {
        return;
    }

    let textareaId;
    switch (tabType) {
        case 'sam-dict':
            textareaId = 'header-input';
            break;
        case 'assembly-report':
            textareaId = 'assembly-input';
            break;
        case 'vcf':
            textareaId = 'vcf-input';
            break;
        default:
            return;
    }

    const textarea = document.getElementById(textareaId);
    if (textarea) {
        textarea.value = example;
        tabManager.validateFormat();
    }

    // Set threshold to 0 so example matches are visible
    updateThreshold(0);
    const slider = document.getElementById('score-threshold');
    if (slider) {
        slider.value = 0;
    }
}

/**
 * Clear a textarea and revalidate the form
 * @param {string} textareaId - ID of the textarea to clear
 * @returns {void}
 */
function clearTextArea(textareaId) {
    const textarea = document.getElementById(textareaId);
    if (textarea) {
        textarea.value = '';
        tabManager.validateFormat();
    }
}

// Expose all functions globally for inline event handlers
window.showTab = showTab;
window.toggleHelp = toggleHelp;
window.showHelpTab = showHelpTab;
window.updateThreshold = updateThreshold;
window.updateWeight = updateWeight;
window.toggleAdvanced = toggleAdvanced;
window.toggleResultDetails = toggleResultDetails;
window.toggleInputSection = toggleInputSection;
window.collapseInputAfterIdentify = collapseInputAfterIdentify;
window.handleFileUpload = handleFileUpload;
window.loadExample = loadExample;
window.clearTextArea = clearTextArea;
window.escapeHtml = escapeHtml;

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    configManager.updateUI();
    tabManager.validateFormat();

    // Add input event listeners for real-time validation
    const textareas = ['header-input', 'assembly-input', 'vcf-input'];
    textareas.forEach(id => {
        const textarea = document.getElementById(id);
        if (textarea) {
            textarea.addEventListener('input', function() {
                tabManager.validateFormat();
            });
            textarea.addEventListener('paste', function() {
                // Validate after paste content is processed
                setTimeout(() => tabManager.validateFormat(), 10);
            });
        }
    });

    // Add change listener for result limit
    const resultLimitEl = document.getElementById('result-limit');
    if (resultLimitEl) {
        resultLimitEl.addEventListener('change', function() {
            configManager.resultLimit = parseInt(this.value, 10);
            configManager.saveConfig();
        });
    }

    // Form submission
    const identifyForm = document.getElementById('identify-form');
    if (identifyForm) {
        identifyForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            // Collapse input section after clicking identify
            collapseInputAfterIdentify();

            const input = tabManager.getCurrentInput();

            if (!input) {
                const resultsDiv = document.getElementById('results');
                resultsDiv.innerHTML = '<div class="error">No valid input found. Please enter text or upload a file.</div>';
                return;
            }

            const resultsDiv = document.getElementById('results');
            resultsDiv.innerHTML = '<div class="loading">Analyzing...</div>';

            try {
                const formData = new FormData();

                if (input.type === 'text') {
                    formData.append('header_text', input.content);
                    if (input.filename) {
                        formData.append('filename', input.filename);
                    }
                } else if (input.type === 'file') {
                    formData.append('file', input.file);
                }

                // Add configuration
                const config = configManager.getConfig();

                formData.append('config', JSON.stringify(config));
                const response = await fetch('/api/identify', {
                    method: 'POST',
                    body: formData
                });

                if (!response.ok) {
                    const responseText = await response.text();
                    throw new Error(`HTTP ${response.status}: ${response.statusText} - ${responseText}`);
                }

                let data;
                try {
                    data = await response.json();
                } catch (jsonError) {
                    throw new Error(`Invalid JSON response from server: ${jsonError.message}`);
                }

                // Store input and config in SplitViewManager for detailed requests
                splitViewManager.originalInput = input;
                splitViewManager.originalConfig = config;

                resultsManager.renderResults(data, config);
            } catch (error) {
                resultsDiv.innerHTML = `<div class="error">Error: ${escapeHtml(error.message)}</div>`;
            }
        });
    }
});

// Export for testing
export {
    configManager,
    tabManager,
    resultsManager,
    helpSystem,
    splitViewManager,
    showTab,
    toggleHelp,
    showHelpTab,
    updateThreshold,
    updateWeight,
    toggleAdvanced,
    toggleResultDetails,
    toggleInputSection,
    collapseInputAfterIdentify,
    handleFileUpload,
    loadExample,
    clearTextArea
};