// R&D DocMap Catalog - Enhanced JavaScript Functionality // Initialize Mermaid mermaid.initialize({ startOnLoad: false, theme: 'base', securityLevel: 'loose', themeVariables: { primaryColor: '#eff6ff', primaryTextColor: '#1e3a8a', primaryBorderColor: '#60a5fa', lineColor: '#6b7280', secondaryColor: '#f1f5f9', tertiaryColor: '#e0f2fe' } }); // --- Global Variables --- let documentsData = []; // Main document catalog data let lineageData = []; // Section level lineage data let templateData = []; // Document template data if available let sectionMappingData = []; // Document section mapping data for lineage // Flow definitions for document process visualization const flowDefinitions = { "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 dataLineageViewWrapper = document.getElementById('dataLineageViewWrapper'); const uberDepViewWrapper = document.getElementById('uberDepViewWrapper'); 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'); // Data Lineage Elements const lineageDocumentSelect = document.getElementById('lineageDocumentSelect'); const lineageSectionSelect = document.getElementById('lineageSectionSelect'); const mermaidLineageGraph = document.getElementById('mermaidLineageGraph'); const lineagePlaceholder = document.getElementById('lineagePlaceholder'); // Uber Dependency Elements const uberDepDocTypeSelect = document.getElementById('uberDepDocTypeSelect'); const uberDepPhaseSelect = document.getElementById('uberDepPhaseSelect'); const mermaidUberDepGraph = document.getElementById('mermaidUberDepGraph'); const uberDepPlaceholder = document.getElementById('uberDepPlaceholder'); const homeButton = document.getElementById('homeButton'); const breadcrumbNav = document.getElementById('breadcrumbNav'); // Modals const showExampleFlowBtnHeader = document.getElementById('showExampleFlowBtn'); 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 closeDetailsModalBtn = document.getElementById('closeDetailsModalBtn'); const prevDocBtn = document.getElementById('prevDocBtn'); const nextDocBtn = document.getElementById('nextDocBtn'); const loadingSpinner = document.getElementById('loadingSpinner'); // --- State Variables --- let currentVisibleView = 'home'; let currentDocViewTab = 'All'; let currentSelectedDocId = null; let currentSelectedFlowId = null; let currentDocListIndices = { prev: null, next: null }; let currentLineageDocId = null; let currentLineageSectionId = 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) || []; 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 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'); dataLineageViewWrapper.classList.add('hidden-container'); uberDepViewWrapper.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'; renderDocumentViewTabs(); renderDocumentList(); } else if (viewId === 'flowsViewWrapper') { renderFlowsList(); mermaidFlowGraphContainer.innerHTML = ''; flowPlaceholder.style.display = 'block'; currentSelectedFlowId = null; } else if (viewId === 'dataLineageViewWrapper') { renderDataLineageSelectors(); mermaidLineageGraph.innerHTML = ''; lineagePlaceholder.style.display = 'block'; } else if (viewId === 'uberDepViewWrapper') { renderUberDepFilters(); renderUberDependencyGraph(); } else { // Home view currentDocViewTab = 'All'; } } else { console.error(`Target view section not found: ${viewId}. Defaulting to home.`); homeSection.classList.remove('hidden-container'); currentVisibleView = 'home'; } updateBreadcrumb(); clearSelection(); } function updateBreadcrumb() { breadcrumbNav.innerHTML = ''; 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`; } else if (currentVisibleView === 'dataLineageViewWrapper') { breadcrumbNav.innerHTML = `${homeLink} / Section-Level Lineage`; } else if (currentVisibleView === 'uberDepViewWrapper') { breadcrumbNav.innerHTML = `${homeLink} / DocGen Dependencies`; } } // --- Document View Functions --- 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']; 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; tabsHtml += ` `; }); mainTabsDocViewContainer.innerHTML = tabsHtml; // Add event listeners to THESE tabs mainTabsDocViewContainer.querySelectorAll('.doc-view-tab').forEach(tab => { tab.addEventListener('click', () => { currentDocViewTab = tab.dataset.tabName; renderDocumentViewTabs(); renderDocumentList(); updateBreadcrumb(); clearSelection(); }); }); } function renderDocumentList() { 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(); 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(); }); }); } function findNextPrevDocs(currentId) { const listItems = documentListDocViewContainer.querySelectorAll('li[data-doc-id]'); 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 document details display with modern, clean card design 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
Sections
`; // Create content sections with enhanced styling const infoHtml = `

