// DocMap Agent - Enhanced Script with Improved Navigation and Document Catalog // Override renderDocumentViewTabs const originalRenderDocumentViewTabs = window.renderDocumentViewTabs; window.renderDocumentViewTabs = function() { console.log("RENDERING TABS START"); console.log("documentsData length:", documentsData.length); console.log("mainTabsDocViewContainer exists:", !!mainTabsDocViewContainer); try { // Simple fallback tab rendering const tabNames = ['All', 'Discovery', 'Preclinical', 'Clinical Development', 'Regulatory Submission']; let tabsHtml = ''; tabNames.forEach(tabName => { const isActive = tabName === currentDocViewTab; tabsHtml += ` `; }); mainTabsDocViewContainer.innerHTML = tabsHtml; // Add event listeners mainTabsDocViewContainer.querySelectorAll('.doc-view-tab').forEach(tab => { tab.addEventListener('click', () => { currentDocViewTab = tab.dataset.tabName; renderDocumentViewTabs(); renderDocumentList(); updateBreadcrumb(); clearSelection(); }); }); console.log("RENDERING TABS COMPLETE"); } catch (error) { console.error("Error rendering tabs:", error); } }; // Override renderDocumentList const originalRenderDocumentList = window.renderDocumentList; window.renderDocumentList = function() { console.log("RENDERING LIST START"); console.log("Current view:", currentVisibleView); console.log("Current tab:", currentDocViewTab); try { if (currentVisibleView !== 'documentViewWrapper') return; // Simple implementation of document list const searchTerm = searchInputDocView.value.toLowerCase(); let filteredDocs = documentsData; if (currentDocViewTab !== 'All') { filteredDocs = filteredDocs.filter(doc => { // Simplified phase mapping const docPhase = doc.Phase || ''; return docPhase.includes(currentDocViewTab) || (currentDocViewTab === 'Clinical Development' && docPhase.includes('Clinical')); }); } if (searchTerm) { filteredDocs = filteredDocs.filter(doc => doc.Document_Name.toLowerCase().includes(searchTerm) || doc.Doc_ID_Type.toLowerCase().includes(searchTerm) ); } if (filteredDocs.length === 0) { documentListDocViewContainer.innerHTML = `

No documents found.

