// Analyzer page functionality document.addEventListener('DOMContentLoaded', function() { initUpload(); initAnalysis(); initResults(); initCreateChallengeModal(); // Check if we should load a sample case const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('sample') === 'true') { loadSampleCase(); } }); // Upload functionality function initUpload() { const uploadZone = document.getElementById('uploadZone'); const fileInput = document.getElementById('fileInput'); const browseButton = document.getElementById('browseButton'); const filePreview = document.getElementById('filePreview'); const analyzeBtn = document.getElementById('analyzeBtn'); const addMoreFilesBtn = document.getElementById('addMoreFiles'); const clearAllFilesBtn = document.getElementById('clearAllFiles'); const previewList = document.getElementById('previewList'); const fileCount = document.getElementById('fileCount'); // Store selected files let selectedFiles = []; // Click to upload uploadZone.addEventListener('click', () => { fileInput.click(); }); // Browse button if (browseButton) { browseButton.addEventListener('click', (e) => { e.stopPropagation(); fileInput.click(); }); } // Add more files button addMoreFilesBtn.addEventListener('click', () => { fileInput.click(); }); // Clear all files button clearAllFilesBtn.addEventListener('click', () => { clearAllFiles(); }); // File input change (auto-start analysis) fileInput.addEventListener('change', (e) => { handleFileSelect(e); if (getSelectedFiles().length > 0) { startAnalysis(); } }); // Drag and drop uploadZone.addEventListener('dragover', (e) => { e.preventDefault(); uploadZone.classList.add('drag-over'); }); uploadZone.addEventListener('dragleave', (e) => { e.preventDefault(); uploadZone.classList.remove('drag-over'); }); uploadZone.addEventListener('drop', (e) => { e.preventDefault(); uploadZone.classList.remove('drag-over'); const files = e.dataTransfer.files; if (files.length > 0) { handleFileSelect({ target: { files } }); } }); // Analyze button analyzeBtn.addEventListener('click', startAnalysis); function handleFileSelect(e) { const files = Array.from(e.target.files); if (files.length === 0) return; // Validate each file const validFiles = []; const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/tiff']; files.forEach(file => { // Validate file type if (!validTypes.includes(file.type)) { window.oncoConnect.showToast(`Invalid file type: ${file.name}. Please upload JPG, PNG, or TIFF files.`, 'error'); return; } // Validate file size (max 50MB) if (file.size > 50 * 1024 * 1024) { window.oncoConnect.showToast(`File too large: ${file.name}. Maximum size is 50MB.`, 'error'); return; } validFiles.push(file); }); if (validFiles.length === 0) return; // Add valid files to selected files selectedFiles = [...selectedFiles, ...validFiles]; // Update UI updateFilePreview(); updateAnalyzeButton(); // Clear file input fileInput.value = ''; } function updateFilePreview() { if (selectedFiles.length === 0) { filePreview.style.display = 'none'; return; } filePreview.style.display = 'block'; // Update file count fileCount.textContent = `${selectedFiles.length} file${selectedFiles.length > 1 ? 's' : ''}`; // Clear and rebuild preview list previewList.innerHTML = ''; selectedFiles.forEach((file, index) => { const previewItem = createFilePreviewItem(file, index); previewList.appendChild(previewItem); }); } function createFilePreviewItem(file, index) { const item = document.createElement('div'); item.className = 'preview-item'; item.innerHTML = `
${file.name}
${window.oncoConnect.formatFileSize(file.size)} Ready to analyze
`; return item; } function removeFile(index) { selectedFiles.splice(index, 1); updateFilePreview(); updateAnalyzeButton(); } function clearAllFiles() { selectedFiles = []; updateFilePreview(); updateAnalyzeButton(); } function updateAnalyzeButton() { const analyzeBtn = document.getElementById('analyzeBtn'); analyzeBtn.disabled = selectedFiles.length === 0; // Update button text based on file count const btnText = analyzeBtn.querySelector('.btn-text'); if (selectedFiles.length === 0) { btnText.textContent = 'Analyze Images'; } else if (selectedFiles.length === 1) { btnText.textContent = 'Analyze Image'; } else { btnText.textContent = `Analyze ${selectedFiles.length} Images`; } } // Make functions globally accessible window.removeFile = removeFile; window.clearAllFiles = clearAllFiles; window.getSelectedFiles = () => selectedFiles; } // Analysis functionality function initAnalysis() { // Already initialized in initUpload } function startAnalysis() { const selectedFiles = window.getSelectedFiles(); if (!selectedFiles || selectedFiles.length === 0) { window.oncoConnect.showToast('Please select at least one image to analyze', 'error'); return; } const uploadSection = document.getElementById('uploadSection'); const loadingSection = document.getElementById('loadingSection'); const resultsSection = document.getElementById('resultsSection'); // Hide upload, show loading uploadSection.style.display = 'none'; loadingSection.style.display = 'block'; resultsSection.style.display = 'none'; // Show toast with file count const fileCount = selectedFiles.length; const message = fileCount === 1 ? 'Analysis started...' : `Analysis started for ${fileCount} images...`; window.oncoConnect.showToast(message, 'info'); // Simulate analysis steps with progress bar const steps = ['step1', 'step2', 'step3', 'step4']; const stepTexts = [ 'Starting analysis...', `Processing ${fileCount} image${fileCount > 1 ? 's' : ''}...`, 'Running AI classification...', 'Finding clinical trials...' ]; let currentStep = 0; const progressFill = document.getElementById('progressFill'); const progressText = document.getElementById('progressText'); const progressInterval = setInterval(() => { if (currentStep > 0) { // Mark previous step as completed const prevStep = document.getElementById(steps[currentStep - 1]); prevStep.classList.remove('active'); prevStep.classList.add('completed'); } if (currentStep < steps.length) { // Activate current step const currentStepEl = document.getElementById(steps[currentStep]); currentStepEl.classList.add('active'); // Update progress bar const progress = ((currentStep + 1) / steps.length) * 100; progressFill.style.width = progress + '%'; progressText.textContent = stepTexts[currentStep]; currentStep++; } else { clearInterval(progressInterval); // Complete the progress bar progressFill.style.width = '100%'; progressText.textContent = 'Analysis complete!'; // Show results after a short delay setTimeout(() => { showResults(); }, 1000); } }, 1200); } function showResults() { const loadingSection = document.getElementById('loadingSection'); const resultsSection = document.getElementById('resultsSection'); const selectedFiles = window.getSelectedFiles(); loadingSection.style.display = 'none'; resultsSection.style.display = 'block'; // Load sample results loadResultsData(); // Setup image selector if multiple images setupImageSelector(selectedFiles); // Scroll to results resultsSection.scrollIntoView({ behavior: 'smooth' }); } function setupImageSelector(files) { const imageSelector = document.getElementById('imageSelector'); const imageSelect = document.getElementById('imageSelect'); if (files.length > 1) { // Show selector and populate options imageSelector.style.display = 'block'; imageSelect.innerHTML = ''; files.forEach((file, index) => { const option = document.createElement('option'); option.value = index; option.textContent = file.name; imageSelect.appendChild(option); }); // Add change listener imageSelect.addEventListener('change', (e) => { const selectedIndex = parseInt(e.target.value); switchToImage(selectedIndex, files[selectedIndex]); }); // Initialize with first image switchToImage(0, files[0]); } else { // Hide selector for single image imageSelector.style.display = 'none'; if (files.length === 1) { switchToImage(0, files[0]); } } } function switchToImage(index, file) { // Update image info document.getElementById('imageFileName').textContent = file.name; document.getElementById('imageResolution').textContent = '2048×2048'; // Placeholder document.getElementById('analyzedTime').textContent = '2 minutes ago'; // Placeholder // Update image source (placeholder for now) const img = document.getElementById('analyzedImage'); img.src = URL.createObjectURL(file); img.alt = `Analyzed pathology image: ${file.name}`; // Reinitialize image viewer initImageViewer(); } function loadSampleCase() { // Auto-load a sample case for demo with multiple images const mockFiles = [ { name: 'sample_breast_wsi_1.jpg', size: 2.4 * 1024 * 1024, type: 'image/jpeg' }, { name: 'sample_breast_wsi_2.jpg', size: 1.8 * 1024 * 1024, type: 'image/jpeg' } ]; // Set selected files window.getSelectedFiles = () => mockFiles; // Update UI updateFilePreview(); updateAnalyzeButton(); // Auto-start analysis after a delay setTimeout(() => { startAnalysis(); }, 1000); function updateFilePreview() { const filePreview = document.getElementById('filePreview'); const previewList = document.getElementById('previewList'); const fileCount = document.getElementById('fileCount'); filePreview.style.display = 'block'; fileCount.textContent = `${mockFiles.length} files`; previewList.innerHTML = ''; mockFiles.forEach((file, index) => { const previewItem = createFilePreviewItem(file, index); previewList.appendChild(previewItem); }); } function updateAnalyzeButton() { const analyzeBtn = document.getElementById('analyzeBtn'); analyzeBtn.disabled = false; const btnText = analyzeBtn.querySelector('.btn-text'); btnText.textContent = `Analyze ${mockFiles.length} Images`; } function createFilePreviewItem(file, index) { const item = document.createElement('div'); item.className = 'preview-item'; item.innerHTML = `
${file.name}
${window.oncoConnect.formatFileSize(file.size)} Ready to analyze
`; return item; } } // Results functionality function initResults() { // Save case button document.getElementById('saveCase').addEventListener('click', () => { requireAuth(saveCase); }); // Create challenge button document.getElementById('createChallenge').addEventListener('click', () => { requireAuth(() => { window.oncoConnect.openModal('createChallengeModal'); }); }); // Analyze another button document.getElementById('analyzeAnother').addEventListener('click', resetAnalyzer); // Heatmap controls initHeatmapControls(); // Trial filters initTrialFilters(); // Export trials const exportBtn = document.getElementById('exportTrials'); if (exportBtn) exportBtn.addEventListener('click', exportTrials); } function loadResultsData() { // Load analyzed image - use uploaded file if available const analyzedImage = document.getElementById('analyzedImage'); const uploadZone = document.getElementById('uploadZone'); if (uploadZone.selectedFile) { // Use the actual uploaded file const reader = new FileReader(); reader.onload = function(e) { analyzedImage.src = e.target.result; }; reader.readAsDataURL(uploadZone.selectedFile); // Update image info document.getElementById('imageFileName').textContent = uploadZone.selectedFile.name; document.getElementById('imageResolution').textContent = '2048×2048'; // Mock resolution } else { // Use placeholder for demo analyzedImage.src = createPlaceholderImage(400, 400, '#f8fafc', '🔬 Pathology Image'); document.getElementById('imageFileName').textContent = 'sample_breast_wsi.jpg'; document.getElementById('imageResolution').textContent = '2048×2048'; } // Update analyzed time document.getElementById('analyzedTime').textContent = 'Just now'; // Create heatmap overlay createHeatmapOverlay(); // Set diagnosis results document.getElementById('cancerStatus').textContent = 'Yes'; document.getElementById('confidenceValue').textContent = '94.2%'; document.getElementById('diagnosisExplanation').textContent = 'Analysis indicates invasive ductal carcinoma with well-defined tumor boundaries. High cellular density and irregular nuclear morphology support malignant classification.'; // Set chemo response document.getElementById('chemoResponse').textContent = 'Likely Responsive'; document.getElementById('chemoExplanation').textContent = 'Tumor characteristics suggest good response to standard chemotherapy protocols. High proliferation markers and hormone receptor status indicate favorable treatment outcomes.'; // Update risk assessment demo updateRiskAssessment(87); // Load clinical trials loadClinicalTrials(); // Initialize image viewer controls initImageViewer(); } function updateRiskAssessment(score) { const riskScoreEl = document.getElementById('riskScore'); const riskBadgeEl = document.getElementById('riskBadge'); const riskCategoryEl = document.getElementById('riskCategory'); if (!riskScoreEl || !riskBadgeEl || !riskCategoryEl) return; riskScoreEl.textContent = String(score); let riskLevel, riskClass; if (score >= 70) { riskLevel = 'HIGH RISK'; riskClass = 'high-risk'; } else if (score >= 40) { riskLevel = 'MEDIUM RISK'; riskClass = 'medium-risk'; } else { riskLevel = 'LOW RISK'; riskClass = 'low-risk'; } riskBadgeEl.textContent = riskLevel; riskBadgeEl.className = 'card-badge ' + riskClass; riskCategoryEl.textContent = riskLevel; } function createPlaceholderImage(width, height, color, text) { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.fillStyle = color; ctx.fillRect(0, 0, width, height); // Add some pattern to simulate pathology image ctx.strokeStyle = '#e2e8f0'; ctx.lineWidth = 1; // Create a grid pattern for (let i = 0; i < width; i += 20) { for (let j = 0; j < height; j += 20) { if (Math.random() > 0.7) { ctx.fillStyle = '#e2e8f0'; ctx.fillRect(i, j, 15, 15); } } } // Add text ctx.fillStyle = '#9ca3af'; ctx.font = '20px sans-serif'; ctx.textAlign = 'center'; ctx.fillText(text, width/2, height/2); return canvas.toDataURL(); } function createHeatmapOverlay() { const canvas = document.getElementById('heatmapOverlay'); const ctx = canvas.getContext('2d'); canvas.width = 400; canvas.height = 400; // Create random heatmap pattern const gradient = ctx.createRadialGradient(200, 200, 0, 200, 200, 150); gradient.addColorStop(0, 'rgba(255, 0, 0, 0.8)'); gradient.addColorStop(0.5, 'rgba(255, 255, 0, 0.6)'); gradient.addColorStop(1, 'rgba(255, 0, 0, 0)'); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 400, 400); // Add some random hot spots for (let i = 0; i < 5; i++) { const x = Math.random() * 400; const y = Math.random() * 400; const radius = Math.random() * 30 + 20; const spotGradient = ctx.createRadialGradient(x, y, 0, x, y, radius); spotGradient.addColorStop(0, 'rgba(255, 0, 0, 0.9)'); spotGradient.addColorStop(1, 'rgba(255, 0, 0, 0)'); ctx.fillStyle = spotGradient; ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI); ctx.fill(); } } function initImageViewer() { const zoomInBtn = document.getElementById('zoomIn'); const zoomOutBtn = document.getElementById('zoomOut'); const fitScreenBtn = document.getElementById('fitScreen'); const downloadOverlayBtn = document.getElementById('downloadOverlay'); const analyzedImage = document.getElementById('analyzedImage'); let currentZoom = 1; const minZoom = 0.5; const maxZoom = 3; const zoomStep = 0.2; zoomInBtn.addEventListener('click', () => { currentZoom = Math.min(currentZoom + zoomStep, maxZoom); updateImageZoom(); }); zoomOutBtn.addEventListener('click', () => { currentZoom = Math.max(currentZoom - zoomStep, minZoom); updateImageZoom(); }); fitScreenBtn.addEventListener('click', () => { currentZoom = 1; updateImageZoom(); }); downloadOverlayBtn.addEventListener('click', () => { downloadHeatmap(); }); function updateImageZoom() { analyzedImage.style.transform = `scale(${currentZoom})`; analyzedImage.style.transformOrigin = 'center'; } function downloadHeatmap() { const canvas = document.getElementById('heatmapOverlay'); const link = document.createElement('a'); link.download = 'heatmap-overlay.png'; link.href = canvas.toDataURL(); link.click(); window.oncoConnect.showToast('Heatmap downloaded successfully!', 'success'); } } function initHeatmapControls() { const heatmapToggle = document.getElementById('heatmapToggle'); const opacitySlider = document.getElementById('opacitySlider'); const opacityValue = document.getElementById('opacityValue'); const heatmapOverlay = document.getElementById('heatmapOverlay'); // Initialize heatmap visibility updateHeatmapVisibility(); heatmapToggle.addEventListener('change', () => { updateHeatmapVisibility(); }); opacitySlider.addEventListener('input', () => { const opacity = opacitySlider.value / 100; heatmapOverlay.style.opacity = opacity; opacityValue.textContent = opacitySlider.value + '%'; }); } function updateHeatmapVisibility() { const heatmapToggle = document.getElementById('heatmapToggle'); const heatmapOverlay = document.getElementById('heatmapOverlay'); const analyzedImage = document.getElementById('analyzedImage'); if (heatmapToggle.checked) { // Show both image and heatmap overlay analyzedImage.style.display = 'block'; heatmapOverlay.style.display = 'block'; } else { // Show only the uploaded image analyzedImage.style.display = 'block'; heatmapOverlay.style.display = 'none'; } } function initTrialFilters() { const filterChips = document.querySelectorAll('.filter-chip'); filterChips.forEach(chip => { chip.addEventListener('click', () => { const group = chip.parentElement; // Remove active from siblings group.querySelectorAll('.filter-chip').forEach(sibling => { sibling.classList.remove('active'); }); // Add active to clicked chip chip.classList.add('active'); // Filter trials filterTrials(); }); }); } function filterTrials() { const activePhase = document.querySelector('.filter-chip[data-phase].active')?.dataset.phase || 'all'; const activeStatus = document.querySelector('.filter-chip[data-status].active')?.dataset.status || 'all'; const activeDistance = document.querySelector('.filter-chip[data-distance].active')?.dataset.distance || 'all'; const activeBiomarker = document.querySelector('.filter-chip[data-biomarker].active')?.dataset.biomarker || 'all'; const trialCards = document.querySelectorAll('.trial-card'); trialCards.forEach(card => { const phase = card.dataset.phase; const status = card.dataset.status; const distance = card.dataset.distance || 'remote'; const biomarkers = (card.dataset.biomarkers || '').split(','); const phaseMatch = activePhase === 'all' || phase === activePhase; const statusMatch = activeStatus === 'all' || status === activeStatus; const distanceMatch = activeDistance === 'all' || distance === activeDistance; const biomarkerMatch = activeBiomarker === 'all' || biomarkers.includes(activeBiomarker); card.style.display = (phaseMatch && statusMatch && distanceMatch && biomarkerMatch) ? 'block' : 'none'; }); } function loadClinicalTrials() { const trialsList = document.getElementById('trialsList'); const trials = window.oncoConnect.getClinicalTrials(); trialsList.innerHTML = trials.map(trial => `