Document Overview

${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'}

Content & Metadata

Purpose / Key Content:
${doc.Purpose_Key_Content || 'N/A'}
Key Metadata:
${doc.Key_Metadata || 'N/A'}

Dependencies

Input Docs/Data:
${linkDocumentIDsForDetails(doc.Input_Documents_Data_Sources) || 'N/A'}
Output/Informs Docs:
${linkDocumentIDsForDetails(doc.Output_Informs_Documents) || 'N/A'}
`; const dependenciesHtml = `
`; // Section listing tab - for documents with section lineage data const relatedSections = sectionMappingData.filter(section => section.Document_Name === doc.Document_Name || section['Input Document (s)']?.includes(doc.Document_Name) ); let sectionsHtml = `
`; if (relatedSections.length > 0) { sectionsHtml += `

Document Sections

`; relatedSections.forEach(section => { sectionsHtml += `
${section['Output Section Name']}
${section['Output Sub-section Name'] || ''}
Input: ${section['Input Document (s)'] || 'N/A'}
`; }); sectionsHtml += `
`; } else { sectionsHtml += `

No section-level mapping data available for this document.

`; } sectionsHtml += `
`; // Combine all content detailsContentInModal.innerHTML = tabsHtml + infoHtml + dependenciesHtml + sectionsHtml; // 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(); } } // 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.

`; } } // --- Flow Visualization Functions --- 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 }); }); } 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"; } } // --- NEW: Data Lineage Functions --- function renderDataLineageSelectors() { if (!lineageDocumentSelect) return; // Clear previous options lineageDocumentSelect.innerHTML = ''; lineageSectionSelect.innerHTML = ''; lineageSectionSelect.disabled = true; // Get unique document names from section mapping data const uniqueDocNames = [...new Set(sectionMappingData.map(section => section.Document_Name))]; // Add options to document select uniqueDocNames.sort().forEach(docName => { lineageDocumentSelect.innerHTML += ``; }); // Add event listener to document select lineageDocumentSelect.addEventListener('change', function() { const selectedDoc = this.value; if (selectedDoc) { currentLineageDocId = selectedDoc; lineageSectionSelect.disabled = false; // Filter sections for the selected document const docSections = sectionMappingData.filter(section => section.Document_Name === selectedDoc); // Clear and populate section select lineageSectionSelect.innerHTML = ''; // Get unique section names (avoiding duplicates) const uniqueSections = [...new Set(docSections.map(section => section['Output Section Name']))]; uniqueSections.forEach(sectionName => { lineageSectionSelect.innerHTML += ``; }); } else { lineageSectionSelect.disabled = true; lineageSectionSelect.innerHTML = ''; currentLineageDocId = null; lineagePlaceholder.style.display = 'block'; mermaidLineageGraph.innerHTML = ''; } }); // Add event listener to section select lineageSectionSelect.addEventListener('change', function() { const selectedSection = this.value; if (selectedSection && currentLineageDocId) { currentLineageSectionId = selectedSection; renderSectionLineageGraph(currentLineageDocId, selectedSection); } else { currentLineageSectionId = null; lineagePlaceholder.style.display = 'block'; mermaidLineageGraph.innerHTML = ''; } }); } // Function to select a section for lineage visualization (from document details modal) function selectSectionForLineage(docName, sectionName) { // Switch to lineage view switchToView('dataLineageViewWrapper'); // Set the selectors if (lineageDocumentSelect) { lineageDocumentSelect.value = docName; // Trigger change event to populate section select const event = new Event('change'); lineageDocumentSelect.dispatchEvent(event); // Set the section selector after a small delay (to ensure it's populated) setTimeout(() => { if (lineageSectionSelect) { lineageSectionSelect.value = sectionName; // Trigger change event to render the graph lineageSectionSelect.dispatchEvent(event); } }, 100); } } // Render section lineage graph async function renderSectionLineageGraph(documentName, sectionName) { if (!documentName || !sectionName) { lineagePlaceholder.style.display = 'block'; mermaidLineageGraph.innerHTML = ''; return; } lineagePlaceholder.style.display = 'none'; mermaidLineageGraph.innerHTML = `