`; } else { let listHtml = ''; documentListDocViewContainer.innerHTML = listHtml; // Add event listeners document.querySelectorAll('.doc-list-item').forEach(item => { item.addEventListener('click', () => { alert(`Document details for: ${item.dataset.docId}`); // Uncomment to use modal when fixed // currentSelectedDocId = item.dataset.docId; // displayDetailsInModal(currentSelectedDocId); }); }); } console.log("RENDERING LIST COMPLETE"); } catch (error) { console.error("Error rendering document list:", error); } }; // Override flowsList rendering const originalRenderFlowsList = window.renderFlowsList; window.renderFlowsList = function() { console.log("RENDERING FLOWS START"); try { const flowIds = Object.keys(flowDefinitions); console.log("Flow IDs:", flowIds); if (flowIds.length === 0) { flowsListContainer.innerHTML = '

No flows available

'; return; } let flowsHtml = ''; flowIds.forEach(id => { const title = id.replace(/_/g, ' ').toUpperCase(); flowsHtml += `
${title}
`; }); flowsListContainer.innerHTML = flowsHtml; // Add event listeners flowsListContainer.querySelectorAll('.flow-card').forEach(card => { card.addEventListener('click', () => { const flowId = card.dataset.flowId; currentSelectedFlowId = flowId; alert(`Selected flow: ${flowId}`); // Uncomment when fixed // displayFlowGraph(flowId); // renderFlowsList(); }); }); console.log("RENDERING FLOWS COMPLETE"); } catch (error) { console.error("Error rendering flows list:", error); } }; // Force load sequence after a delay setTimeout(() => { console.log("FORCE LOADING SEQUENCE"); if (currentVisibleView === 'documentViewWrapper') { renderDocumentViewTabs(); renderDocumentList(); } else if (currentVisibleView === 'flowsViewWrapper') { renderFlowsList(); } }, 3000); // Initialize Mermaid mermaid.initialize({ startOnLoad: false, theme: 'base', securityLevel: 'loose', /* Allow clicks */ themeVariables: { primaryColor: '#eff6ff', // blue-50 primaryTextColor: '#1e3a8a', // blue-900 primaryBorderColor: '#60a5fa', // blue-400 lineColor: '#6b7280', // gray-500 secondaryColor: '#f1f5f9', // slate-100 tertiaryColor: '#e0f2fe' // sky-100 } }); // --- Global Variables --- let documentsData = []; let templateData = []; const flowDefinitions = { // Keep example flows from v2 "p1_sad": `graph TD; subgraph Preclinical & Setup; IB(IB v1):::input --> CLI-PROT-P1(Phase 1 Protocol):::core; PRE-REP-TOX(Tox Report):::input --> IB; PRE-REP-PK(PK Report):::input --> IB; PRE-REP-CMC-STAB(Stability Report):::input --> IB; CLI-PROT-P1 --> REG-SUB-IND(IND / CTA):::output; CLI-PROT-P1 --> ICF(Informed Consent Form):::output; CLI-PROT-P1 --> CRF(eCRF Spec):::output; CLI-PROT-P1 --> CLI-PLAN-SAP(Stat Analysis Plan):::output; CLI-PROT-P1 --> CLI-PLAN-DMP(Data Mgt Plan):::output; CLI-PROT-P1 --> CLI-MAN-IMPHANDLE(IMP Handling Manual):::output; CLI-PROT-P1 --> CMC-LABEL-IMP(IMP Label Spec):::output; end; subgraph Execution & Reporting; ICF --> SiteOps[Site Operations / Enrollment]; CRF --> SiteOps; CLI-MAN-IMPHANDLE --> SiteOps; CMC-LABEL-IMP --> SiteOps; CLI-PLAN-DMP --> SiteOps; SiteOps --> ClinicalData[(Clinical Database)]; CLI-PLAN-SAP --> Analysis[Statistical Analysis]; ClinicalData --> Analysis; Analysis --> CLI-REP-CSR(Phase 1 CSR):::core; ClinicalData --> CLI-REP-CSR; IB --> CLI-REP-CSR; end; subgraph Updates & Follow-on; CLI-REP-CSR --> IB_v2(IB Update v2):::output; CLI-REP-CSR --> REG-AR(IND Annual Report / DSUR):::output; CLI-REP-CSR --> CLI-PLAN-CDP(Clinical Dev Plan Update):::output; end; classDef input fill:#f3e8ff,stroke:#a855f7,color:#581c87; classDef core fill:#e0f2fe,stroke:#38bdf8,color:#075985; classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d; click IB call displayDetailsAndGraphFromGraph("IB") "View Details"; click PRE-REP-TOX call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Details"; click PRE-REP-PK call displayDetailsAndGraphFromGraph("PRE-REP-PK") "View Details"; click PRE-REP-CMC-STAB call displayDetailsAndGraphFromGraph("PRE-REP-CMC-STAB") "View Details"; click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details"; click REG-SUB-IND call displayDetailsAndGraphFromGraph("REG-SUB-IND") "View Details"; click ICF call displayDetailsAndGraphFromGraph("ICF") "View Details"; click CRF call displayDetailsAndGraphFromGraph("CRF") "View Details"; click CLI-PLAN-SAP call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details"; click CLI-PLAN-DMP call displayDetailsAndGraphFromGraph("CLI-PLAN-DMP") "View Details"; click CLI-MAN-IMPHANDLE call displayDetailsAndGraphFromGraph("CLI-MAN-IMPHANDLE") "View Details"; click CMC-LABEL-IMP call displayDetailsAndGraphFromGraph("CMC-LABEL-IMP") "View Details"; click CLI-REP-CSR call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details"; click IB_v2 call displayDetailsAndGraphFromGraph("IB") "View Details (Latest IB)"; click REG-AR call displayDetailsAndGraphFromGraph("REG-AR") "View Details"; click CLI-PLAN-CDP call displayDetailsAndGraphFromGraph("CLI-PLAN-CDP") "View Details";`, "nda_submission": `graph TD; subgraph Inputs; CSRs(All Phase 1-3 CSRs):::input --> REG-ISS(ISS):::core; CSRs --> REG-ISE(ISE):::core; NonClinReps(All Nonclinical Reports):::input --> REG-CTD-M2(CTD Module 2 Summaries):::core; CMCDataPkg(Full CMC Data Package):::input --> REG-CTD-M3(CTD Module 3 Quality):::core; ProposedLabel(Proposed Label / SmPC):::input --> REG-CTD-M1(CTD Module 1 Admin & Label):::core; end; subgraph CTD_Assembly; REG-ISS --> REG-CTD-M5(CTD Module 5 Clinical):::output; REG-ISE --> REG-CTD-M5; CSRs --> REG-CTD-M5; NonClinReps --> REG-CTD-M4(CTD Module 4 Nonclinical):::output; REG-CTD-M1 --> FullSubmission[eCTD Submission Package]; REG-CTD-M2 --> FullSubmission; REG-CTD-M3 --> FullSubmission; REG-CTD-M4 --> FullSubmission; REG-CTD-M5 --> FullSubmission; end; subgraph Submission_Output; FullSubmission --> REG-SUB-NDA(NDA / MAA Submission):::final; REG-SUB-NDA --> AgencyReview{Agency Review}; AgencyReview --> REG-RTQ(Responses to Questions):::input; REG-RTQ --> AgencyReview; AgencyReview --> ApprovalDecision[Approval / Rejection]; end; classDef input fill:#fef9c3,stroke:#eab308,color:#854d0e; classDef core fill:#e0f2fe,stroke:#38bdf8,color:#075985; classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d; classDef final fill:#fee2e2,stroke:#f87171,color:#991b1b; click CSRs call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View CSR Details (Example)"; click NonClinReps call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Tox Report (Example)"; click CMCDataPkg call displayDetailsAndGraphFromGraph("PRE-REP-CMC-PROCDEV") "View CMC Report (Example)"; click ProposedLabel call displayDetailsAndGraphFromGraph("REG-LABEL-US") "View Label Details (Example)"; click REG-ISS call displayDetailsAndGraphFromGraph("REG-ISS") "View Details"; click REG-ISE call displayDetailsAndGraphFromGraph("REG-ISE") "View Details"; click REG-CTD-M1 call displayDetailsAndGraphFromGraph("REG-CTD-M1") "View Details"; click REG-CTD-M2 call displayDetailsAndGraphFromGraph("REG-CTD-M2") "View Details"; click REG-CTD-M3 call displayDetailsAndGraphFromGraph("REG-CTD-M3") "View Details"; click REG-CTD-M4 call displayDetailsAndGraphFromGraph("REG-CTD-M4") "View Details"; click REG-CTD-M5 call displayDetailsAndGraphFromGraph("REG-CTD-M5") "View Details"; click REG-SUB-NDA call displayDetailsAndGraphFromGraph("REG-SUB-NDA") "View Details"; click REG-RTQ call displayDetailsAndGraphFromGraph("REG-RTQ") "View Details";`, "ind_pathway": `graph TD; DIS-REP-TVAL(Target Validation Report):::discovery --> DIS-REP-LO(Lead Optimization Report):::discovery; DIS-REP-LO --> DIS-REP-CANDSEL(Candidate Selection Report):::discovery; DIS-REP-CANDSEL --> PRE-PLAN-DEV(Preclinical Development Plan):::preclinical; PRE-PLAN-DEV --> PRE-PROT-TOX(Toxicology Study Protocol):::preclinical; PRE-PLAN-DEV --> PRE-PROT-PK(PK Study Protocol):::preclinical; PRE-PLAN-DEV --> PRE-REP-CMC-PROCDEV(CMC Process Development):::preclinical; PRE-PROT-TOX --> PRE-REP-TOX(Toxicology Study Report):::preclinical; PRE-PROT-PK --> PRE-REP-PK(PK Study Report):::preclinical; PRE-REP-CMC-PROCDEV --> PRE-REP-CMC-STAB(Stability Report):::preclinical; PRE-REP-TOX --> IB(Investigator's Brochure):::clinical; PRE-REP-PK --> IB; PRE-REP-CMC-STAB --> IB; IB --> REG-SUB-IND(IND Submission):::regulatory; IB --> CLI-PROT-P1(Phase 1 Protocol):::clinical; CLI-PROT-P1 --> REG-SUB-IND; REG-SUB-IND --> CLI-REP-CSR(Clinical Study Reports):::clinical; classDef discovery fill:#dbeafe,stroke:#3b82f6,color:#1e40af; classDef preclinical fill:#dcfce7,stroke:#22c55e,color:#166534; classDef clinical fill:#ede9fe,stroke:#8b5cf6,color:#5b21b6; classDef regulatory fill:#fef3c7,stroke:#f59e0b,color:#92400e; click DIS-REP-TVAL call displayDetailsAndGraphFromGraph("DIS-REP-TVAL") "View Details"; click DIS-REP-LO call displayDetailsAndGraphFromGraph("DIS-REP-LO") "View Details"; click DIS-REP-CANDSEL call displayDetailsAndGraphFromGraph("DIS-REP-CANDSEL") "View Details"; click PRE-PLAN-DEV call displayDetailsAndGraphFromGraph("PRE-PLAN-DEV") "View Details"; click PRE-PROT-TOX call displayDetailsAndGraphFromGraph("PRE-PROT-TOX") "View Details"; click PRE-PROT-PK call displayDetailsAndGraphFromGraph("PRE-PROT-PK") "View Details"; click PRE-REP-CMC-PROCDEV call displayDetailsAndGraphFromGraph("PRE-REP-CMC-PROCDEV") "View Details"; click PRE-REP-TOX call displayDetailsAndGraphFromGraph("PRE-REP-TOX") "View Details"; click PRE-REP-PK call displayDetailsAndGraphFromGraph("PRE-REP-PK") "View Details"; click PRE-REP-CMC-STAB call displayDetailsAndGraphFromGraph("PRE-REP-CMC-STAB") "View Details"; click IB call displayDetailsAndGraphFromGraph("IB") "View Details"; click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details"; click REG-SUB-IND call displayDetailsAndGraphFromGraph("REG-SUB-IND") "View Details"; click CLI-REP-CSR call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details";`, "clinical_program": `graph TD; CLI-PLAN-TPP(Target Product Profile):::planning --> CLI-PLAN-CDP(Clinical Development Plan):::planning; CLI-PLAN-CDP --> CLI-PROT-P1(Phase 1 Protocol):::phase1; CLI-PLAN-CDP --> CLI-PROT-P2(Phase 2 Protocol):::phase2; CLI-PLAN-CDP --> CLI-PROT-P3(Phase 3 Protocol):::phase3; CLI-PROT-P1 --> ICF1(Phase 1 ICF):::phase1; CLI-PROT-P1 --> CRF1(Phase 1 CRF):::phase1; CLI-PROT-P1 --> CLI-PLAN-SAP1(Phase 1 SAP):::phase1; CLI-PROT-P2 --> ICF2(Phase 2 ICF):::phase2; CLI-PROT-P2 --> CRF2(Phase 2 CRF):::phase2; CLI-PROT-P2 --> CLI-PLAN-SAP2(Phase 2 SAP):::phase2; CLI-PROT-P3 --> ICF3(Phase 3 ICF):::phase3; CLI-PROT-P3 --> CRF3(Phase 3 CRF):::phase3; CLI-PROT-P3 --> CLI-PLAN-SAP3(Phase 3 SAP):::phase3; CLI-PROT-P3 --> CLI-CHARTER-DMC(DMC Charter):::phase3; CLI-PLAN-SAP1 --> CLI-REP-CSR1(Phase 1 CSR):::phase1; CLI-PLAN-SAP2 --> CLI-REP-CSR2(Phase 2 CSR):::phase2; CLI-PLAN-SAP3 --> CLI-REP-CSR3(Phase 3 CSR):::phase3; CLI-REP-CSR1 & CLI-REP-CSR2 & CLI-REP-CSR3 --> REG-ISS(Integrated Summary of Safety):::submission; CLI-REP-CSR2 & CLI-REP-CSR3 --> REG-ISE(Integrated Summary of Efficacy):::submission; REG-ISS & REG-ISE --> REG-SUB-NDA(NDA Submission):::submission; classDef planning fill:#dbeafe,stroke:#3b82f6,color:#1e40af; classDef phase1 fill:#ede9fe,stroke:#8b5cf6,color:#5b21b6; classDef phase2 fill:#fae8ff,stroke:#d946ef,color:#86198f; classDef phase3 fill:#fce7f3,stroke:#ec4899,color:#9d174d; classDef submission fill:#fee2e2,stroke:#f87171,color:#991b1b; click CLI-PLAN-TPP call displayDetailsAndGraphFromGraph("CLI-PLAN-TPP") "View Details"; click CLI-PLAN-CDP call displayDetailsAndGraphFromGraph("CLI-PLAN-CDP") "View Details"; click CLI-PROT-P1 call displayDetailsAndGraphFromGraph("CLI-PROT-P1") "View Details"; click CLI-PROT-P2 call displayDetailsAndGraphFromGraph("CLI-PROT-P2") "View Details"; click CLI-PROT-P3 call displayDetailsAndGraphFromGraph("CLI-PROT-P3") "View Details"; click ICF1 call displayDetailsAndGraphFromGraph("ICF") "View Details"; click CRF1 call displayDetailsAndGraphFromGraph("CRF") "View Details"; click CLI-PLAN-SAP1 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details"; click ICF2 call displayDetailsAndGraphFromGraph("ICF") "View Details"; click CRF2 call displayDetailsAndGraphFromGraph("CRF") "View Details"; click CLI-PLAN-SAP2 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details"; click ICF3 call displayDetailsAndGraphFromGraph("ICF") "View Details"; click CRF3 call displayDetailsAndGraphFromGraph("CRF") "View Details"; click CLI-PLAN-SAP3 call displayDetailsAndGraphFromGraph("CLI-PLAN-SAP") "View Details"; click CLI-CHARTER-DMC call displayDetailsAndGraphFromGraph("CLI-CHARTER-DMC") "View Details"; click CLI-REP-CSR1 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details"; click CLI-REP-CSR2 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details"; click CLI-REP-CSR3 call displayDetailsAndGraphFromGraph("CLI-REP-CSR") "View Details"; click REG-ISS call displayDetailsAndGraphFromGraph("REG-ISS") "View Details"; click REG-ISE call displayDetailsAndGraphFromGraph("REG-ISE") "View Details"; click REG-SUB-NDA call displayDetailsAndGraphFromGraph("REG-SUB-NDA") "View Details";` }; // --- DOM Elements Cache --- const mainContentArea = document.getElementById('mainContentArea'); const homeSection = document.getElementById('home'); const documentViewWrapper = document.getElementById('documentViewWrapper'); const flowsViewWrapper = document.getElementById('flowsViewWrapper'); const searchInputDocView = document.getElementById('searchInputDocView'); const headerSearchInput = document.getElementById('headerSearchInput'); const mainTabsDocViewContainer = document.getElementById('mainTabsDocView'); const documentListDocViewContainer = document.getElementById('documentListDocView'); const flowsListContainer = document.getElementById('flowsList'); const mermaidFlowGraphContainer = document.getElementById('mermaidFlowGraph'); const flowPlaceholder = document.getElementById('flowPlaceholder'); const showExampleFlowBtnFlowView = document.getElementById('showExampleFlowBtnFlowView'); const homeButton = document.getElementById('homeButton'); // Home Button const breadcrumbNav = document.getElementById('breadcrumbNav'); // Breadcrumb container // Modals const showExampleFlowBtnHeader = document.getElementById('showExampleFlowBtn'); // Button in header const exampleFlowModal = document.getElementById('exampleFlowModal'); const exampleMermaidGraphContainer = document.getElementById('exampleMermaidGraph'); const closeExampleModalBtn = document.getElementById('closeExampleModalBtn'); const detailsModal = document.getElementById('detailsModal'); const detailsModalTitle = document.getElementById('detailsModalTitle'); const detailsContentInModal = document.getElementById('detailsContentInModal'); const graphContentInModal = document.getElementById('graphContentInModal'); const mermaidGraphContainerInModal = document.getElementById('mermaidGraphInModal'); const closeDetailsModalBtn = document.getElementById('closeDetailsModalBtn'); const prevDocBtn = document.getElementById('prevDocBtn'); const nextDocBtn = document.getElementById('nextDocBtn'); // --- State Variables --- let currentVisibleView = 'home'; // Tracks which main section is visible ('home', 'documentViewWrapper', 'flowsViewWrapper') let currentDocViewTab = 'All'; // Track the active tab within the document view ('All', 'Discovery', ...) let currentSelectedDocId = null; let currentSelectedFlowId = null; let currentDocListIndices = { prev: null, next: null }; // --- Utility Functions --- function getDocNameById(docId) { const doc = documentsData.find(d => d.Doc_ID_Type === docId); return doc ? (doc.Document_Name.split('(')[0].trim() || doc.Document_Name) : docId; } function extractDocIDs(text) { if (!text || documentsData.length === 0) return []; const knownIDs = new Set(documentsData.map(doc => doc.Doc_ID_Type)); const potentialIDs = text.match(/[A-Z0-9]+(?:-[A-Z0-9]+)*\b/g) || []; // Use word boundary \b return potentialIDs.filter(id => knownIDs.has(id)); } function getComplexityIcon(complexity) { switch (complexity?.toLowerCase()) { case 'low': return ''; case 'low-medium': return ''; case 'medium': return ''; case 'medium-high': return ''; case 'high': return ''; default: return ''; } } function getRegulatoryIcon(significance) { if (!significance) return ''; const lowerSig = significance.toLowerCase(); if (lowerSig.includes('submission critical')) return ''; if (lowerSig.includes('gcp')) return ''; if (lowerSig.includes('glp')) return ''; if (lowerSig.includes('gmp')) return ''; if (lowerSig.includes('gvp')) return ''; if (lowerSig.includes('regulatory requirement')) return ''; if (lowerSig.includes('internal')) return ''; return ''; } function getMainTabIcon(tabName) { if (!tabName) return ''; const lowerTab = tabName.toLowerCase(); if (lowerTab.includes('discovery')) return ''; if (lowerTab.includes('preclinical')) return ''; if (lowerTab === 'clinical development') return ''; if (lowerTab === 'regulatory submission') return ''; if (lowerTab === 'post-marketing & quality') return ''; if (lowerTab.includes('flows')) return ''; if (lowerTab.includes('all')) return ''; return ''; } function linkDocumentIDsForDetails(text) { if (!text || documentsData.length === 0) return 'N/A'; const knownIDs = new Set(documentsData.map(doc => doc.Doc_ID_Type)); let linkedText = text.replace(/(\b[A-Z0-9]+(?:-[A-Z0-9]+)*\b)/g, (match) => { if (knownIDs.has(match)) { return `${match}`; } return match; }); return linkedText; } // --- Core Rendering & View Switching --- // Function to switch between major views (Home, Documents, Flows) function switchToView(viewId, initialTab = null) { console.log(`Switching view to: ${viewId}, Initial Tab: ${initialTab}`); currentVisibleView = viewId; // Hide all main sections homeSection.classList.add('hidden-container'); documentViewWrapper.classList.add('hidden-container'); flowsViewWrapper.classList.add('hidden-container'); // Show the target section const targetSection = document.getElementById(viewId); if (targetSection) { targetSection.classList.remove('hidden-container'); // Handle specific view initializations if (viewId === 'documentViewWrapper') { currentDocViewTab = initialTab || 'All'; // Set the tab for document view renderDocumentViewTabs(); // Render the tabs within this view renderDocumentList(); // Render the list based on the tab } else if (viewId === 'flowsViewWrapper') { renderFlowsList(); // Optionally display a default flow or keep placeholder mermaidFlowGraphContainer.innerHTML = ''; flowPlaceholder.style.display = 'block'; currentSelectedFlowId = null; } else { // Home view currentDocViewTab = 'All'; // Reset doc view tab when going home } } else { console.error(`Target view section not found: ${viewId}. Defaulting to home.`); homeSection.classList.remove('hidden-container'); currentVisibleView = 'home'; } updateBreadcrumb(); // Update breadcrumb based on the current view clearSelection(); // Clear specific doc selection when switching main views } // Function to update breadcrumbs function updateBreadcrumb() { breadcrumbNav.innerHTML = ''; // Clear existing const homeLink = `Home`; if (currentVisibleView === 'home') { breadcrumbNav.innerHTML = `Home`; } else if (currentVisibleView === 'documentViewWrapper') { breadcrumbNav.innerHTML = `${homeLink} / Document Catalog (${currentDocViewTab})`; } else if (currentVisibleView === 'flowsViewWrapper') { breadcrumbNav.innerHTML = `${homeLink} / Process Visualization`; } } // Function to render tabs ONLY within the Document View section function renderDocumentViewTabs() { const phaseMap = { 'Discovery': 'Discovery', 'Preclinical': 'Preclinical', 'Clinical Phase 1': 'Clinical Development', 'Clinical Phase 2': 'Clinical Development', 'Clinical Phase 3': 'Clinical Development', 'Clinical (All Phases)': 'Clinical Development', 'Regulatory Submission': 'Regulatory Submission', 'Regulatory Submission Review Phase': 'Regulatory Submission', 'Post-Marketing': 'Post-Marketing & Quality', 'All Phases': 'Post-Marketing & Quality', 'Discovery, Preclinical': 'Discovery', 'Preclinical, Clinical': 'Preclinical', 'Preclinical (End), Clinical Phase 1': 'Preclinical', 'Discovery (late), Preclinical, Clinical': 'Discovery', 'Pre/Post-Approval':'Regulatory Submission', 'Clinical (Annual)': 'Clinical Development', 'Preclinical / Clinical':'Preclinical', 'Clinical (Early Phase 2/End of Phase 2)': 'Clinical Development' }; const uniquePhases = [...new Set(documentsData.map(doc => phaseMap[doc.Phase] || 'Other'))]; const tabOrder = ['All', 'Discovery', 'Preclinical', 'Clinical Development', 'Regulatory Submission', 'Post-Marketing & Quality', 'Other']; // No 'Flows' here const sortedTabs = tabOrder.filter(tab => uniquePhases.includes(tab) || tab === 'All'); uniquePhases.forEach(phase => { if (!sortedTabs.includes(phase)) sortedTabs.push(phase); }); let tabsHtml = ''; sortedTabs.forEach(tabName => { const isActive = tabName === currentDocViewTab; // Use currentDocViewTab state tabsHtml += ` `; }); mainTabsDocViewContainer.innerHTML = tabsHtml; // Add event listeners to THESE tabs mainTabsDocViewContainer.querySelectorAll('.doc-view-tab').forEach(tab => { tab.addEventListener('click', () => { currentDocViewTab = tab.dataset.tabName; // Update the doc view tab state renderDocumentViewTabs(); // Re-render tabs for active style renderDocumentList(); // Re-render list for the new tab updateBreadcrumb(); // Update breadcrumb text clearSelection(); // Clear specific doc selection }); }); } // Function to render the document list based on the ACTIVE DOC VIEW TAB and search function renderDocumentList() { // This function should only render if documentViewWrapper is the current view if (currentVisibleView !== 'documentViewWrapper') return; const phaseMap = { 'Discovery': 'Discovery', 'Preclinical': 'Preclinical', 'Clinical Phase 1': 'Clinical Development', 'Clinical Phase 2': 'Clinical Development', 'Clinical Phase 3': 'Clinical Development', 'Clinical (All Phases)': 'Clinical Development', 'Regulatory Submission': 'Regulatory Submission', 'Regulatory Submission Review Phase': 'Regulatory Submission', 'Post-Marketing': 'Post-Marketing & Quality', 'All Phases': 'Post-Marketing & Quality', 'Discovery, Preclinical': 'Discovery', 'Preclinical, Clinical': 'Preclinical', 'Preclinical (End), Clinical Phase 1': 'Preclinical', 'Discovery (late), Preclinical, Clinical': 'Discovery', 'Pre/Post-Approval':'Regulatory Submission', 'Clinical (Annual)': 'Clinical Development', 'Preclinical / Clinical':'Preclinical', 'Clinical (Early Phase 2/End of Phase 2)': 'Clinical Development' }; const searchTerm = searchInputDocView.value.toLowerCase(); // Use the correct search input let filteredDocs = documentsData; // Apply phase filter based on currentDocViewTab if (currentDocViewTab !== 'All') { filteredDocs = filteredDocs.filter(doc => { const primaryPhase = phaseMap[doc.Phase] || 'Other'; return primaryPhase === currentDocViewTab; }); } // Apply search filter if (searchTerm) { filteredDocs = filteredDocs.filter(doc => doc.Document_Name.toLowerCase().includes(searchTerm) || doc.Doc_ID_Type.toLowerCase().includes(searchTerm) || (doc.Sub_Phase_Discipline && doc.Sub_Phase_Discipline.toLowerCase().includes(searchTerm)) || (doc.Purpose_Key_Content && doc.Purpose_Key_Content.toLowerCase().includes(searchTerm)) || (doc["Authoring_Department(s)"] && doc["Authoring_Department(s)"].toLowerCase().includes(searchTerm)) || (doc.Key_Metadata && doc.Key_Metadata.toLowerCase().includes(searchTerm)) ); } // Render logic with enhanced styling let listHtml = ''; if (filteredDocs.length === 0) { listHtml = `

