Drag and Drop

This commit is contained in:
2025-09-17 18:45:55 +00:00
parent 2115238217
commit 20e41b67a7
10 changed files with 1358 additions and 379 deletions

View File

@@ -1,5 +1,3 @@
/* static/css/style.css */
:root {
/* Core */
--bg-color: #000000;
@@ -449,6 +447,110 @@ button[type="submit"]:disabled {
}
/* --- START: Drag and Drop and Dialog Styles --- */
.drag-overlay {
position: fixed;
inset: 0;
z-index: 9999;
display: none; /* Hidden by default */
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(5px);
}
body.dragging .drag-overlay {
display: flex; /* Shown when body has .dragging class */
}
.drag-overlay-content {
border: 3px dashed var(--primary-color);
border-radius: 12px;
padding: 2rem 4rem;
text-align: center;
background-color: rgba(0, 0, 0, 0.2);
}
.drag-overlay-content p {
margin: 0;
font-size: 1.5rem;
font-weight: 500;
color: var(--primary-color);
}
.dialog-overlay {
position: fixed;
inset: 0;
z-index: 10000;
display: none; /* Hidden by default */
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(5px);
}
.dialog-overlay.visible {
display: flex; /* Show when .visible class is added */
}
.dialog-box {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 1.5rem;
width: 100%;
max-width: 450px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.5);
}
.dialog-box h2 {
margin-top: 0;
font-size: 1.5rem;
}
.dialog-box p {
color: var(--muted-text);
margin-bottom: 1.5rem;
}
.dialog-actions {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem;
margin-bottom: 1rem;
}
.dialog-actions button {
display: block;
width: 100%;
background: transparent;
border: 1px solid var(--border-color);
color: var(--text-color);
padding: 0.65rem 1rem;
font-size: 1rem;
font-weight: 600;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.dialog-actions button:hover {
background: var(--primary-hover);
border-color: var(--primary-hover);
}
.dialog-secondary-action {
background-color: transparent !important;
border: 1px solid var(--border-color) !important;
}
.dialog-secondary-action:hover {
background-color: rgba(255, 255, 255, 0.05) !important;
}
.dialog-cancel {
background: none;
border: none;
color: var(--muted-text);
cursor: pointer;
font-size: 0.9rem;
padding: 0.5rem;
}
.dialog-cancel:hover {
color: var(--text-color);
}
/* --- END: Drag and Drop and Dialog Styles --- */
/* Spinner */
.spinner-small {
border: 3px solid rgba(255,255,255,0.1);
@@ -467,7 +569,6 @@ button[type="submit"]:disabled {
/* Mobile responsive table */
@media (max-width: 768px) {
/* ... (no changes in this section) ... */
.table-wrapper {
border: none;
background-color: transparent;
@@ -513,17 +614,17 @@ button[type="submit"]:disabled {
.cell-value {
min-width: 0;
max-width: 20em;
text-wrap: nowrap;
overflow: scroll;
}
max-width: 20em;
text-wrap: nowrap;
overflow: scroll;
}
#job-table td[data-label="File"],
#job-table td[data-label="Task"] {
overflow: scroll;
text-overflow: ellipsis;
text-wrap: nowrap;
max-width: 100em;
}
#job-table td[data-label="File"],
#job-table td[data-label="Task"] {
overflow: scroll;
text-overflow: ellipsis;
text-wrap: nowrap;
max-width: 100em;
}
}

View File

@@ -1,6 +1,17 @@
// static/js/script.js
document.addEventListener('DOMContentLoaded', () => {
// --- User Locale and Timezone Detection (Corrected Implementation) ---
const USER_LOCALE = navigator.language || 'en-US'; // Fallback to en-US
const USER_TIMEZONE = Intl.DateTimeFormat().resolvedOptions().timeZone;
const DATETIME_FORMAT_OPTIONS = {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
timeZone: USER_TIMEZONE,
};
console.log(`Using locale: ${USER_LOCALE} and timezone: ${USER_TIMEZONE}`);
// --- Element Selectors ---
const jobListBody = document.getElementById('job-list-body');
@@ -11,16 +22,35 @@ document.addEventListener('DOMContentLoaded', () => {
const audioForm = document.getElementById('audio-form');
const audioFileInput = document.getElementById('audio-file-input');
const audioFileName = document.getElementById('audio-file-name');
const modelSizeSelect = document.getElementById('model-size-select');
const conversionForm = document.getElementById('conversion-form');
const conversionFileInput = document.getElementById('conversion-file-input');
const conversionFileName = document.getElementById('conversion-file-name');
const outputFormatSelect = document.getElementById('output-format-select');
// MODIFICATION: Store the Choices.js instance in a variable
let conversionChoices = null;
// START: Drag and Drop additions
const dragOverlay = document.getElementById('drag-overlay');
const actionDialog = document.getElementById('action-dialog');
const dialogFileCount = document.getElementById('dialog-file-count');
// Dialog Views
const dialogInitialView = document.getElementById('dialog-initial-actions');
const dialogConvertView = document.getElementById('dialog-convert-view');
// Dialog Buttons
const dialogConvertBtn = document.getElementById('dialog-action-convert');
const dialogOcrBtn = document.getElementById('dialog-action-ocr');
const dialogTranscribeBtn = document.getElementById('dialog-action-transcribe');
const dialogCancelBtn = document.getElementById('dialog-action-cancel');
const dialogStartConversionBtn = document.getElementById('dialog-start-conversion');
const dialogBackBtn = document.getElementById('dialog-back');
// Dialog Select
const dialogOutputFormatSelect = document.getElementById('dialog-output-format-select');
// END: Drag and Drop additions
let conversionChoices = null;
let dialogConversionChoices = null; // For the dialog's format selector
const activePolls = new Map();
let stagedFiles = null; // To hold files from a drop event
// --- Main Event Listeners ---
pdfFileInput.addEventListener('change', () => updateFileName(pdfFileInput, pdfFileName));
@@ -37,13 +67,222 @@ document.addEventListener('DOMContentLoaded', () => {
handleCancelJob(jobId);
}
});
// --- Helper Functions ---
function formatBytes(bytes, decimals = 1) {
if (!+bytes) return '0 Bytes'; // Handles 0, null, undefined
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}
// --- Core Job Submission Logic (Refactored for reuse) ---
async function submitJob(endpoint, formData, originalFilename) {
try {
const response = await fetch(endpoint, { method: 'POST', body: formData });
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || `HTTP error! Status: ${response.status}`);
}
const result = await response.json();
const preliminaryJob = {
id: result.job_id,
status: 'pending',
progress: 0,
original_filename: originalFilename,
input_filesize: formData.get('file').size,
task_type: endpoint.includes('ocr') ? 'ocr' : (endpoint.includes('transcribe') ? 'transcription' : 'conversion'),
created_at: new Date().toISOString() // Create preliminary UTC timestamp
};
renderJobRow(preliminaryJob);
startPolling(result.job_id);
} catch (error) {
console.error('Error submitting job:', error);
alert(`Submission failed for ${originalFilename}: ${error.message}`);
}
}
// --- Original Form Submission Handler (Now uses submitJob) ---
async function handleFormSubmit(event, endpoint, form) {
event.preventDefault();
const fileInput = form.querySelector('input[type="file"]');
if (fileInput.files.length === 0) return;
const submitButton = form.querySelector('button[type="submit"]');
submitButton.disabled = true;
// Convert FileList to an array to loop through it
const files = Array.from(fileInput.files);
// Process each file as a separate job
for (const file of files) {
const formData = new FormData();
formData.append('file', file);
// Append other form data if it exists
const outputFormat = form.querySelector('select[name="output_format"]');
if (outputFormat) {
formData.append('output_format', outputFormat.value);
}
const modelSize = form.querySelector('select[name="model_size"]');
if (modelSize) {
formData.append('model_size', modelSize.value);
}
// Await each job submission to process them sequentially
await submitJob(endpoint, formData, file.name);
}
// Reset the form UI after all jobs have been submitted
const fileNameDisplay = form.querySelector('.file-name');
form.reset();
if (fileNameDisplay) {
fileNameDisplay.textContent = 'No file chosen';
fileNameDisplay.title = 'No file chosen';
}
if (form.id === 'conversion-form' && conversionChoices) {
conversionChoices.clearInput();
conversionChoices.setValue([]);
}
submitButton.disabled = false;
}
// --- START: Drag and Drop Implementation ---
function setupDragAndDropListeners() {
let dragCounter = 0; // Counter to manage enter/leave events reliably
window.addEventListener('dragenter', (e) => {
e.preventDefault();
dragCounter++;
document.body.classList.add('dragging');
});
window.addEventListener('dragleave', (e) => {
e.preventDefault();
dragCounter--;
if (dragCounter === 0) {
document.body.classList.remove('dragging');
}
});
window.addEventListener('dragover', (e) => {
e.preventDefault(); // This is necessary to allow a drop
});
window.addEventListener('drop', (e) => {
e.preventDefault();
dragCounter = 0; // Reset counter
document.body.classList.remove('dragging');
// Only handle the drop if it's on our designated overlay
if (e.target === dragOverlay || dragOverlay.contains(e.target)) {
const files = e.dataTransfer.files;
if (files && files.length > 0) {
stagedFiles = files;
showActionDialog();
}
}
});
}
function showActionDialog() {
dialogFileCount.textContent = stagedFiles.length;
// Clone options from main form's select to the dialog's select
dialogOutputFormatSelect.innerHTML = outputFormatSelect.innerHTML;
// Clean up previous Choices.js instance if it exists
if (dialogConversionChoices) {
dialogConversionChoices.destroy();
}
// Initialize a new Choices.js instance for the dialog
dialogConversionChoices = new Choices(dialogOutputFormatSelect, {
searchEnabled: true,
itemSelectText: 'Select',
shouldSort: false,
placeholder: true,
placeholderValue: 'Select a format...',
});
// Ensure the initial view is shown
dialogInitialView.style.display = 'grid';
dialogConvertView.style.display = 'none';
actionDialog.classList.add('visible');
}
function closeActionDialog() {
actionDialog.classList.remove('visible');
stagedFiles = null;
// Important: Destroy the Choices instance to prevent memory leaks
if (dialogConversionChoices) {
// Explicitly hide the dropdown before destroying
dialogConversionChoices.hideDropdown();
dialogConversionChoices.destroy();
dialogConversionChoices = null;
}
}
// --- Dialog Button and Action Listeners ---
dialogConvertBtn.addEventListener('click', () => {
// Switch to the conversion view
dialogInitialView.style.display = 'none';
dialogConvertView.style.display = 'block';
});
dialogBackBtn.addEventListener('click', () => {
// Switch back to the initial view
dialogInitialView.style.display = 'grid';
dialogConvertView.style.display = 'none';
});
dialogStartConversionBtn.addEventListener('click', () => handleDialogAction('convert'));
dialogOcrBtn.addEventListener('click', () => handleDialogAction('ocr'));
dialogTranscribeBtn.addEventListener('click', () => handleDialogAction('transcribe'));
dialogCancelBtn.addEventListener('click', closeActionDialog);
function handleDialogAction(action) {
if (!stagedFiles) return;
let endpoint = '';
const formDataArray = [];
for (const file of stagedFiles) {
const formData = new FormData();
formData.append('file', file);
if (action === 'convert') {
const selectedFormat = dialogConversionChoices.getValue(true);
if (!selectedFormat) {
alert('Please select a format to convert to.');
return;
}
formData.append('output_format', selectedFormat);
endpoint = '/convert-file';
} else if (action === 'ocr') {
endpoint = '/ocr-pdf';
} else if (action === 'transcribe') {
formData.append('model_size', modelSizeSelect.value);
endpoint = '/transcribe-audio';
}
formDataArray.push({ formData, name: file.name });
}
formDataArray.forEach(item => {
submitJob(endpoint, item.formData, item.name);
});
closeActionDialog();
}
// --- END: Drag and Drop Implementation ---
function initializeConversionSelector() {
// MODIFICATION: Destroy the old instance if it exists before creating a new one
if (conversionChoices) {
conversionChoices.destroy();
}
conversionChoices = new Choices(outputFormatSelect, {
searchEnabled: true,
itemSelectText: 'Select',
@@ -65,7 +304,7 @@ document.addEventListener('DOMContentLoaded', () => {
for (const formatKey in tool.formats) {
group.choices.push({
value: `${toolKey}_${formatKey}`,
label: `${formatKey.toUpperCase()} - ${tool.formats[formatKey]}`
label: `${tool.name} - ${formatKey.toUpperCase()} (${tool.formats[formatKey]})`
});
}
choicesArray.push(group);
@@ -73,58 +312,23 @@ document.addEventListener('DOMContentLoaded', () => {
conversionChoices.setChoices(choicesArray, 'value', 'label', true);
}
// --- Helper Functions ---
function updateFileName(input, nameDisplay) {
const fileName = input.files.length > 0 ? input.files[0].name : 'No file chosen';
nameDisplay.textContent = fileName;
nameDisplay.title = fileName;
}
const numFiles = input.files.length;
let displayText = 'No file chosen';
let displayTitle = 'No file chosen';
async function handleFormSubmit(event, endpoint, form) {
event.preventDefault();
const fileInput = form.querySelector('input[type="file"]');
const fileNameDisplay = form.querySelector('.file-name');
if (!fileInput.files[0]) return;
const formData = new FormData(form);
const submitButton = form.querySelector('button[type="submit"]');
submitButton.disabled = true;
try {
const response = await fetch(endpoint, { method: 'POST', body: formData });
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.detail || `HTTP error! Status: ${response.status}`);
}
const result = await response.json();
const preliminaryJob = {
id: result.job_id,
status: 'pending',
progress: 0,
original_filename: fileInput.files[0].name,
task_type: endpoint.includes('ocr') ? 'ocr' : (endpoint.includes('transcribe') ? 'transcription' : 'conversion'),
created_at: new Date().toISOString()
};
renderJobRow(preliminaryJob);
startPolling(result.job_id);
} catch (error) {
console.error('Error submitting job:', error);
alert(`Submission failed: ${error.message}`);
} finally {
form.reset();
if (fileNameDisplay) fileNameDisplay.textContent = 'No file chosen';
// MODIFICATION: Use the stored instance to correctly reset the dropdown
// without causing an error.
if (form.id === 'conversion-form' && conversionChoices) {
conversionChoices.clearInput();
conversionChoices.setValue([]); // Clears the selected value
}
submitButton.disabled = false;
if (numFiles === 1) {
displayText = input.files[0].name;
displayTitle = input.files[0].name;
} else if (numFiles > 1) {
displayText = `${numFiles} files selected`;
// Create a title attribute to show all filenames on hover
displayTitle = Array.from(input.files).map(file => file.name).join(', ');
}
nameDisplay.textContent = displayText;
nameDisplay.title = displayTitle;
}
async function handleCancelJob(jobId) {
if (!confirm('Are you sure you want to cancel this job?')) return;
try {
@@ -161,7 +365,7 @@ document.addEventListener('DOMContentLoaded', () => {
}
} catch (error) {
console.error("Couldn't load job history:", error);
jobListBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">Could not load job history.</td></tr>';
jobListBody.innerHTML = '<tr><td colspan="6" style="text-align: center;">Could not load job history.</td></tr>';
}
}
@@ -214,7 +418,12 @@ document.addEventListener('DOMContentLoaded', () => {
taskTypeLabel = 'Conversion';
}
const formattedDate = new Date(job.created_at).toLocaleString();
// --- CORRECTED DATE FORMATTING ---
// Takes the UTC string from the server (or the preliminary job)
// and formats it using the user's detected locale and timezone.
const submittedDate = new Date(job.created_at);
const formattedDate = submittedDate.toLocaleString(USER_LOCALE, DATETIME_FORMAT_OPTIONS);
let statusHtml = `<span class="job-status-badge status-${job.status}">${job.status}</span>`;
if (job.status === 'processing') {
const progressClass = (job.task_type === 'transcription' && job.progress > 0) ? '' : 'indeterminate';
@@ -233,9 +442,21 @@ document.addEventListener('DOMContentLoaded', () => {
actionHtml = `<span class="error-text"${errorTitle}>Failed</span>`;
}
// --- File Size Logic ---
let fileSizeHtml = '<span>-</span>';
if (job.input_filesize) {
let sizeString = formatBytes(job.input_filesize);
if (job.status === 'completed' && job.output_filesize) {
sizeString += `${formatBytes(job.output_filesize)}`;
}
fileSizeHtml = `<span class="cell-value">${sizeString}</span>`;
}
const escapedFilename = job.original_filename ? job.original_filename.replace(/</g, "&lt;").replace(/>/g, "&gt;") : "No filename";
row.innerHTML = `
<td data-label="File"><span class="cell-value" title="${escapedFilename}">${escapedFilename}</span></td>
<td data-label="File Size">${fileSizeHtml}</td>
<td data-label="Task"><span class="cell-value">${taskTypeLabel}</span></td>
<td data-label="Submitted"><span class="cell-value">${formattedDate}</span></td>
<td data-label="Status"><span class="cell-value">${statusHtml}</span></td>
@@ -246,4 +467,5 @@ document.addEventListener('DOMContentLoaded', () => {
// --- Initial Load ---
initializeConversionSelector();
loadInitialJobs();
setupDragAndDropListeners();
});