Rendering section lineage...

`; // Filter section data to find the target section and related sections const targetSection = sectionMappingData.find(section => section.Document_Name === documentName && section['Output Section Name'] === sectionName ); if (!targetSection) { mermaidLineageGraph.innerHTML = `

No lineage data found for this section.

`; return; } // Create Mermaid definition for section lineage let mermaidDefinition = 'graph TD;\n'; // Create unique node IDs const targetNodeId = `${sanitizeForMermaid(documentName)}_${sanitizeForMermaid(sectionName)}`; // Create the target section node mermaidDefinition += ` ${targetNodeId}["${documentName}\\n${sectionName}"]:::target;\n`; // Add input documents/sections if available if (targetSection['Input Document (s)']) { const inputSources = targetSection['Input Document (s)'].split(',').map(s => s.trim()); inputSources.forEach((source, idx) => { // Try to find if it's a specific section const sourceSection = source.includes(':') ? source.split(':')[1].trim() : ''; const sourceDoc = source.includes(':') ? source.split(':')[0].trim() : source; const sourceNodeId = `input_${sanitizeForMermaid(sourceDoc)}_${idx}`; if (sourceSection) { mermaidDefinition += ` ${sourceNodeId}["${sourceDoc}\\n${sourceSection}"]:::input --> ${targetNodeId};\n`; } else { mermaidDefinition += ` ${sourceNodeId}["${sourceDoc}"]:::input --> ${targetNodeId};\n`; } }); } // Find sections that use this section as input const outputSections = sectionMappingData.filter(section => { if (!section['Input Document (s)']) return false; // Check if any input source references this document and section const inputSources = section['Input Document (s)'].split(',').map(s => s.trim()); return inputSources.some(source => { // Check for exact section reference if (source.includes(':')) { const [sourceDoc, sourceSection] = source.split(':').map(s => s.trim()); return sourceDoc === documentName && sourceSection === sectionName; } // Check for document reference return source === documentName; }); }); // Add output sections to graph outputSections.forEach((outputSection, idx) => { const outputNodeId = `output_${sanitizeForMermaid(outputSection.Document_Name)}_${idx}`; mermaidDefinition += ` ${targetNodeId} --> ${outputNodeId}["${outputSection.Document_Name}\\n${outputSection['Output Section Name']}"]:::output;\n`; }); // Add styling mermaidDefinition += ` classDef target fill:#e0f2fe,stroke:#38bdf8,stroke-width:2px,color:#075985; classDef input fill:#f1f5f9,stroke:#94a3b8,color:#334155; classDef output fill:#f0fdf4,stroke:#4ade80,color:#15803d; `; try { const graphId = `mermaid-lineage-${Date.now()}`; const { svg } = await mermaid.render(graphId, mermaidDefinition); // Create title container const titleContainer = document.createElement('div'); titleContainer.className = 'mb-4'; titleContainer.innerHTML = `

Section Lineage: ${sectionName}

Document: ${documentName}

${targetSection['Output Sub-section Name'] ? `

Subsection: ${targetSection['Output Sub-section Name']}

` : ''} `; // Clear container and add title + SVG mermaidLineageGraph.innerHTML = ''; mermaidLineageGraph.appendChild(titleContainer); mermaidLineageGraph.innerHTML += svg; // Make SVG responsive const svgElement = mermaidLineageGraph.querySelector('svg'); if (svgElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); svgElement.style.maxHeight = '600px'; } } catch (error) { console.error("Mermaid rendering error for section lineage:", error); mermaidLineageGraph.innerHTML = `

Error rendering section lineage graph.