No documents found ${searchTerm ? 'matching search in' : 'for'} ${currentDocViewTab === 'All' ? 'any phase' : currentDocViewTab}.

`; } else { const sortedDocs = filteredDocs.sort((a, b) => a.Document_Name.localeCompare(b.Document_Name)); listHtml = ''; } if(documentListDocViewContainer) { documentListDocViewContainer.innerHTML = listHtml; } else { console.error("documentListDocViewContainer element not found!"); return; } // Add event listeners for items in THIS list document.querySelectorAll('#documentListDocView li.doc-list-item').forEach(item => { item.addEventListener('click', () => { currentSelectedDocId = item.dataset.docId; displayDetailsInModal(currentSelectedDocId); renderDocumentList(); // Re-render list for selection highlight }); }); } // findNextPrevDocs uses the correct container based on current view function findNextPrevDocs(currentId) { const listItems = documentListDocViewContainer.querySelectorAll('li[data-doc-id]'); // Always use DocView list const docIds = Array.from(listItems).map(li => li.dataset.docId); const currentIndex = docIds.indexOf(currentId); if (currentIndex === -1 || docIds.length <= 1) { return { prev: null, next: null }; } const prevIndex = currentIndex > 0 ? currentIndex - 1 : docIds.length - 1; const nextIndex = currentIndex < docIds.length - 1 ? currentIndex + 1 : 0; return { prev: docIds[prevIndex], next: docIds[nextIndex] }; } // Enhanced displayDetailsInModal with tabs for different views async function displayDetailsInModal(docId) { const doc = documentsData.find(d => d.Doc_ID_Type === docId); if (!doc) return; currentSelectedDocId = docId; detailsModalTitle.textContent = `${doc.Document_Name} (${doc.Doc_ID_Type})`; // Create tabs for different views const tabsHtml = `
Information
Dependencies
Templates
`; // Create content sections const infoHtml = `
Phase: ${doc.Phase || 'N/A'}
Discipline: ${doc.Sub_Phase_Discipline || 'N/A'}
Authoring Department(s): ${doc['Authoring_Department(s)'] || 'N/A'}
Review/Approval Dept(s): ${doc['Review_Approval_Dept(s)'] || 'N/A'}
Complexity: ${getComplexityIcon(doc.Complexity_Authoring)} ${doc.Complexity_Authoring || 'N/A'}
Regulatory Significance: ${getRegulatoryIcon(doc.Regulatory_Significance)} ${doc.Regulatory_Significance || 'N/A'}
Purpose / Key Content:
${doc.Purpose_Key_Content || 'N/A'}
Key Metadata:
${doc.Key_Metadata || 'N/A'}
Input Docs/Data:
${linkDocumentIDsForDetails(doc.Input_Documents_Data_Sources) || 'N/A'}
Output/Informs Docs:
${linkDocumentIDsForDetails(doc.Output_Informs_Documents) || 'N/A'}
`; const dependenciesHtml = `
`; // Get templates related to this document type const relatedTemplates = templateData.filter(tpl => tpl.document_type === doc.Doc_ID_Type); let templatesHtml = `
`; if (relatedTemplates.length > 0) { templatesHtml += `
`; relatedTemplates.forEach(tpl => { templatesHtml += `

