Here's the complete sentiment analysis web application, built according to your specifications. It's a single HTML file containing all HTML, CSS, and JavaScript, along with CDN links for the external libraries.
Key Features Implemented:
- File Upload: Drag & drop and standard file input for
.csv, .xlsx, and .json files.
- File Validation: Checks file type and displays errors for invalid files.
- Processing State: Disables the upload section and shows a loading indicator during analysis.
- File Parsing: Uses PapaParse for CSV, SheetJS for XLSX, and native JavaScript for JSON to extract text. It attempts to flatten all string content from the files.
- Sentiment Analysis: A simplified custom keyword-based sentiment analysis is implemented directly in the browser. (Note: The
sentiment npm package typically requires a Node.js environment or a build step for browser usage. This custom solution provides the core functionality without requiring a complex build setup for a single HTML file).
- Highlighted Display: Analyzed text is rendered on the webpage with colored highlights (green for positive, red for negative, yellow for neutral).
- Sentiment Statistics: Counts for positive, negative, and neutral entries are displayed.
- Download Analysis: Buttons to download the results as an HTML file or a PDF using
html2pdf.js.
- Best Practices: ES6+ syntax, modular functions, error handling with
try/catch, Promises, const/let, Set for allowed types, Object.freeze for constants, and a clean UI.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sentiment Analysis Web App</title>
<!-- Google Fonts - Roboto for modern UI -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
<style>
/* --- CSS Styling --- */
/* Color Variables */
:root {
--primary-color: #4CAF50; /* Green */
--primary-dark: #388E3C; /* Darker Green */
--background-light: #f4f7f6;
--text-color: #333;
--border-color: #ddd;
--error-color: #D32F2F; /* Red */
--positive-color: #4CAF50; /* Green */
--negative-color: #F44336; /* Red */
--neutral-color: #FFEB3B; /* Yellow/Amber */
--neutral-text-color: #333; /* For yellow background, ensures readability */
--shadow-light: 0 4px 8px rgba(0, 0, 0, 0.1);
}
/* Basic Body Styles */
body {
font-family: 'Roboto', sans-serif;
margin: 0;
padding: 20px;
background-color: var(--background-light);
color: var(--text-color);
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
box-sizing: border-box; /* Include padding in element's total width and height */
}
/* Main Container for the Application */
.container {
background-color: #fff;
border-radius: 8px;
box-shadow: var(--shadow-light);
padding: 30px;
width: 100%;
max-width: 900px;
box-sizing: border-box;
margin-bottom: 20px;
}
h1 {
color: var(--primary-dark);
text-align: center;
margin-bottom: 30px;
font-weight: 700;
}
/* Upload Section Styles */
#upload-section {
border: 2px dashed var(--border-color);
border-radius: 8px;
padding: 40px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 20px;
}
#upload-section.drag-over {
border-color: var(--primary-color);
background-color: #e8f5e9; /* Light green background on drag over */
}
#upload-section.disabled {
opacity: 0.6;
pointer-events: none; /* Disable interaction */
cursor: not-allowed;
background-color: #f0f0f0;
}
#upload-section p {
margin: 0;
font-size: 1.1em;
color: #666;
}
#fileInput {
display: none; /* Hide native file input */
}
/* Generic Button Styles */
.button {
display: inline-block;
background-color: var(--primary-color);
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.3s ease, opacity 0.3s ease;
text-decoration: none; /* For download links */
}
.button:hover:not(:disabled) {
background-color: var(--primary-dark);
}
.button:disabled {
background-color: #ccc;
cursor: not-allowed;
opacity: 0.7;
}
/* Error and Loading Indicators */
#error-message {
color: var(--error-color);
margin-top: 10px;
text-align: center;
font-weight: bold;
}
#loading-indicator {
display: none; /* Hidden by default */
text-align: center;
margin-top: 20px;
font-size: 1.1em;
color: #666;
}
/* Results Section Styles */
#results-section {
display: none; /* Hidden by default */
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid var(--border-color);
}
#results-section.active {
display: block; /* Show when active */
}
.stats-container {
display: flex;
justify-content: space-around;
margin-bottom: 20px;
flex-wrap: wrap; /* Allow wrapping on smaller screens */
}
.stat-box {
padding: 15px 25px;
border-radius: 8px;
text-align: center;
min-width: 120px;
margin: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
color: white;
font-weight: bold;
}
.stat-box h3 {
margin: 0 0 5px 0;
font-size: 1.2em;
}
.stat-box p {
margin: 0;
font-size: 1.8em;
}
/* Sentiment Specific Colors for Stats */
.stat-box.positive { background-color: var(--positive-color); }
.stat-box.negative { background-color: var(--negative-color); }
.stat-box.neutral { background-color: var(--neutral-color); color: var(--neutral-text-color); }
/* Highlighted Text Output Area */
#highlighted-text-output {
border: 1px solid var(--border-color);
padding: 20px;
border-radius: 8px;
background-color: #fcfcfc;
max-height: 400px; /* Limit height and enable scrolling */
overflow-y: auto;
line-height: 1.6;
margin-bottom: 20px;
white-space: pre-wrap; /* Preserve whitespace and line breaks */
word-wrap: break-word; /* Allow long words to break */
}
/* Sentiment Specific Highlighting Classes */
.sentiment-positive,
.sentiment-negative,
.sentiment-neutral {
padding: 2px 4px;
border-radius: 3px;
margin: 0 2px; /* Small margin for visual separation */
display: inline; /* Keep text flowing */
}
.sentiment-positive { background-color: var(--positive-color); color: white; }
.sentiment-negative { background-color: var(--negative-color); color: white; }
.sentiment-neutral { background-color: var(--neutral-color); color: var(--neutral-text-color); }
/* Download Buttons Group */
.download-buttons {
text-align: center;
margin-top: 20px;
}
.download-buttons .button {
margin: 0 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>Text Sentiment Analyzer</h1>
<section id="upload-section">
<!-- Hidden file input triggered by custom button/drag-drop -->
<input type="file" id="fileInput" accept=".csv,.xlsx,.json">
<label for="fileInput" class="button">Browse Files</label>
<p>or drag & drop .csv, .xlsx, or .json files here</p>
<div id="error-message"></div>
</section>
<div id="loading-indicator">Processing file... Please wait.</div>
<section id="results-section">
<h2>Sentiment Analysis Results</h2>
<div class="stats-container">
<div class="stat-box positive">
<h3>Positive</h3>
<p id="positive-count">0</p>
</div>
<div class="stat-box negative">
<h3>Negative</h3>
<p id="negative-count">0</p>
</div>
<div class="stat-box neutral">
<h3>Neutral</h3>
<p id="neutral-count">0</p>
</div>
</div>
<h3>Highlighted Text:</h3>
<div id="highlighted-text-output">
<!-- Highlighted text will be rendered here by JavaScript -->
</div>
<div class="download-buttons">
<button id="downloadHtmlButton" class="button">Download as HTML</button>
<button id="downloadPdfButton" class="button">Download as PDF</button>
</div>
</section>
</div>
<!-- --- External Libraries (CDNs) --- -->
<!-- PapaParse for CSV parsing -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.0/papaparse.min.js"></script>
<!-- SheetJS for XLSX parsing -->
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<!-- html2pdf.js for PDF generation -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.9.3/html2pdf.bundle.min.js"></script>
<script>
// --- Core Application Logic ---
// Constants and DOM Element References
const DOM = {
uploadSection: document.getElementById('upload-section'),
fileInput: document.getElementById('fileInput'),
errorMessage: document.getElementById('error-message'),
loadingIndicator: document.getElementById('loading-indicator'),
resultsSection: document.getElementById('results-section'),
positiveCount: document.getElementById('positive-count'),
negativeCount: document.getElementById('negative-count'),
neutralCount: document.getElementById('neutral-count'),
highlightedTextOutput: document.getElementById('highlighted-text-output'),
downloadHtmlButton: document.getElementById('downloadHtmlButton'),
downloadPdfButton: document.getElementById('downloadPdfButton'),
};
// Allowed file MIME types and extensions for validation
const ALLOWED_FILE_TYPES = new Set([
'text/csv',
'application/vnd.ms-excel', // .xls
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
'application/json',
]);
const FILE_EXTENSIONS = new Set([ // Fallback for less reliable MIME types or custom extensions
'.csv',
'.xlsx',
'.json',
'.xls', // Add .xls explicitly for SheetJS
]);
// Mapping sentiment categories to CSS classes for highlighting
// Using Object.freeze for immutability and performance of constants
const SENTIMENT_CLASSES = Object.freeze({
POSITIVE: 'sentiment-positive',
NEGATIVE: 'sentiment-negative',
NEUTRAL: 'sentiment-neutral',
});
// Application State Management
// Encapsulates current processing status and analyzed data
const appState = {
isProcessing: false,
analyzedData: [], // Stores objects like { originalText, sentimentCategory }
};
// --- Utility Functions ---
/**
* Safely extracts the file extension from a given file name.
* @param {string} fileName - The name of the file.
* @returns {string} The file extension (e.g., ".csv", ".json"), or empty string if not found.
*/
const getFileExtension = (fileName) => {
if (!fileName) return '';
const lastDotIndex = fileName.lastIndexOf('.');
return lastDotIndex !== -1 ? fileName.substring(lastDotIndex).toLowerCase() : '';
};
/**
* Toggles the UI's processing state, disabling/enabling elements and showing/hiding indicators.
* @param {boolean} processing - True to enable processing state (disable upload, show loading), false to disable.
*/
const toggleProcessingState = (processing) => {
appState.isProcessing = processing;
DOM.uploadSection.classList.toggle('disabled', processing);
DOM.loadingIndicator.style.display = processing ? 'block' : 'none';
DOM.errorMessage.textContent = ''; // Clear any previous errors when starting a new process
// Show results section only when processing is done and data is ready
DOM.resultsSection.classList.toggle('active', !processing && appState.analyzedData.length > 0);
};
/**
* Displays a user-friendly error message on the UI.
* @param {string} message - The error message to display.
*/
const displayError = (message) => {
DOM.errorMessage.textContent = message;
console.error('Application Error:', message);
};
/**
* Clears all previous analysis results from the UI and application state.
*/
const clearResultsUI = () => {
DOM.positiveCount.textContent = '0';
DOM.negativeCount.textContent = '0';
DOM.neutralCount.textContent = '0';
DOM.highlightedTextOutput.innerHTML = ''; // Clear the displayed text
appState.analyzedData = []; // Clear stored analyzed data
};
// --- File Handling Functions ---
/**
* Validates the uploaded file's type based on its MIME type and extension.
* @param {File} file - The File object to validate.
* @returns {boolean} True if the file type is valid, false otherwise.
*/
const validateFile = (file) => {
const fileExtension = getFileExtension(file.name);
// Check both MIME type (more reliable) and file extension (fallback/common check)
const isValidType = ALLOWED_FILE_TYPES.has(file.type) || FILE_EXTENSIONS.has(fileExtension);
if (!isValidType) {
displayError(`Invalid file type: "${file.name}". Please upload .csv, .xlsx, or .json files.`);
return false;
}
return true;
};
/**
* Reads the content of a file. For XLSX, it reads as ArrayBuffer; for others, as text.
* @param {File} file - The File object to read.
* @returns {Promise<string|ArrayBuffer>} A promise that resolves with the file's content.
*/
const readFileContent = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) => reject(e.target.error);
const fileExtension = getFileExtension(file.name);
// XLSX files need to be read as ArrayBuffer for SheetJS
if (fileExtension === '.xlsx' || fileExtension === '.xls') {
reader.readAsArrayBuffer(file);
} else {
reader.readAsText(file);
}
});
};
/**
* Parses the file content based on its detected type and extracts all string data.
* @param {File} file - The original File object (for extension).
* @param {string|ArrayBuffer} content - The content read from the file.
* @returns {Promise<Array<string>>} A promise resolving to an array of extracted text strings.
*/
const parseFile = async (file, content) => {
const fileExtension = getFileExtension(file.name);
let extractedTexts = [];
try {
if (fileExtension === '.csv') {
// PapaParse for CSV. Header: false to treat all rows as data, skipEmptyLines for cleanliness.
const result = PapaParse.parse(content, { header: false, skipEmptyLines: true });
if (result.errors.length > 0) {
throw new Error(`CSV parsing error: ${result.errors[0].message}`);
}
// Flatten all cell values into a single array and filter out non-string/empty values
extractedTexts = result.data.flat().filter(s => typeof s === 'string' && s.trim() !== '');
} else if (fileExtension === '.xlsx' || fileExtension === '.xls') {
// SheetJS for XLSX. Read as array buffer.
const workbook = XLSX.read(content, { type: 'array' });
// Iterate over all sheets in the workbook
workbook.SheetNames.forEach(sheetName => {
const sheet = workbook.Sheets[sheetName];
// Convert sheet to JSON array-of-arrays (header: 1)
const json = XLSX.utils.sheet_to_json(sheet, { header: 1 });
// Extract all string cell values
json.forEach(row => {
// Ensure row is an array before iterating
if (Array.isArray(row)) {
row.forEach(cell => {
if (typeof cell === 'string' && cell.trim() !== '') {
extractedTexts.push(cell);
}
});
}
});
});
} else if (fileExtension === '.json') {
const data = JSON.parse(content);
// Recursive function to deeply extract all string values from a JSON object/array
const extractStrings = (obj) => {
let strings = [];
if (typeof obj === 'string' && obj.trim() !== '') {
strings.push(obj);
} else if (Array.isArray(obj)) {
obj.forEach(item => strings = strings.concat(extractStrings(item)));
} else if (typeof obj === 'object' && obj !== null) {
// Use Object.entries for robust iteration over own enumerable properties
for (const [key, value] of Object.entries(obj)) {
strings = strings.concat(extractStrings(value));
}
}
return strings;
};
extractedTexts = extractStrings(data);
} else {
throw new Error(`Unsupported file extension for parsing: ${fileExtension}`);
}
if (extractedTexts.length === 0) {
throw new Error("No text data could be extracted from the file. Please ensure it contains readable text.");
}
return extractedTexts;
} catch (error) {
// Log and re-throw a more user-friendly error message
console.error('File parsing detailed error:', error);
throw new Error(`File parsing failed: ${error.message}. Please check file format and content.`);
}
};
// --- Sentiment Analysis Functions ---
/**
* Performs a basic keyword-based sentiment analysis on a given text.
* This is a simplified implementation for a browser-based demo without a build step.
* For production, consider robust NLP libraries (e.g., VADER-sentiment-js)
* or a backend API with advanced models.
* @param {string} text - The text string to analyze.
* @returns {'positive'|'negative'|'neutral'} The determined sentiment category.
*/
const analyzeSentiment = (text) => {
const lowerText = text.toLowerCase();
let score = 0;
// Define lists of common positive and negative keywords
const positiveWords = [
'good', 'great', 'excellent', 'amazing', 'happy', 'love', 'fantastic',
'best', 'wonderful', 'joy', 'positive', 'superb', 'awesome', 'brilliant',
'👍', '😊', '😁', '✨'
];
const negativeWords = [
'bad', 'poor', 'terrible', 'awful', 'sad', 'hate', 'worst',
'disappointing', 'unhappy', 'negative', 'frustrating', 'horrible', 'dreadful',
'👎', '😠', '😡', '😞'
];
// Count occurrences to determine score
positiveWords.forEach(word => {
if (lowerText.includes(word)) {
score++;
}
});
negativeWords.forEach(word => {
if (lowerText.includes(word)) {
score--;
}
});
// Classify based on score
if (score > 0) return 'positive';
if (score < 0) return 'negative';
return 'neutral';
};
/**
* Analyzes an array of text strings for sentiment.
* @param {Array<string>} textArray - An array of strings to analyze.
* @returns {Array<{originalText: string, sentimentCategory: string}>} An array of objects
* containing the original text and its determined sentiment category.
*/
const performSentimentAnalysis = (textArray) => {
// Using map for immutability and clean transformation
return textArray.map(text => ({
originalText: text,
sentimentCategory: analyzeSentiment(text)
}));
};
// --- Results Display Functions ---
/**
* Renders the analyzed text with appropriate sentiment highlighting on the webpage.
* @param {Array<{originalText: string, sentimentCategory: string}>} analyzedData - The data to render.
*/
const renderSentimentResults = (analyzedData) => {
DOM.highlightedTextOutput.innerHTML = ''; // Clear any previous content
const fragment = document.createDocumentFragment(); // Use DocumentFragment for efficient DOM updates
analyzedData.forEach(item => {
const span = document.createElement('span');
// Ensure the category exists in SENTIMENT_CLASSES before accessing
const className = SENTIMENT_CLASSES[item.sentimentCategory?.toUpperCase()] || SENTIMENT_CLASSES.NEUTRAL;
span.classList.add(className);
span.textContent = item.originalText;
// Add a line break after each entry for better readability, or a space if preferred.
// Text content for highlighting needs to be pre-wrapped to preserve breaks within it.
// span.appendChild(document.createTextNode('\n')); // For paragraph-like separation
fragment.appendChild(span);
fragment.appendChild(document.createTextNode(' ')); // Add a space between highlighted phrases
});
DOM.highlightedTextOutput.appendChild(fragment);
};
/**
* Calculates and displays the counts of positive, negative, and neutral sentiments.
* @param {Array<{originalText: string, sentimentCategory: string}>} analyzedData - The data to count.
*/
const displaySentimentStats = (analyzedData) => {
// Use reduce to efficiently count occurrences of each sentiment category
const counts = analyzedData.reduce((acc, item) => {
// Safely increment count, initializing to 0 if category is new
acc[item.sentimentCategory] = (acc[item.sentimentCategory] || 0) + 1;
return acc;
}, { positive: 0, negative: 0, neutral: 0 }); // Initialize with all categories for display consistency
DOM.positiveCount.textContent = counts.positive;
DOM.negativeCount.textContent = counts.negative;
DOM.neutralCount.textContent = counts.neutral;
};
// --- Download Functionality ---
/**
* Initiates the download of the sentiment analysis results in the specified format.
* @param {'html'|'pdf'} format - The desired download format ("html" or "pdf").
*/
const downloadAnalysis = async (format) => {
const resultsContentElement = DOM.highlightedTextOutput; // The element containing the highlighted text
if (format === 'html') {
// Construct a complete HTML document for download
const htmlTemplate = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sentiment Analysis Report</title>
<style>
/* Embed CSS for consistent styling in downloaded HTML */
body { font-family: 'Roboto', sans-serif; margin: 20px; line-height: 1.6; }
h1 { color: #388E3C; text-align: center; }
p { margin-bottom: 5px; }
hr { border: 0; border-top: 1px solid #eee; margin: 20px 0; }
#highlighted-text-output {
border: 1px solid #ddd;
padding: 20px;
border-radius: 8px;
background-color: #fcfcfc;
white-space: pre-wrap; /* Preserve line breaks */
word-wrap: break-word; /* Allow long words to break */
}
.sentiment-positive { background-color: #4CAF50; color: white; padding: 2px 4px; border-radius: 3px; display: inline; margin: 0 2px;}
.sentiment-negative { background-color: #F44336; color: white; padding: 2px 4px; border-radius: 3px; display: inline; margin: 0 2px;}
.sentiment-neutral { background-color: #FFEB3B; color: #333; padding: 2px 4px; border-radius: 3px; display: inline; margin: 0 2px;}
</style>
</head>
<body>
<h1>Sentiment Analysis Report</h1>
<p><strong>Total Positive:</strong> ${DOM.positiveCount.textContent}</p>
<p><strong>Total Negative:</strong> ${DOM.negativeCount.textContent}</p>
<p><strong>Total Neutral:</strong> ${DOM.neutralCount.textContent}</p>
<hr/>
<!-- The actual highlighted content will be inserted here -->
<div id="highlighted-text-output">${resultsContentElement.innerHTML}</div>
</body>
</html>
`;
// Create a Blob from the HTML string and trigger download
const blob = new Blob([htmlTemplate], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'sentiment_analysis_report.html';
document.body.appendChild(a); // Append to body to make it clickable
a.click(); // Programmatically click the link
document.body.removeChild(a); // Clean up
URL.revokeObjectURL(url); // Release the object URL
} else if (format === 'pdf') {
// html2pdf.js requires an element to render
// Create a temporary element to hold content for PDF generation
const pdfContentWrapper = document.createElement('div');
pdfContentWrapper.style.padding = '20px'; // Add some internal padding for PDF margins
pdfContentWrapper.style.fontFamily = 'Roboto, sans-serif'; // Ensure font is consistent
// Construct the content for the PDF, including stats and the highlighted text
pdfContentWrapper.innerHTML = `
<h1 style="color: #388E3C; text-align: center;">Sentiment Analysis Report</h1>
<p><strong>Total Positive:</strong> ${DOM.positiveCount.textContent}</p>
<p><strong>Total Negative:</strong> ${DOM.negativeCount.textContent}</p>
<p><strong>Total Neutral:</strong> ${DOM.neutralCount.textContent}</p>
<hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;"/>
<div style="white-space: pre-wrap; word-wrap: break-word;">${resultsContentElement.innerHTML}</div>
`;
// Temporarily append to DOM to ensure styles are applied correctly by the browser
// before html2pdf processes it. Styles from the main page are usually inherited.
document.body.appendChild(pdfContentWrapper);
// Configure html2pdf and generate PDF
try {
await html2pdf().from(pdfContentWrapper).set({
margin: [10, 10, 10, 10], // Top, Left, Bottom, Right
filename: 'sentiment_analysis_report.pdf',
html2canvas: { scale: 2, logging: false }, // Scale up for better quality, disable logging
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}).save();
} catch (error) {
console.error('PDF generation failed:', error);
displayError('Failed to generate PDF. Please try again.');
} finally {
// Clean up the temporary element regardless of success or failure
document.body.removeChild(pdfContentWrapper);
}
}
};
// --- Main Application Flow ---
/**
* Orchestrates the file processing, sentiment analysis, and display.
* @param {File} file - The File object selected or dropped by the user.
*/
const processFile = async (file) => {
clearResultsUI(); // Clear any previous results from the UI
toggleProcessingState(true); // Disable upload and show loading indicator
try {
// 1. Validate file type
if (!validateFile(file)) {
return; // Stop if validation fails; error already displayed
}
// 2. Read file content
const fileContent = await readFileContent(file);
// 3. Parse file and extract text data
const extractedTexts = await parseFile(file, fileContent);
// 4. Perform sentiment analysis on extracted text
appState.analyzedData = performSentimentAnalysis(extractedTexts);
// 5. Display results on the webpage
renderSentimentResults(appState.analyzedData);
displaySentimentStats(appState.analyzedData);
} catch (error) {
// Catch any errors during the process and display them
displayError(`Analysis failed: ${error.message}`);
clearResultsUI(); // Clear any partially processed data or UI elements
} finally {
// Always disable processing state regardless of success or failure
toggleProcessingState(false); // Enable upload and hide loading indicator
}
};
// --- Event Listeners Setup ---
document.addEventListener('DOMContentLoaded', () => {
// Event listener for standard file input change
DOM.fileInput.addEventListener('change', (event) => {
const file = event.target.files?.[0]; // Use optional chaining for safety
if (file) {
processFile(file);
}
event.target.value = ''; // Clear the input value to allow re-uploading the same file
});
// Event listeners for drag & drop functionality
// Prevent default drag behaviors to allow custom drop handling
DOM.uploadSection.addEventListener('dragover', (event) => {
event.preventDefault();
// Add highlight class if not already processing
if (!appState.isProcessing) {
DOM.uploadSection.classList.add('drag-over');
}
});
DOM.uploadSection.addEventListener('dragleave', (event) => {
event.preventDefault();
DOM.uploadSection.classList.remove('drag-over');
});
// Handle the file drop event
DOM.uploadSection.addEventListener('drop', (event) => {
event.preventDefault();
DOM.uploadSection.classList.remove('drag-over');
// Prevent processing if another file is already being handled
if (appState.isProcessing) {
displayError('Already processing a file. Please wait.');
return;
}
const file = event.dataTransfer.files?.[0]; // Get the dropped file
if (file) {
processFile(file);
}
});
// Event listeners for download buttons
DOM.downloadHtmlButton.addEventListener('click', () => downloadAnalysis('html'));
DOM.downloadPdfButton.addEventListener('click', () => downloadAnalysis('pdf'));
});
</script>
</body>
</html>