${error.message}
`; } } // Helper function to sanitize text for Mermaid node IDs function sanitizeForMermaid(text) { return text.replace(/[^a-zA-Z0-9]/g, '_'); } // --- NEW: Uber Dependency View Functions --- function renderUberDepFilters() { if (!uberDepDocTypeSelect || !uberDepPhaseSelect) return; // Clear previous options uberDepDocTypeSelect.innerHTML = ''; uberDepPhaseSelect.innerHTML = ''; // Get unique document types const uniqueDocTypes = [...new Set(documentsData.map(doc => doc.Doc_ID_Type.split('-')[0]))]; // Add options to document type select uniqueDocTypes.sort().forEach(docType => { uberDepDocTypeSelect.innerHTML += ``; }); // Get unique phases const uniquePhases = [...new Set(documentsData.map(doc => doc.Phase))].filter(phase => phase); // Add options to phase select uniquePhases.sort().forEach(phase => { uberDepPhaseSelect.innerHTML += ``; }); // Add event listeners to filters uberDepDocTypeSelect.addEventListener('change', renderUberDependencyGraph); uberDepPhaseSelect.addEventListener('change', renderUberDependencyGraph); } // Function to render uber dependency graph based on selected filters async function renderUberDependencyGraph() { uberDepPlaceholder.style.display = 'none'; mermaidUberDepGraph.innerHTML = `

Rendering document generation dependencies...

`; // Get filter values const selectedDocType = uberDepDocTypeSelect ? uberDepDocTypeSelect.value : 'all'; const selectedPhase = uberDepPhaseSelect ? uberDepPhaseSelect.value : 'all'; // Filter documents based on selected filters let filteredDocs = documentsData; if (selectedDocType !== 'all') { filteredDocs = filteredDocs.filter(doc => doc.Doc_ID_Type.startsWith(selectedDocType)); } if (selectedPhase !== 'all') { filteredDocs = filteredDocs.filter(doc => doc.Phase === selectedPhase); } // Limit to a reasonable number of documents for the graph if (filteredDocs.length > 30) { filteredDocs = filteredDocs.slice(0, 30); } // Create Mermaid definition for uber dependency graph let mermaidDefinition = 'graph TD;\n'; // Track all dependencies to avoid duplicates const processedDeps = new Set(); // Track all doc IDs in the graph const docIdsInGraph = new Set(); // Process each document filteredDocs.forEach(doc => { const docId = doc.Doc_ID_Type; docIdsInGraph.add(docId); // Add the document node with phase-based styling const phaseClass = getPhaseClassForNode(doc.Phase); mermaidDefinition += ` ${docId}["${doc.Document_Name}\\n(${docId})"]:::${phaseClass};\n`; // Process input documents if (doc.Input_Documents_Data_Sources) { const inputIds = extractDocIDs(doc.Input_Documents_Data_Sources); inputIds.forEach(inputId => { if (!processedDeps.has(`${inputId}->${docId}`)) { mermaidDefinition += ` ${inputId} --> ${docId};\n`; processedDeps.add(`${inputId}->${docId}`); docIdsInGraph.add(inputId); } }); } // Process output documents if (doc.Output_Informs_Documents) { const outputIds = extractDocIDs(doc.Output_Informs_Documents); outputIds.forEach(outputId => { if (!processedDeps.has(`${docId}->${outputId}`)) { mermaidDefinition += ` ${docId} --> ${outputId};\n`; processedDeps.add(`${docId}->${outputId}`); docIdsInGraph.add(outputId); } }); } }); // Add styling for different document phases mermaidDefinition += ` 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; classDef postmarketing fill:#fee2e2,stroke:#f87171,color:#991b1b; classDef default fill:#f1f5f9,stroke:#94a3b8,color:#334155; `; // Add click handlers for all nodes docIdsInGraph.forEach(id => { mermaidDefinition += ` click ${id} call displayDetailsFromUberGraph("${id}") "View Details";\n`; }); try { const graphId = `mermaid-uber-dep-${Date.now()}`; const { svg } = await mermaid.render(graphId, mermaidDefinition); // Create title container const titleContainer = document.createElement('div'); titleContainer.className = 'mb-4'; titleContainer.innerHTML = `

Document Generation Dependencies

${selectedDocType !== 'all' ? `Document Type: ${selectedDocType}` : 'All Document Types'} | ${selectedPhase !== 'all' ? `Phase: ${selectedPhase}` : 'All Phases'}