${tpl.name}

${tpl.document_type}

${tpl.description}

Sections:

${tpl.sections.slice(0, 4).map(section => `
${section.title}
${section.description}
`).join('')} ${tpl.sections.length > 4 ? `
+ ${tpl.sections.length - 4} more sections
` : ''}
`; }); templatesHtml += `
`; } else { templatesHtml += `

No templates available for this document type.

`; } templatesHtml += `
`; // Combine all content detailsContentInModal.innerHTML = tabsHtml + infoHtml + dependenciesHtml + templatesHtml; // Add tab switching functionality detailsContentInModal.querySelectorAll('.details-tab').forEach(tab => { tab.addEventListener('click', () => { // Update active tab detailsContentInModal.querySelectorAll('.details-tab').forEach(t => t.classList.remove('active')); tab.classList.add('active'); // Show corresponding content const tabId = tab.dataset.tab; detailsContentInModal.querySelectorAll('.details-content').forEach(c => c.classList.remove('active')); document.getElementById(`tab-content-${tabId}`).classList.add('active'); // If dependencies tab, render the graph if (tabId === 'dependencies') { renderDependencyGraph(docId); } }); }); // Add event listeners to document links within the modal detailsContentInModal.querySelectorAll('.doc-link').forEach(link => { link.addEventListener('click', (e) => { displayDetailsInModal(e.target.dataset.docId); // Optionally update the main list highlight if visible if (currentVisibleView === 'documentViewWrapper') { renderDocumentList(); } }); }); // Setup Next/Prev Buttons currentDocListIndices = findNextPrevDocs(docId); prevDocBtn.disabled = !currentDocListIndices.prev; nextDocBtn.disabled = !currentDocListIndices.next; // Show Modal detailsModal.style.display = 'flex'; // Only re-render list if doc view is active if (currentVisibleView === 'documentViewWrapper') { renderDocumentList(); } } // New function to render dependency graph using Mermaid async function renderDependencyGraph(docId) { const doc = documentsData.find(d => d.Doc_ID_Type === docId); if (!doc) return; const container = document.getElementById('document-graph-container'); if (!container) return; // Show loading spinner container.innerHTML = '
'; const inputIDs = extractDocIDs(doc.Input_Documents_Data_Sources); const outputIDs = extractDocIDs(doc.Output_Informs_Documents); let mermaidDefinition = 'graph TD;\n'; const centerNodeName = getDocNameById(doc.Doc_ID_Type); // Define center node with improved styling mermaidDefinition += ` ${doc.Doc_ID_Type}("${centerNodeName}\\n(${doc.Doc_ID_Type})"):::focus;\n`; // Define input nodes and connections inputIDs.forEach(inputId => { const inputNodeName = getDocNameById(inputId); mermaidDefinition += ` ${inputId}("${inputNodeName}\\n(${inputId})"):::input --> ${doc.Doc_ID_Type};\n`; }); // Define output nodes and connections outputIDs.forEach(outputId => { const outputNodeName = getDocNameById(outputId); mermaidDefinition += ` ${doc.Doc_ID_Type} --> ${outputId}("${outputNodeName}\\n(${outputId})"):::output;\n`; }); // Add class definitions for better styling mermaidDefinition += ` classDef focus fill:#e0f2fe,stroke:#38bdf8,stroke-width:2px,color:#075985;\n`; mermaidDefinition += ` classDef input fill:#f1f5f9,stroke:#94a3b8,color:#334155;\n`; mermaidDefinition += ` classDef output fill:#f1f5f9,stroke:#94a3b8,color:#334155;\n`; // Add click handlers for all nodes [doc.Doc_ID_Type, ...inputIDs, ...outputIDs].forEach(id => { mermaidDefinition += ` click ${id} call displayDetailsAndGraphFromModal("${id}") "View Details";\n`; }); try { const graphId = `mermaid-modal-graph-${docId}-${Date.now()}`; const { svg } = await mermaid.render(graphId, mermaidDefinition); container.innerHTML = svg; // Make the SVG responsive const svgElement = container.querySelector('svg'); if (svgElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); svgElement.style.maxHeight = '400px'; } } catch (error) { console.error("Mermaid rendering error:", error); container.innerHTML = `

