// Global state management
const state = {
isLoading: false,
currentPdfUrl: null
};
// Add state management for the current paper
let currentPaperState = {
pdfUrl: null,
title: null
};
// Add state management for search results
let searchState = {
lastResults: null,
lastQuery: null
};
// Add missing sortBy variable
let sortBy = 'relevance'; // Default sort option
// Utility Functions
function getCsrfToken() {
return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
}
function showLoading() {
const overlay = document.getElementById('loadingOverlay');
overlay.classList.remove('hidden');
state.isLoading = true;
}
function hideLoading() {
const overlay = document.getElementById('loadingOverlay');
overlay.classList.add('hidden');
state.isLoading = false;
}
// Search Functionality
async function performSearch() {
const searchQuery = document.getElementById('searchInput').value.trim();
const maxResults = parseInt(document.getElementById('maxResults').value);
if (!searchQuery) {
alert('Please enter a search term');
return;
}
// Show loading overlay
document.getElementById('loadingOverlay').classList.remove('hidden');
try {
const response = await fetch('/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCsrfToken()
},
body: JSON.stringify({
paper_name: searchQuery,
sort_by: sortBy,
max_results: maxResults
})
});
const data = await response.json();
// Save the results to the state
searchState.lastResults = data;
searchState.lastQuery = searchQuery;
// Get results section and clear it
const resultsSection = document.getElementById('resultsSection');
resultsSection.innerHTML = '';
if (!response.ok) {
throw new Error(data.error || 'Search failed');
}
// Show results section
showResults();
if (data.length === 0) {
resultsSection.innerHTML = `
No papers found matching your search.
`;
return;
}
// Create results container
const resultsGrid = document.createElement('div');
resultsGrid.className = 'results-grid';
// Add each paper to the grid using the new function
data.forEach(paper => {
const paperCard = createPaperCard(paper);
resultsGrid.appendChild(paperCard);
});
resultsSection.appendChild(resultsGrid);
} catch (error) {
console.error('Search error:', error);
document.getElementById('resultsSection').innerHTML = `
Failed to search papers: ${error.message}
`;
} finally {
// Hide loading overlay
document.getElementById('loadingOverlay').classList.add('hidden');
}
}
// Helper function to escape HTML and prevent XSS
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Display Functions
function displayResults(results) {
const resultsSection = document.getElementById('resultsSection');
resultsSection.innerHTML = '';
const resultsGrid = document.createElement('div');
resultsGrid.className = 'results-grid';
results.forEach((paper, index) => {
// Create paper card
const paperCard = document.createElement('div');
paperCard.className = 'paper-card';
// Build the card HTML - removed save button
paperCard.innerHTML = `
${paper.published}
${paper.title}
${paper.authors}
${paper.abstract}
`;
// Add the paper card to the grid
resultsGrid.appendChild(paperCard);
// Add click handlers for remaining buttons
const viewPdfButton = paperCard.querySelector('.view-pdf');
viewPdfButton.addEventListener('click', () => window.open(paper.pdf_link, '_blank'));
const arxivButton = paperCard.querySelector('.arxiv');
arxivButton.addEventListener('click', () => window.open(paper.arxiv_link, '_blank'));
const analyzeButton = paperCard.querySelector('.analyze');
analyzeButton.addEventListener('click', () => analyzePaper(paper.pdf_link, paper.title));
});
resultsSection.appendChild(resultsGrid);
}
// Analysis Functions
async function analyzePaper(pdfUrl, paperTitle) {
// Update current paper state
currentPaperState.pdfUrl = pdfUrl;
currentPaperState.title = paperTitle;
// Show loading overlay
showLoading();
try {
const response = await fetch('/perform-rag', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCsrfToken()
},
body: JSON.stringify({
pdf_url: pdfUrl,
paper_title: paperTitle
})
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
// Show results section with enhanced tab styling
const resultsSection = document.getElementById('resultsSection');
resultsSection.innerHTML = `
${paperTitle}
Research Paper Analysis
${marked.parse(data.analysis.executive_summary)}
AI
Hello! I'm here to help you understand this research paper better.
Feel free to ask any questions about the paper's content, methodology,
findings, or implications.
Hello! I'm here to help you understand this research paper better.
Feel free to ask any questions about the paper's content, methodology,
findings, or implications.
`;
}
// Navigation Functions
function showHome() {
hideAllSections();
document.getElementById('homeSection').classList.add('active');
document.getElementById('backButton').style.display = 'none';
}
function showResults() {
hideAllSections();
document.getElementById('resultsSection').classList.add('active');
document.getElementById('currentSection').textContent = 'Search Results';
document.getElementById('backButton').style.display = 'block';
}
function hideAllSections() {
const sections = ['homeSection', 'historySection', 'savedSection', 'resultsSection'];
sections.forEach(section => {
document.getElementById(section).classList.remove('active');
});
}
function goBack() {
showHome();
}
// Load search history
function loadSearchHistory() {
const historyGrid = document.getElementById('searchHistory');
try {
const history = JSON.parse(localStorage.getItem('searchHistory') || '[]');
if (history.length === 0) {
historyGrid.innerHTML = '
`;
} catch (error) {
console.error('Error displaying search history:', error);
}
}
// Add function to handle search again
function searchAgain(term) {
document.getElementById('searchInput').value = term;
handleSearch(term);
}
// Update the search container HTML in your JavaScript
function initializeSearchInterface() {
const searchSection = document.querySelector('.search-section');
if (searchSection) {
searchSection.innerHTML = `
`;
chatMessages.appendChild(thinkingDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
return thinkingDiv;
}
// Add new function to remove thinking message
function removeThinkingMessage(id) {
const thinkingDiv = document.getElementById(id);
if (thinkingDiv) {
thinkingDiv.remove();
}
}
// Function to create consistent paper cards with properly styled buttons
function createPaperCard(paper) {
const paperCard = document.createElement('div');
paperCard.className = 'paper-card';
// Format the paper data with proper HTML structure
paperCard.innerHTML = `