${trial.title}

${trial.phase} ${trial.status}
${trial.description}
Inclusion: ${trial.inclusion}
Site: ${trial.location}
Contact: ${trial.contact}
`).join(''); } function saveCase() { const caseData = { id: window.oncoConnect.generateId(), fileName: document.getElementById('fileName').textContent, diagnosis: document.getElementById('cancerStatus').textContent, confidence: document.getElementById('confidenceValue').textContent, timestamp: new Date().toISOString(), chemoResponse: document.getElementById('chemoResponse').textContent }; // Save to localStorage const savedCases = window.oncoConnect.getSavedData('savedCases') || []; savedCases.push(caseData); window.oncoConnect.saveData('savedCases', savedCases); window.oncoConnect.showToast('Case saved successfully!'); } function resetAnalyzer() { document.getElementById('uploadSection').style.display = 'block'; document.getElementById('loadingSection').style.display = 'none'; document.getElementById('resultsSection').style.display = 'none'; // Clear file input document.getElementById('fileInput').value = ''; document.getElementById('filePreview').style.display = 'none'; document.getElementById('analyzeBtn').disabled = true; // Scroll to top window.scrollTo({ top: 0, behavior: 'smooth' }); } // Create Challenge Modal functionality function initCreateChallengeModal() { const modal = document.getElementById('createChallengeModal'); const form = document.getElementById('challengeForm'); const closeBtn = document.getElementById('closeChallengeModal'); const cancelBtn = document.getElementById('cancelChallenge'); closeBtn.addEventListener('click', () => { window.oncoConnect.closeModal(modal); }); cancelBtn.addEventListener('click', () => { window.oncoConnect.closeModal(modal); }); form.addEventListener('submit', (e) => { e.preventDefault(); createChallenge(); }); } function createChallenge() { const title = document.getElementById('challengeTitle').value; const description = document.getElementById('challengeDescription').value; const difficulty = document.getElementById('challengeDifficulty').value; const challengeData = { id: window.oncoConnect.generateId(), title, description, difficulty, solved: 0, enrolled: true, createdBy: 'user', timestamp: new Date().toISOString() }; // Add to challenges const challenges = window.oncoConnect.getSavedData('challenges') || []; challenges.push(challengeData); window.oncoConnect.saveData('challenges', challenges); // Close modal and show success window.oncoConnect.closeModal('createChallengeModal'); window.oncoConnect.showToast('Challenge created successfully!'); // Reset form document.getElementById('challengeForm').reset(); }