Failed to render dependency graph.

`; } } // Callbacks from Mermaid graphs window.displayDetailsAndGraphFromGraph = async (docId) => { console.log("Graph node clicked (main flow or example):", docId); await displayDetailsInModal(docId); // Always show in modal setTimeout(() => { // If the doc list view is active, scroll the item into view if (currentVisibleView === 'documentViewWrapper') { const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`); listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }, 100); }; window.displayDetailsAndGraphFromModal = async (docId) => { console.log("Modal graph node clicked:", docId); await displayDetailsInModal(docId); // Update current modal setTimeout(() => { if (currentVisibleView === 'documentViewWrapper') { const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`); listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }, 100); }; function clearSelection() { currentSelectedDocId = null; if (currentVisibleView === 'documentViewWrapper') { renderDocumentList(); // Update list highlight } } // Enhance flow list rendering with better UI function renderFlowsList() { const flowDisplayTitles = { "p1_sad": "Phase 1 SAD Study Documents", "nda_submission": "NDA/MAA Submission Process", "ind_pathway": "IND Pathway Documents", "clinical_program": "Clinical Program Development" }; let flowsHtml = `

Document Workflows

Select a flow to visualize document relationships and dependencies in typical R&D processes.

`; Object.keys(flowDefinitions).forEach(id => { const title = flowDisplayTitles[id] || `Flow ${id}`; const isSelected = id === currentSelectedFlowId; flowsHtml += `
${title}

${id === 'p1_sad' ? 'Documents required for First-in-Human studies' : id === 'nda_submission' ? 'Regulatory submission package assembly' : id === 'ind_pathway' ? 'Discovery to IND enabling documents' : id === 'clinical_program' ? 'Clinical phase documentation flow' : 'Document workflow visualization'}

`; }); flowsListContainer.innerHTML = flowsHtml; // Add event listeners flowsListContainer.querySelectorAll('.flow-card').forEach(card => { card.addEventListener('click', () => { const flowId = card.dataset.flowId; currentSelectedFlowId = flowId; displayFlowGraph(flowId); renderFlowsList(); // Update active state }); }); } // Enhanced flow graph display async function displayFlowGraph(flowId) { const definition = flowDefinitions[flowId]; if (!definition) { mermaidFlowGraphContainer.innerHTML = `

Flow definition not found.

`; flowPlaceholder.style.display = 'none'; return; } // Show loading indicator mermaidFlowGraphContainer.innerHTML = `

Rendering flow graph...

`; flowPlaceholder.style.display = 'none'; try { if (flowsViewWrapper.classList.contains('hidden-container')) return; const clickableDefinition = definition.replace(/click ([A-Z0-9_\-]+) call displayDetailsAndGraphFromGraph/g,'click $1 call displayDetailsAndGraphFromGraph'); const graphId = `mermaid-flow-${flowId}-${Date.now()}`; const { svg } = await mermaid.render(graphId, clickableDefinition); mermaidFlowGraphContainer.innerHTML = svg; // Make the SVG responsive const svgElement = mermaidFlowGraphContainer.querySelector('svg'); if (svgElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); svgElement.style.maxHeight = '700px'; // Taller to accommodate complex flows } // Add title and description based on flow ID const flowDisplayTitles = { "p1_sad": "Phase 1 SAD Study Documents", "nda_submission": "NDA/MAA Submission Process", "ind_pathway": "IND Pathway Documents", "clinical_program": "Clinical Program Development" }; const flowDescriptions = { "p1_sad": "This diagram shows the key documents needed for a Phase 1 Single Ascending Dose study, from preclinical inputs through to clinical execution and reporting.", "nda_submission": "The NDA/MAA submission process flow showing how various documents and data packages are assembled into a regulatory submission.", "ind_pathway": "Documents required from Discovery through Preclinical development to enable an IND/CTA submission.", "clinical_program": "The integrated flow of clinical documentation across Phases 1-3 leading to regulatory submission." }; const title = flowDisplayTitles[flowId] || `Flow ${flowId}`; const description = flowDescriptions[flowId] || "Document workflow visualization"; // Add title and description above the graph const titleContainer = document.createElement('div'); titleContainer.className = 'mb-4'; titleContainer.innerHTML = `

${title}

${description}

`; mermaidFlowGraphContainer.insertBefore(titleContainer, mermaidFlowGraphContainer.firstChild); } catch (error) { console.error(`Mermaid rendering error for flow ${flowId}:`, error); mermaidFlowGraphContainer.innerHTML = `

Error rendering flow graph.

${error.message}
`; } } async function showExampleFlow() { const exampleDefinition = flowDefinitions['p1_sad']; try { // Show loading indicator exampleMermaidGraphContainer.innerHTML = `

Rendering example flow...

`; const clickableDefinition = exampleDefinition.replace(/click ([A-Z0-9_\-]+) call displayDetailsAndGraphFromGraph/g, 'click $1 call displayDetailsAndGraphFromModal'); const graphId = `example-mermaid-graph-render-${Date.now()}`; const { svg } = await mermaid.render(graphId, clickableDefinition); exampleMermaidGraphContainer.innerHTML = svg; // Add title and description const titleContainer = document.createElement('div'); titleContainer.className = 'mb-4'; titleContainer.innerHTML = `

Phase 1 SAD Study Documents

This diagram shows the key documents needed for a Phase 1 Single Ascending Dose study, from preclinical inputs through to clinical execution and reporting.

`; exampleMermaidGraphContainer.insertBefore(titleContainer, exampleMermaidGraphContainer.firstChild); // Make the SVG responsive const svgElement = exampleMermaidGraphContainer.querySelector('svg'); if (svgElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); } exampleFlowModal.style.display = "flex"; } catch (error) { console.error("Mermaid rendering error for example:", error); exampleMermaidGraphContainer.innerHTML = `

Error rendering example flow graph.

`; exampleFlowModal.style.display = "flex"; } } // --- Global Search Functionality --- // Add global search functionality function performGlobalSearch(searchTerm) { if (!searchTerm) return; searchTerm = searchTerm.toLowerCase(); let results = documentsData.filter(doc => doc.Document_Name.toLowerCase().includes(searchTerm) || doc.Doc_ID_Type.toLowerCase().includes(searchTerm) || (doc.Purpose_Key_Content && doc.Purpose_Key_Content.toLowerCase().includes(searchTerm)) ); // Switch to document view with search results switchToView('documentViewWrapper', 'All'); // Set the search input in document view to match the global search searchInputDocView.value = searchTerm; // Render the filtered list renderDocumentList(); } // --- Event Listeners --- // Search input specific to document view searchInputDocView?.addEventListener('input', renderDocumentList); // Global header search headerSearchInput?.addEventListener('keypress', (e) => { if (e.key === 'Enter') { performGlobalSearch(e.target.value); } }); // Home button listener homeButton?.addEventListener('click', () => switchToView('home')); // Breadcrumb listener (delegated) breadcrumbNav?.addEventListener('click', (e) => { if (e.target.tagName === 'A' && e.target.dataset.viewTarget) { e.preventDefault(); switchToView(e.target.dataset.viewTarget); } }); // Dashboard card listeners (delegated to main content area) mainContentArea?.addEventListener('click', (e) => { const card = e.target.closest('.dashboard-card[data-target-view]'); if (card) { const targetView = card.dataset.targetView; const initialTab = card.dataset.initialTab; // Get initial tab if specified if (targetView) { switchToView(targetView, initialTab); } } }); // Example Flow Buttons (Header and Flow View) showExampleFlowBtnHeader?.addEventListener('click', showExampleFlow); showExampleFlowBtnFlowView?.addEventListener('click', showExampleFlow); // Modal Close Listeners closeExampleModalBtn?.addEventListener('click', () => exampleFlowModal.style.display = "none"); window.addEventListener('click', (event) => { if (event.target == exampleFlowModal) exampleFlowModal.style.display = "none"; }); closeDetailsModalBtn?.addEventListener('click', () => { detailsModal.style.display = "none"; clearSelection(); }); window.addEventListener('click', (event) => { if (event.target == detailsModal) { detailsModal.style.display = "none"; clearSelection(); } }); // Modal Next/Prev Button Listeners prevDocBtn?.addEventListener('click', () => { if (currentDocListIndices.prev) displayDetailsInModal(currentDocListIndices.prev); }); nextDocBtn?.addEventListener('click', () => { if (currentDocListIndices.next) displayDetailsInModal(currentDocListIndices.next); }); // --- Initialization --- document.addEventListener('DOMContentLoaded', async () => { console.log("DOM Loaded. Fetching data..."); mainContentArea.innerHTML += '

Loading Data...

'; // Add loading spinner try { // Load document data const docsResponse = await fetch('documents.json'); if (!docsResponse.ok) { throw new Error(`HTTP error! status: ${docsResponse.status}`); } documentsData = await docsResponse.json(); console.log(`Successfully loaded ${documentsData.length} documents from documents.json`); // Load template data try { const templatesResponse = await fetch('document_templates.json'); if (templatesResponse.ok) { templateData = await templatesResponse.json(); console.log(`Successfully loaded ${templateData.length} templates from document_templates.json`); } else { console.warn("Templates file not found. Document templates will not be available."); templateData = []; } } catch (templateError) { console.warn("Error loading templates:", templateError); templateData = []; } // Remove spinner and initialize UI document.getElementById('loadingSpinner')?.remove(); switchToView('home'); // Start on the 'Home' view } catch (error) { console.error("Failed to load documents.json:", error); document.getElementById('loadingSpinner')?.remove(); // Display error message more prominently mainContentArea.innerHTML = ``; } });