Spaces:
Running

pdf-upload-wizard / script.js
ekonkati's picture
i wish to develop a full stack webapp based on my prd in pdf file. Help me how to proceed further?
6f0fc6f verified
Raw History Blame Contribute Delete
8.07 kB
document.addEventListener('DOMContentLoaded', function() {
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const previewSection = document.getElementById('previewSection');
const successSection = document.getElementById('successSection');
const uploadBtn = document.getElementById('uploadBtn');
const removeFile = document.getElementById('removeFile');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
// Prevent default drag behaviors
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, preventDefaults, false);
document.body.addEventListener(eventName, preventDefaults, false);
});
// Highlight drop zone when item is dragged over it
['dragenter', 'dragover'].forEach(eventName => {
dropZone.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropZone.addEventListener(eventName, unhighlight, false);
});
// Handle dropped files
dropZone.addEventListener('drop', handleDrop, false);
// Handle file selection via button
fileInput.addEventListener('change', handleFiles);
// Remove file handler
removeFile.addEventListener('click', resetForm);
// Upload button handler
uploadBtn.addEventListener('click', uploadFile);
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
function highlight() {
dropZone.classList.add('highlight');
}
function unhighlight() {
dropZone.classList.remove('highlight');
}
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
handleFiles({ target: { files } });
}
function handleFiles(e) {
const files = e.target.files;
if (files.length) {
const file = files[0];
// Check if file is PDF
if (file.type !== 'application/pdf') {
alert('Please upload a PDF file only.');
return;
}
// Check file size (10MB max)
if (file.size > 10 * 1024 * 1024) {
alert('File size exceeds 10MB limit.');
return;
}
// Display file info
fileName.textContent = file.name;
fileSize.textContent = formatFileSize(file.size);
// Show preview section
previewSection.classList.remove('hidden');
dropZone.classList.add('hidden');
// Set default document name
document.getElementById('documentName').value =
file.name.replace('.pdf', '').replace(/_/g, ' ');
}
}
function resetForm() {
fileInput.value = '';
previewSection.classList.add('hidden');
dropZone.classList.remove('hidden');
}
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
async function uploadFile() {
const file = fileInput.files[0];
const formData = new FormData();
formData.append('pdf', file);
formData.append('name', document.getElementById('documentName').value);
formData.append('description', document.getElementById('description').value);
uploadBtn.disabled = true;
uploadBtn.innerHTML = '<i data-feather="loader" class="animate-spin mr-2"></i> Uploading...';
feather.replace();
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('Upload failed');
}
const data = await response.json();
console.log('Upload successful:', data);
previewSection.classList.add('hidden');
successSection.classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
} catch (error) {
console.error('Upload error:', error);
alert('Upload failed. Please try again.');
uploadBtn.disabled = false;
uploadBtn.innerHTML = '<i data-feather="upload" class="mr-2"></i> Upload PRD';
feather.replace();
}
}
// Load documents for documents.html
if (window.location.pathname.includes('documents.html')) {
loadDocuments();
}
async function loadDocuments() {
try {
const response = await fetch('/api/documents');
if (!response.ok) throw new Error('Failed to load documents');
const documents = await response.json();
renderDocuments(documents);
} catch (error) {
console.error('Error loading documents:', error);
}
}
function renderDocuments(documents) {
const container = document.getElementById('documentsList');
if (!container) return;
container.innerHTML = documents.map(doc => `
<div class="grid grid-cols-12 p-4 items-center">
<div class="col-span-5 flex items-center">
<i data-feather="file-text" class="text-red-500 mr-3"></i>
<div>
<p class="font-medium">${doc.name}</p>
<p class="text-sm text-gray-500">${formatFileSize(doc.size)}</p>
</div>
</div>
<div class="col-span-3 text-gray-600">${new Date(doc.uploadDate).toLocaleDateString()}</div>
<div class="col-span-2">
<span class="${getStatusClass(doc.status)}">${doc.status}</span>
</div>
<div class="col-span-2 flex space-x-2">
<button class="text-blue-500 hover:text-blue-700" onclick="viewDocument('${doc.id}')">
<i data-feather="eye"></i>
</button>
<button class="text-gray-500 hover:text-gray-700" onclick="downloadDocument('${doc.id}')">
<i data-feather="download"></i>
</button>
<button class="text-red-500 hover:text-red-700" onclick="deleteDocument('${doc.id}')">
<i data-feather="trash-2"></i>
</button>
</div>
</div>
`).join('');
feather.replace();
}
function getStatusClass(status) {
const classes = {
'uploaded': 'bg-blue-100 text-blue-800',
'processing': 'bg-yellow-100 text-yellow-800',
'processed': 'bg-green-100 text-green-800',
'error': 'bg-red-100 text-red-800'
};
return `${classes[status] || 'bg-gray-100 text-gray-800'} text-xs px-2 py-1 rounded-full`;
}
async function deleteDocument(id) {
if (!confirm('Are you sure you want to delete this document?')) return;
try {
const response = await fetch(`/api/documents/${id}`, {
method: 'DELETE'
});
if (response.ok) {
loadDocuments();
} else {
throw new Error('Delete failed');
}
} catch (error) {
console.error('Delete error:', error);
alert('Failed to delete document');
}
}
function viewDocument(id) {
// Will implement document viewer later
alert('Document viewer will be implemented');
}
function downloadDocument(id) {
// Will implement download later
alert('Download will be implemented');
}
});