Implement Part 1: Fix Scan Library button with progress UI
Implements the frontend scan button fix from TASKS-scanning-progress.md Part 1.
Changes:
1. web/src/admin.ts - Added 6 new TypeScript functions:
- scanAllLibraries(): Fetches all libraries, triggers scan for each
- showScanProgress(): Displays progress UI with per-library progress bars
- pollScanProgress(): Polls status every 2 seconds, updates progress
- updateLibraryProgress(): Updates individual library progress bar/status
- showScanResults(): Displays scan completion results
- hideScanProgress(): Hides progress UI
2. templates/admin.templ - Updated UI:
- Added admin.js script include (Step 2)
- Changed button onclick from quickScan() to scanAllLibraries() (Step 3)
- Removed broken inline quickScan() function (Step 3.5)
- Added progress UI HTML with slide-in animation (Step 4)
Key Features:
- Fetches all libraries via GET /api/libraries
- Triggers scan for each library via POST /api/libraries/{id}/scan
- Displays per-library progress bars
- Shows overall progress percentage
- Real-time status updates every 2 seconds
- Results summary with file counts and errors
- TailwindCSS animation (no custom CSS)
- Follows PROJECT_GUIDELINES.md: TypeScript only, TailwindCSS classes
TypeScript compiles successfully (npm run build:ts)
All guidelines verified (26/26 checks pass)
This commit is contained in:
+54
-19
@@ -8,6 +8,7 @@ templ Admin(user User) {
|
||||
<title>Admin Dashboard - Bookhoard</title>
|
||||
<script src="/static/htmx.min.js"></script>
|
||||
<script src="/static/toast.js"></script>
|
||||
<script src="/static/admin.js"></script>
|
||||
<link href="/static/style.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="theme-tokyo-night">
|
||||
@@ -51,7 +52,7 @@ templ Admin(user User) {
|
||||
<div class="card p-6 rounded-lg border" style="background-color: var(--bg-secondary); border-color: var(--border)">
|
||||
<h3 class="text-xl font-semibold mb-4" style="color: var(--text-primary)">Quick Actions</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<button onclick="quickScan()" class="btn-primary p-4 rounded-lg text-left">
|
||||
<button onclick="scanAllLibraries()" class="btn-primary p-4 rounded-lg text-left">
|
||||
<div class="font-medium">Scan Library</div>
|
||||
<div style="color: var(--text-secondary)" class="text-sm">Find new ebooks in your folders</div>
|
||||
</button>
|
||||
@@ -61,29 +62,63 @@ templ Admin(user User) {
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Scan Progress Section -->
|
||||
<div id="scan-progress-container" class="hidden mt-6 p-6 rounded-lg border opacity-0 -translate-y-2.5 transition-all duration-300 ease-out" style="background-color: var(--bg-secondary); border-color: var(--border);">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="text-lg font-semibold" style="color: var(--text-primary)">
|
||||
📚 Scanning Libraries
|
||||
</h3>
|
||||
<button onclick="hideScanProgress()" class="p-2 hover:bg-gray-700 rounded">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Overall Progress -->
|
||||
<div class="mb-4">
|
||||
<div class="flex justify-between text-sm mb-2">
|
||||
<span style="color: var(--text-secondary)">Overall Progress</span>
|
||||
<span id="scan-progress-text" style="color: var(--text-primary)">0%</span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-700 rounded-full h-3">
|
||||
<div id="scan-progress-bar"
|
||||
class="h-3 rounded-full transition-all duration-500"
|
||||
style="width: 0%; background-color: var(--accent);">
|
||||
</div>
|
||||
</div>
|
||||
<div id="scan-status" class="text-sm mt-2" style="color: var(--text-secondary)">
|
||||
Starting scan...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Per-Library Progress -->
|
||||
<div id="library-progress-list" class="space-y-3">
|
||||
<!-- Dynamically populated -->
|
||||
</div>
|
||||
|
||||
<!-- Results Summary -->
|
||||
<div id="scan-results" class="hidden mt-6 p-4 rounded-lg border" style="background-color: var(--bg-primary); border-color: var(--border);">
|
||||
<h4 class="font-semibold mb-2" style="color: var(--text-primary)">✅ Scan Complete!</h4>
|
||||
<div id="scan-results-content" style="color: var(--text-secondary)">
|
||||
<!-- Results populated by JS -->
|
||||
</div>
|
||||
<div class="mt-4 flex gap-2">
|
||||
<button onclick="window.location.reload()"
|
||||
class="btn-primary px-4 py-2 rounded-lg">
|
||||
Refresh to View Books
|
||||
</button>
|
||||
<button onclick="hideScanProgress()"
|
||||
class="btn-secondary px-4 py-2 rounded-lg">
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function quickScan() {
|
||||
fetch('/api/scanner/scan', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + localStorage.getItem('token')
|
||||
},
|
||||
body: JSON.stringify({
|
||||
folder_paths: []
|
||||
})
|
||||
}).then(res => res.json()).then(data => {
|
||||
alert(data.message || 'Scan completed successfully!');
|
||||
}).catch(err => {
|
||||
console.error('Scan error:', err);
|
||||
alert('Scan failed. Please check your folder configuration.');
|
||||
});
|
||||
}
|
||||
|
||||
function logout() {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
|
||||
@@ -98,6 +98,199 @@ function renderSystemStats(stats: Record<string, unknown>): void {
|
||||
`;
|
||||
}
|
||||
|
||||
async function scanAllLibraries(): Promise<void> {
|
||||
const token = localStorage.getItem('token');
|
||||
if (!token) return;
|
||||
|
||||
try {
|
||||
const libsResp = await fetch('/api/libraries', {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (!libsResp.ok) {
|
||||
throw new Error('Failed to get libraries');
|
||||
}
|
||||
|
||||
const libsData = await libsResp.json();
|
||||
|
||||
if (!libsData.data || libsData.data.length === 0) {
|
||||
if ((window as any).showToast?.error) {
|
||||
(window as any).showToast.error('No libraries found. Please create a library first.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const libraries = libsData.data;
|
||||
|
||||
const jobs: string[] = [];
|
||||
const libraryNames: Record<string, string> = {};
|
||||
|
||||
for (const lib of libraries) {
|
||||
const scanResp = await fetch(`/api/libraries/${lib.id}/scan`, {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (scanResp.ok) {
|
||||
const result = await scanResp.json();
|
||||
jobs.push(result.job_id);
|
||||
libraryNames[result.job_id] = lib.name;
|
||||
} else {
|
||||
console.error(`Failed to scan library: ${lib.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (jobs.length === 0) {
|
||||
if ((window as any).showToast?.error) {
|
||||
(window as any).showToast.error('Failed to start scan for any library');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
showScanProgress(jobs, libraryNames);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Scan error:', error);
|
||||
if ((window as any).showToast?.error) {
|
||||
(window as any).showToast.error('Failed to start scan: ' + (error as Error).message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showScanProgress(jobIds: string[], libraryNames: Record<string, string>): void {
|
||||
const container = document.getElementById('scan-progress-container') as HTMLElement;
|
||||
const list = document.getElementById('library-progress-list') as HTMLElement;
|
||||
|
||||
if (!container || !list) return;
|
||||
|
||||
container.classList.remove('hidden');
|
||||
container.classList.remove('opacity-0', '-translate-y-2.5');
|
||||
|
||||
list.innerHTML = jobIds.map(jobId => `
|
||||
<div id="progress-${jobId}" class="p-3 rounded border"
|
||||
style="background-color: var(--bg-primary); border-color: var(--border);">
|
||||
<div class="flex justify-between items-center mb-2">
|
||||
<span class="font-medium" style="color: var(--text-primary)">
|
||||
${libraryNames[jobId]}
|
||||
</span>
|
||||
<span id="status-${jobId}" class="text-sm" style="color: var(--text-secondary)">
|
||||
Pending...
|
||||
</span>
|
||||
</div>
|
||||
<div class="w-full bg-gray-700 rounded-full h-2">
|
||||
<div id="bar-${jobId}"
|
||||
class="h-2 rounded-full transition-all duration-500"
|
||||
style="width: 0%; background-color: var(--accent);">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
pollScanProgress(jobIds, libraryNames);
|
||||
}
|
||||
|
||||
function pollScanProgress(jobIds: string[], _libraryNames: Record<string, string>): void {
|
||||
const token = localStorage.getItem('token');
|
||||
const startTime = Date.now();
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
let allComplete = true;
|
||||
let totalProgress = 0;
|
||||
let totalFiles = 0;
|
||||
let totalNewItems = 0;
|
||||
let totalErrors = 0;
|
||||
|
||||
for (const jobId of jobIds) {
|
||||
try {
|
||||
const resp = await fetch(`/api/scanner/status/${jobId}`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
});
|
||||
|
||||
if (resp.ok) {
|
||||
const status = await resp.json();
|
||||
|
||||
updateLibraryProgress(jobId, status);
|
||||
|
||||
totalProgress += status.progress || 0;
|
||||
totalFiles += status.files_scanned || 0;
|
||||
totalNewItems += status.new_items || 0;
|
||||
totalErrors += status.errors || 0;
|
||||
|
||||
if (status.status !== 'completed' && status.status !== 'failed') {
|
||||
allComplete = false;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to poll job ${jobId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const overallProgress = Math.round(totalProgress / jobIds.length);
|
||||
const progressBar = document.getElementById('scan-progress-bar') as HTMLElement;
|
||||
const progressText = document.getElementById('scan-progress-text') as HTMLElement;
|
||||
const statusText = document.getElementById('scan-status') as HTMLElement;
|
||||
|
||||
if (progressBar) progressBar.style.width = overallProgress + '%';
|
||||
if (progressText) progressText.textContent = overallProgress + '%';
|
||||
|
||||
const elapsed = Math.round((Date.now() - startTime) / 1000);
|
||||
if (!allComplete && statusText) {
|
||||
statusText.textContent = `Scanning... ${elapsed}s elapsed • ${totalFiles} files processed`;
|
||||
}
|
||||
|
||||
if (allComplete) {
|
||||
clearInterval(interval);
|
||||
showScanResults(jobIds.length, totalFiles, totalNewItems, totalErrors, elapsed);
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function updateLibraryProgress(jobId: string, status: any): void {
|
||||
const bar = document.getElementById(`bar-${jobId}`) as HTMLElement;
|
||||
const statusText = document.getElementById(`status-${jobId}`) as HTMLElement;
|
||||
|
||||
if (bar) {
|
||||
bar.style.width = (status.progress || 0) + '%';
|
||||
}
|
||||
|
||||
if (statusText) {
|
||||
const statusMessages: Record<string, string> = {
|
||||
'pending': 'Pending...',
|
||||
'running': `Scanning... ${status.progress || 0}%`,
|
||||
'completed': `✓ Complete (${status.new_items || 0} items)`,
|
||||
'failed': `✗ Failed`
|
||||
};
|
||||
statusText.textContent = statusMessages[status.status] || status.status;
|
||||
}
|
||||
}
|
||||
|
||||
function showScanResults(libCount: number, files: number, items: number, errors: number, elapsed: number): void {
|
||||
const resultsDiv = document.getElementById('scan-results') as HTMLElement;
|
||||
const contentDiv = document.getElementById('scan-results-content') as HTMLElement;
|
||||
|
||||
if (!resultsDiv || !contentDiv) return;
|
||||
|
||||
contentDiv.innerHTML = `
|
||||
<p>• ${libCount} librar${libCount === 1 ? 'y' : 'ies'} scanned</p>
|
||||
<p>• ${files} files processed</p>
|
||||
<p>• ${items} new items added</p>
|
||||
${errors > 0 ? `<p style="color: var(--accent);">• ${errors} errors</p>` : ''}
|
||||
<p style="color: var(--text-secondary)">Completed in ${elapsed} seconds</p>
|
||||
`;
|
||||
|
||||
resultsDiv.classList.remove('hidden');
|
||||
|
||||
const statusText = document.getElementById('scan-status') as HTMLElement;
|
||||
if (statusText) statusText.textContent = 'Scan complete!';
|
||||
}
|
||||
|
||||
function hideScanProgress(): void {
|
||||
const container = document.getElementById('scan-progress-container') as HTMLElement;
|
||||
if (container) container.classList.add('hidden');
|
||||
}
|
||||
|
||||
(window as any).triggerLibraryScan = triggerLibraryScan;
|
||||
(window as any).triggerQuickScan = triggerQuickScan;
|
||||
(window as any).loadSystemStats = loadSystemStats;
|
||||
(window as any).scanAllLibraries = scanAllLibraries;
|
||||
(window as any).hideScanProgress = hideScanProgress;
|
||||
|
||||
Reference in New Issue
Block a user