Showing ${docIdsInGraph.size} documents and ${processedDeps.size} dependencies ${filteredDocs.length >= 30 ? ' (limited to 30 documents for readability)' : ''}

`; // Clear container and add title + SVG mermaidUberDepGraph.innerHTML = ''; mermaidUberDepGraph.appendChild(titleContainer); mermaidUberDepGraph.innerHTML += svg; // Make SVG responsive const svgElement = mermaidUberDepGraph.querySelector('svg'); if (svgElement) { svgElement.setAttribute('width', '100%'); svgElement.setAttribute('height', '100%'); svgElement.style.maxHeight = '800px'; } } catch (error) { console.error("Mermaid rendering error for uber dependency graph:", error); mermaidUberDepGraph.innerHTML = `

Error rendering dependency graph.

${error.message}
`; } } // Helper function to get Mermaid class for document phase function getPhaseClassForNode(phase) { if (!phase) return 'default'; const lowerPhase = phase.toLowerCase(); if (lowerPhase.includes('discovery')) return 'discovery'; if (lowerPhase.includes('preclinical')) return 'preclinical'; if (lowerPhase.includes('clinical')) return 'clinical'; if (lowerPhase.includes('regulatory') || lowerPhase.includes('submission')) return 'regulatory'; if (lowerPhase.includes('post-marketing') || lowerPhase.includes('post-approval')) return 'postmarketing'; return 'default'; } // --- Callback Functions for Mermaid Graph Interactions --- window.displayDetailsAndGraphFromGraph = async (docId) => { await displayDetailsInModal(docId); setTimeout(() => { if (currentVisibleView === 'documentViewWrapper') { const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`); listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }, 100); }; window.displayDetailsAndGraphFromModal = async (docId) => { await displayDetailsInModal(docId); setTimeout(() => { if (currentVisibleView === 'documentViewWrapper') { const listItem = document.querySelector(`#documentListDocView li[data-doc-id="${docId}"]`); listItem?.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } }, 100); }; window.displayDetailsFromUberGraph = async (docId) => { await displayDetailsInModal(docId); }; function clearSelection() { currentSelectedDocId = null; if (currentVisibleView === 'documentViewWrapper') { renderDocumentList(); } } // --- 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 --- document.addEventListener('DOMContentLoaded', function() { // 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); }); // Load data and initialize application initializeApp(); }); // --- Initialize Application and Load Data --- async function initializeApp() { try { await Promise.all([ loadDocumentsData(), loadSectionMappingData() ]); // Hide loading spinner loadingSpinner.style.display = 'none'; // Initialize the home view switchToView('home'); } catch (error) { console.error("Failed to initialize application:", error); // Hide spinner and show error message loadingSpinner.style.display = 'none'; // Display error message mainContentArea.innerHTML = ` `; } } // Function to load document data async function loadDocumentsData() { const response = await fetch('documents.json'); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } documentsData = await response.json(); console.log(`Successfully loaded ${documentsData.length} documents from documents.json`); // Process document links processDocumentLinks(); } // Function to process document links to establish connections function processDocumentLinks() { // Create a map to track missing Input/Output fields documentsData.forEach(doc => { if (!doc.Input_Documents_Data_Sources) { doc.Input_Documents_Data_Sources = ''; } if (!doc.Output_Informs_Documents) { doc.Output_Informs_Documents = ''; } }); // Ensure bidirectional links documentsData.forEach(doc => { const docId = doc.Doc_ID_Type; // Process document output links const outputIds = extractDocIDs(doc.Output_Informs_Documents); outputIds.forEach(outputId => { const outputDoc = documentsData.find(d => d.Doc_ID_Type === outputId); if (outputDoc && !outputDoc.Input_Documents_Data_Sources.includes(docId)) { // Add this doc as input to the output doc outputDoc.Input_Documents_Data_Sources += outputDoc.Input_Documents_Data_Sources ? `, ${docId}` : docId; } }); // Process document input links const inputIds = extractDocIDs(doc.Input_Documents_Data_Sources); inputIds.forEach(inputId => { const inputDoc = documentsData.find(d => d.Doc_ID_Type === inputId); if (inputDoc && !inputDoc.Output_Informs_Documents.includes(docId)) { // Add this doc as output to the input doc inputDoc.Output_Informs_Documents += inputDoc.Output_Informs_Documents ? `, ${docId}` : docId; } }); }); } // Function to load section mapping data for lineage view async function loadSectionMappingData() { try { const response = await fetch('section_mapping.json'); if (!response.ok) { console.warn(`Section mapping data not available (status: ${response.status})`); // Create mock data from the pasted CSV-like content for demonstration sectionMappingData = createMockSectionMappingData(); } else { sectionMappingData = await response.json(); } console.log(`Loaded ${sectionMappingData.length} section mappings`); } catch (error) { console.warn("Could not load section mapping data:", error); // Create mock data for demonstration sectionMappingData = createMockSectionMappingData(); } } // Function to create mock section mapping data from the pasted content for demonstration function createMockSectionMappingData() { // This would normally come from section_mapping.json // For now, create some sample data return [ { "Document_Name": "Protocol Early Phase", "Output Section Name": "Title Page", "Output Sub-section Name": "Protocol Number", "Input Document (s)": "Manual input", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Title Page", "Output Sub-section Name": "Date", "Input Document (s)": "Manual input", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Title Page", "Output Sub-section Name": "Compound name", "Input Document (s)": "Concept event PPT", "Input Section(s)": "Title page", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Title Page", "Output Sub-section Name": "1 Protocol Title", "Input Document (s)": "Concept event PPT", "Input Section(s)": "Title page", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Title Page", "Output Sub-section Name": "1 Brief Title", "Input Document (s)": "Concept event PPT", "Input Section(s)": "Title page", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "All Pages", "Output Sub-section Name": "Header : Drug Name", "Input Document (s)": "Concept event PPT", "Input Section(s)": "", "Format": "Client-XXXXXXX" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Section 1: PROTOCOL SUMMARY", "Output Sub-section Name": "1 Protocol Title", "Input Document (s)": "Concept event PPT", "Input Section(s)": "Title page", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Section 1: PROTOCOL SUMMARY", "Output Sub-section Name": "1 Brief Title", "Input Document (s)": "Concept event PPT", "Input Section(s)": "Title page", "Format": "" }, { "Document_Name": "Protocol Early Phase", "Output Section Name": "Section 1: PROTOCOL SUMMARY", "Output Sub-section Name": "1 Rationale", "Input Document (s)": "1. Design concept ppt, 2. Investigator Brochure", "Input Section(s)": "Title page, study background, Introduction", "Format": "summary" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Title of Study", "Output Sub-section Name": "Title Page - full protocol title", "Input Document (s)": "Protocol", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Investigators/Study Centers", "Output Sub-section Name": "", "Input Document (s)": "CTMS", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Study Period", "Output Sub-section Name": "", "Input Document (s)": "CTMS", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Clinical Phase", "Output Sub-section Name": "", "Input Document (s)": "Protocol", "Input Section(s)": "Title or Protocol Study Design Section", "Format": "" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Introduction", "Output Sub-section Name": "", "Input Document (s)": "Protocol", "Input Section(s)": "Introduction,Overall Design", "Format": "" }, { "Document_Name": "Clinical Study Report", "Output Section Name": "Objectives", "Output Sub-section Name": "", "Input Document (s)": "Protocol", "Input Section(s)": "Objectives and Endpoints", "Format": "" }, { "Document_Name": "Pharmacy Manual", "Output Section Name": "Section 0: Title Page", "Output Sub-section Name": "PROTOCOL NUMBER", "Input Document (s)": "Protocol", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Pharmacy Manual", "Output Section Name": "Section 0: Title Page", "Output Sub-section Name": "Protocol Title", "Input Document (s)": "Protocol", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Pharmacy Manual", "Output Section Name": "Section 0: Title Page", "Output Sub-section Name": "Version", "Input Document (s)": "Manual input", "Input Section(s)": "", "Format": "" }, { "Document_Name": "Pharmacy Manual", "Output Section Name": "Section 0: Title Page", "Output Sub-section Name": "Protocol Amendment", "Input Document (s)": "Protocol", "Input Section(s)": "", "Format": "" } ]; }