Audiobook Maker Pro v4.2 — production ready

This commit is contained in:
Ashim Kumar
2026-05-22 18:28:47 +06:00
commit 0617a374dd
41 changed files with 15262 additions and 0 deletions

679
templates/admin.html Normal file
View File

@@ -0,0 +1,679 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Audiobook Maker Pro</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #4f46e5;
--primary-hover: #4338ca;
--success-color: #10b981;
--danger-color: #ef4444;
--warning-color: #f59e0b;
--bg-primary: #f8fafc;
--text-primary: #1e293b;
--text-secondary: #64748b;
--text-muted: #94a3b8;
--border-color: #e2e8f0;
}
* { box-sizing: border-box; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--bg-primary);
color: var(--text-primary);
margin: 0;
}
.admin-header {
background: linear-gradient(135deg, var(--primary-color) 0%, #7c3aed 100%);
color: white;
padding: 16px 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.admin-header h1 {
font-size: 1.25rem;
font-weight: 700;
margin: 0;
display: flex;
align-items: center;
gap: 10px;
}
.admin-header-actions {
display: flex;
gap: 10px;
align-items: center;
}
.admin-header-actions .btn {
border-radius: 8px;
font-weight: 500;
font-size: 0.85rem;
}
.btn-header-light {
background: rgba(255,255,255,0.15);
border: 1.5px solid rgba(255,255,255,0.4);
color: white;
}
.btn-header-light:hover {
background: rgba(255,255,255,0.25);
color: white;
}
.admin-container {
max-width: 900px;
margin: 32px auto;
padding: 0 24px;
}
.admin-card {
background: white;
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0,0,0,0.06);
border: 1px solid var(--border-color);
overflow: hidden;
}
.admin-card-header {
padding: 20px 24px;
border-bottom: 1px solid var(--border-color);
display: flex;
justify-content: space-between;
align-items: center;
}
.admin-card-header h2 {
font-size: 1.1rem;
font-weight: 700;
margin: 0;
display: flex;
align-items: center;
gap: 8px;
}
.user-count-badge {
background: var(--bg-primary);
color: var(--text-secondary);
font-size: 0.75rem;
font-weight: 600;
padding: 2px 10px;
border-radius: 12px;
border: 1px solid var(--border-color);
}
.user-table {
width: 100%;
border-collapse: collapse;
}
.user-table th {
background: var(--bg-primary);
padding: 12px 20px;
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.5px;
color: var(--text-secondary);
text-align: left;
border-bottom: 1px solid var(--border-color);
}
.user-table td {
padding: 14px 20px;
border-bottom: 1px solid #f1f5f9;
font-size: 0.88rem;
vertical-align: middle;
}
.user-table tr:last-child td {
border-bottom: none;
}
.user-table tr:hover td {
background: #fafbfd;
}
.role-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px 10px;
border-radius: 12px;
font-size: 0.72rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.3px;
}
.role-badge.admin {
background: #ede9fe;
color: #5b21b6;
}
.role-badge.user {
background: #e0f2fe;
color: #0369a1;
}
.status-badge {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 0.8rem;
font-weight: 500;
}
.status-badge .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
}
.status-badge.active .status-dot { background: var(--success-color); }
.status-badge.active { color: #065f46; }
.status-badge.disabled .status-dot { background: var(--danger-color); }
.status-badge.disabled { color: #991b1b; }
.user-actions .btn {
padding: 4px 10px;
font-size: 0.78rem;
border-radius: 6px;
}
.date-text {
font-size: 0.8rem;
color: var(--text-muted);
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: var(--text-muted);
}
.empty-state i {
font-size: 3rem;
margin-bottom: 12px;
display: block;
}
/* Modal tweaks */
.modal-content {
border: none;
border-radius: 16px;
box-shadow: 0 20px 50px rgba(0,0,0,0.2);
}
.modal-header {
border-bottom: 1px solid var(--border-color);
padding: 20px 24px;
}
.modal-body { padding: 24px; }
.modal-footer { border-top: 1px solid var(--border-color); padding: 16px 24px; }
.form-label {
font-weight: 600;
font-size: 0.85rem;
color: #374151;
}
.form-control, .form-select {
padding: 10px 14px;
border: 2px solid var(--border-color);
border-radius: 8px;
font-size: 0.9rem;
}
.form-control:focus, .form-select:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(79,70,229,0.1);
}
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
}
@media (max-width: 768px) {
.admin-header {
flex-direction: column;
gap: 12px;
text-align: center;
}
.admin-card-header {
flex-direction: column;
gap: 12px;
}
.user-table {
font-size: 0.82rem;
}
.user-table th, .user-table td {
padding: 10px 12px;
}
}
</style>
</head>
<body>
<!-- Header -->
<header class="admin-header">
<h1>
<i class="bi bi-shield-lock"></i>
Admin Dashboard
</h1>
<div class="admin-header-actions">
<span class="text-white-50" id="currentUserLabel"></span>
<a href="/" class="btn btn-header-light btn-sm">
<i class="bi bi-arrow-left me-1"></i> Back to App
</a>
<button class="btn btn-header-light btn-sm" onclick="handleLogout()">
<i class="bi bi-box-arrow-right me-1"></i> Logout
</button>
</div>
</header>
<!-- Main Content -->
<div class="admin-container">
<div class="admin-card">
<div class="admin-card-header">
<h2>
<i class="bi bi-people"></i>
User Management
<span class="user-count-badge" id="userCountBadge">0 users</span>
</h2>
<button class="btn btn-primary btn-sm" onclick="openCreateModal()">
<i class="bi bi-person-plus me-1"></i> Create User
</button>
</div>
<div id="userTableContainer">
<div class="empty-state">
<div class="spinner-border text-primary" role="status"></div>
<p class="mt-2">Loading users...</p>
</div>
</div>
</div>
</div>
<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>
<!-- Create/Edit User Modal -->
<div class="modal fade" id="userModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="userModalTitle">
<i class="bi bi-person-plus me-2"></i>Create New User
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" id="editUserId">
<div class="mb-3">
<label for="modalUsername" class="form-label">Username</label>
<input type="text" class="form-control" id="modalUsername"
placeholder="Enter username" minlength="3" required>
</div>
<div class="mb-3">
<label for="modalPassword" class="form-label">
Password
<span class="text-muted fw-normal" id="passwordHint" style="display:none;">(leave blank to keep current)</span>
</label>
<input type="text" class="form-control" id="modalPassword"
placeholder="Enter password" minlength="4">
</div>
<div class="mb-3">
<label for="modalRole" class="form-label">Role</label>
<select class="form-select" id="modalRole">
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</div>
<div class="mb-3" id="activeField" style="display:none;">
<label class="form-label">Status</label>
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="modalActive" checked>
<label class="form-check-label" for="modalActive">Account Active</label>
</div>
</div>
<div class="alert alert-danger" id="modalError" style="display:none;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="modalSaveBtn" onclick="saveUser()">
<i class="bi bi-check-lg me-1"></i> Create User
</button>
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="bi bi-exclamation-triangle text-danger me-2"></i>Delete User</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete <strong id="deleteUserName"></strong>?</p>
<p class="text-muted small mb-0">This action cannot be undone.</p>
<input type="hidden" id="deleteUserId">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger btn-sm" onclick="confirmDelete()">
<i class="bi bi-trash me-1"></i> Delete
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
let userModal, deleteModal;
let currentUsers = [];
document.addEventListener('DOMContentLoaded', function() {
userModal = new bootstrap.Modal(document.getElementById('userModal'));
deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
loadCurrentUser();
loadUsers();
});
async function loadCurrentUser() {
try {
const resp = await fetch('/api/auth/me');
const data = await resp.json();
if (data.user) {
document.getElementById('currentUserLabel').textContent =
`Logged in as ${data.user.username}`;
}
} catch(e) { /* ignore */ }
}
async function loadUsers() {
try {
const resp = await fetch('/api/admin/users');
const data = await resp.json();
currentUsers = data.users || [];
renderUserTable(currentUsers);
} catch(e) {
document.getElementById('userTableContainer').innerHTML =
'<div class="empty-state"><i class="bi bi-exclamation-circle"></i><p>Failed to load users</p></div>';
}
}
function renderUserTable(users) {
const container = document.getElementById('userTableContainer');
const badge = document.getElementById('userCountBadge');
badge.textContent = `${users.length} user${users.length !== 1 ? 's' : ''}`;
if (users.length === 0) {
container.innerHTML = '<div class="empty-state"><i class="bi bi-people"></i><p>No users found</p></div>';
return;
}
let html = `<table class="user-table">
<thead>
<tr>
<th>User</th>
<th>Role</th>
<th>Status</th>
<th>Last Login</th>
<th>Created</th>
<th style="text-align:right;">Actions</th>
</tr>
</thead>
<tbody>`;
for (const user of users) {
const statusClass = user.is_active ? 'active' : 'disabled';
const statusText = user.is_active ? 'Active' : 'Disabled';
const lastLogin = user.last_login ? formatDate(user.last_login) : '<span class="text-muted">Never</span>';
html += `<tr>
<td>
<strong>${escapeHtml(user.username)}</strong>
</td>
<td>
<span class="role-badge ${user.role}">
<i class="bi bi-${user.role === 'admin' ? 'shield-check' : 'person'}"></i>
${user.role}
</span>
</td>
<td>
<span class="status-badge ${statusClass}">
<span class="status-dot"></span>
${statusText}
</span>
</td>
<td class="date-text">${lastLogin}</td>
<td class="date-text">${formatDate(user.created_at)}</td>
<td style="text-align:right;">
<div class="user-actions d-flex gap-1 justify-content-end">
<button class="btn btn-outline-primary btn-sm" onclick="openEditModal(${user.id})" title="Edit user">
<i class="bi bi-pencil"></i>
</button>
<button class="btn btn-outline-danger btn-sm" onclick="openDeleteModal(${user.id}, '${escapeHtml(user.username)}')" title="Delete user">
<i class="bi bi-trash"></i>
</button>
</div>
</td>
</tr>`;
}
html += '</tbody></table>';
container.innerHTML = html;
}
// --- Create / Edit ---
function openCreateModal() {
document.getElementById('userModalTitle').innerHTML = '<i class="bi bi-person-plus me-2"></i>Create New User';
document.getElementById('editUserId').value = '';
document.getElementById('modalUsername').value = '';
document.getElementById('modalPassword').value = '';
document.getElementById('modalPassword').required = true;
document.getElementById('modalPassword').placeholder = 'Enter password';
document.getElementById('passwordHint').style.display = 'none';
document.getElementById('modalRole').value = 'user';
document.getElementById('modalActive').checked = true;
document.getElementById('activeField').style.display = 'none';
document.getElementById('modalSaveBtn').innerHTML = '<i class="bi bi-check-lg me-1"></i> Create User';
document.getElementById('modalError').style.display = 'none';
userModal.show();
}
function openEditModal(userId) {
const user = currentUsers.find(u => u.id === userId);
if (!user) return;
document.getElementById('userModalTitle').innerHTML = '<i class="bi bi-pencil me-2"></i>Edit User';
document.getElementById('editUserId').value = userId;
document.getElementById('modalUsername').value = user.username;
document.getElementById('modalPassword').value = '';
document.getElementById('modalPassword').required = false;
document.getElementById('modalPassword').placeholder = 'Leave blank to keep current';
document.getElementById('passwordHint').style.display = 'inline';
document.getElementById('modalRole').value = user.role;
document.getElementById('modalActive').checked = user.is_active;
document.getElementById('activeField').style.display = 'block';
document.getElementById('modalSaveBtn').innerHTML = '<i class="bi bi-check-lg me-1"></i> Save Changes';
document.getElementById('modalError').style.display = 'none';
userModal.show();
}
async function saveUser() {
const userId = document.getElementById('editUserId').value;
const username = document.getElementById('modalUsername').value.trim();
const password = document.getElementById('modalPassword').value;
const role = document.getElementById('modalRole').value;
const isActive = document.getElementById('modalActive').checked;
const errorDiv = document.getElementById('modalError');
errorDiv.style.display = 'none';
if (!username || username.length < 3) {
errorDiv.textContent = 'Username must be at least 3 characters';
errorDiv.style.display = 'block';
return;
}
if (!userId && (!password || password.length < 4)) {
errorDiv.textContent = 'Password must be at least 4 characters';
errorDiv.style.display = 'block';
return;
}
if (userId && password && password.length < 4) {
errorDiv.textContent = 'Password must be at least 4 characters';
errorDiv.style.display = 'block';
return;
}
try {
let url, method, body;
if (userId) {
url = `/api/admin/users/${userId}`;
method = 'PUT';
body = { username, role, is_active: isActive };
if (password) body.password = password;
} else {
url = '/api/admin/users';
method = 'POST';
body = { username, password, role };
}
const resp = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const data = await resp.json();
if (data.error) {
errorDiv.textContent = data.error;
errorDiv.style.display = 'block';
return;
}
userModal.hide();
showToast(data.message || 'User saved successfully', 'success');
loadUsers();
} catch(e) {
errorDiv.textContent = 'Network error. Please try again.';
errorDiv.style.display = 'block';
}
}
// --- Delete ---
function openDeleteModal(userId, username) {
document.getElementById('deleteUserId').value = userId;
document.getElementById('deleteUserName').textContent = username;
deleteModal.show();
}
async function confirmDelete() {
const userId = document.getElementById('deleteUserId').value;
try {
const resp = await fetch(`/api/admin/users/${userId}`, { method: 'DELETE' });
const data = await resp.json();
deleteModal.hide();
if (data.error) {
showToast(data.error, 'error');
return;
}
showToast(data.message || 'User deleted', 'success');
loadUsers();
} catch(e) {
deleteModal.hide();
showToast('Failed to delete user', 'error');
}
}
// --- Logout ---
async function handleLogout() {
try {
await fetch('/api/auth/logout', { method: 'POST' });
} catch(e) { /* ignore */ }
window.location.href = '/login';
}
// --- Utilities ---
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function formatDate(dateStr) {
if (!dateStr) return '';
const d = new Date(dateStr);
return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function showToast(message, type = 'info') {
const container = document.getElementById('toastContainer');
const colors = { success: 'success', error: 'danger', info: 'primary' };
const icons = { success: 'check-circle', error: 'exclamation-circle', info: 'info-circle' };
const toast = document.createElement('div');
toast.className = `alert alert-${colors[type] || 'info'} d-flex align-items-center gap-2`;
toast.style.cssText = 'min-width:280px; animation: slideIn 0.3s ease; margin-bottom: 8px;';
toast.innerHTML = `<i class="bi bi-${icons[type] || 'info-circle'}"></i> ${escapeHtml(message)}`;
container.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'slideOut 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// Inject animation styles
const s = document.createElement('style');
s.textContent = `
@keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
@keyframes slideOut { from { transform: translateX(0); opacity: 1; } to { transform: translateX(100%); opacity: 0; } }
`;
document.head.appendChild(s);
</script>
</body>
</html>

478
templates/index.html Normal file
View File

@@ -0,0 +1,478 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audiobook Maker Pro v4.1</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Merriweather:ital,wght@0,400;0,700;1,400&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="/static/css/markdown-editor.css">
</head>
<body>
<div class="loading-overlay" id="loadingOverlay">
<div class="loading-content">
<div class="spinner-border text-primary" role="status"></div>
<h5 id="loadingText">Processing...</h5>
<p id="loadingSubtext" class="text-muted">Please wait</p>
</div>
</div>
<div class="welcome-overlay" id="welcomeOverlay">
<div class="welcome-card">
<div class="welcome-header">
<i class="bi bi-soundwave"></i>
<h2>Welcome to Audiobook Maker Pro</h2>
<p>Turn any document into an interactive audiobook in 3 simple steps</p>
</div>
<div class="welcome-steps">
<div class="welcome-step">
<div class="welcome-step-number">Step-1</div>
<div class="welcome-step-icon"><i class="bi bi-upload"></i></div>
<h4>Upload Document</h4>
<div class="welcome-step-details">
<p>Drag & drop a <strong>PDF</strong>, <strong>DOCX</strong>, or <strong>DOC</strong> file into the upload area</p>
</div>
</div>
<div class="welcome-step-arrow"><i class="bi bi-arrow-right"></i></div>
<div class="welcome-step">
<div class="welcome-step-number">Step-2</div>
<div class="welcome-step-icon"><i class="bi bi-soundwave"></i></div>
<h4>Edit & Generate Audio</h4>
<div class="welcome-step-details">
<p>Use the <strong>Audiobook Maker Panel</strong> at the top to select a voice and set how many blocks to generate</p>
<p>Click <span class="welcome-ui-btn success-btn"><i class="bi bi-play-fill"></i> Generate</span> to create audio with word-level timestamps</p>
</div>
</div>
<div class="welcome-step-arrow"><i class="bi bi-arrow-right"></i></div>
<div class="welcome-step">
<div class="welcome-step-number">Step-3</div>
<div class="welcome-step-icon"><i class="bi bi-book"></i></div>
<h4>Read & Export</h4>
<div class="welcome-step-details">
<p>Switch to the <span class="welcome-ui-btn"><i class="bi bi-book"></i> Interactive Reader</span> tab to listen with word-by-word highlighting</p>
<p>Click <span class="welcome-ui-btn primary-btn"><i class="bi bi-download"></i> Export</span> in the header to download your audiobook as a ZIP</p>
</div>
</div>
</div>
<div class="welcome-actions">
<button class="btn btn-primary btn-lg" onclick="dismissWelcome()">
<i class="bi bi-rocket-takeoff me-2"></i>Get Started
</button>
<label class="welcome-dismiss-label">
<input type="checkbox" id="welcomeDontShow"> Don't show this again
</label>
</div>
</div>
</div>
<div class="floating-guide-panel" id="floatingGuidePanel">
<div class="guide-panel-header" id="guidePanelHeader">
<div class="guide-panel-title">
<i class="bi bi-lightbulb"></i>
<span>Quick Guide</span>
</div>
<div class="guide-panel-controls">
<button class="guide-panel-btn" id="guidePanelCollapse" onclick="toggleGuideCollapse()" title="Collapse / Expand">
<i class="bi bi-chevron-up" id="guideCollapseIcon"></i>
</button>
<button class="guide-panel-btn" onclick="hideGuidePanel()" title="Hide guide panel">
<i class="bi bi-x-lg"></i>
</button>
</div>
</div>
<div class="guide-panel-body" id="guidePanelBody">
<div class="guide-section">
<div class="guide-section-badge">Step 2 — Edit & Generate</div>
<div class="guide-instruction">
<span class="guide-step-num">1</span>
<div class="guide-instruction-text">
Use the <strong>panel at the top</strong> to select a <strong>voice</strong> and set the number of blocks to generate
</div>
</div>
<div class="guide-instruction">
<span class="guide-step-num">2</span>
<div class="guide-instruction-text">
Click the <strong>Starting from</strong> indicator to pick which block to start from, then click
<span class="guide-ui generate-btn-ui"><i class="bi bi-play-fill"></i> Generate</span>
to create audio
</div>
</div>
<div class="guide-instruction">
<span class="guide-step-num">3</span>
<div class="guide-instruction-text">
Click
<span class="guide-ui image-btn-ui"><i class="bi bi-image"></i></span>
between blocks to <strong>add an image</strong>, or
<span class="guide-ui add-block-btn-ui"><i class="bi bi-plus"></i></span>
to <strong>add a text block</strong>
</div>
</div>
<div class="guide-instruction">
<span class="guide-step-num">4</span>
<div class="guide-instruction-text">
After generating, the starting block <strong>auto-advances</strong> so you can keep clicking Generate for the next batch
</div>
</div>
</div>
<div class="guide-section">
<div class="guide-section-badge step3-badge">Step 3 — Read & Export</div>
<div class="guide-instruction">
<span class="guide-step-num">5</span>
<div class="guide-instruction-text">
Switch to the
<span class="guide-ui reader-tab-ui"><i class="bi bi-book"></i> Interactive Reader</span>
tab to <strong>listen</strong> with word-by-word highlighting
</div>
</div>
<div class="guide-instruction">
<span class="guide-step-num">6</span>
<div class="guide-instruction-text">
Click
<span class="guide-ui export-btn-ui"><i class="bi bi-download"></i> Export</span>
in the header to <strong>download</strong> your audiobook as a ZIP
</div>
</div>
</div>
<div class="guide-panel-footer">
<label class="guide-dont-show">
<input type="checkbox" id="guidePanelDontShow" onchange="handleGuideDontShow()">
Don't show this again
</label>
</div>
</div>
</div>
<button class="floating-guide-toggle" id="floatingGuideToggle" onclick="showGuidePanel()" title="Show Quick Guide">
<i class="bi bi-lightbulb"></i>
</button>
<div class="app-container">
<header class="app-header">
<div class="header-left">
<h1 class="app-title">
<i class="bi bi-soundwave"></i>
Audiobook Maker Pro
<span class="version-badge">v4.2</span>
</h1>
</div>
<div class="header-right">
<div class="project-controls">
<input type="text" id="projectName" class="form-control project-name-input"
placeholder="Project Name" value="My Audiobook">
<button class="btn btn-success" id="saveProjectBtn" onclick="saveProject()" title="Save project (Ctrl+S)">
<i class="bi bi-save me-1"></i> Save
</button>
<button class="btn btn-primary" onclick="exportProject()" title="Export as ZIP with audio + reader">
<i class="bi bi-download me-1"></i> Export
</button>
<button class="btn btn-header-archive" onclick="openProjectArchive()" title="Load or manage saved projects">
<i class="bi bi-archive me-1"></i> Archive
</button>
<button class="btn btn-header-help" id="headerHelpBtn" onclick="handleHeaderHelp()" title="Show quick start guide">
<i class="bi bi-question-circle me-1"></i>
<span id="headerHelpLabel">Quick Start</span>
</button>
<div class="dropdown">
<button class="btn btn-header-user dropdown-toggle" type="button"
data-bs-toggle="dropdown" aria-expanded="false" id="userMenuBtn">
<i class="bi bi-person-circle me-1"></i>
<span id="headerUsername">User</span>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li id="adminMenuItem" style="display:none;">
<a class="dropdown-item" href="/admin">
<i class="bi bi-shield-lock me-2"></i>Admin Dashboard
</a>
</li>
<li id="adminDivider" style="display:none;"><hr class="dropdown-divider"></li>
<li>
<a class="dropdown-item" href="#" onclick="openChangePassword()">
<i class="bi bi-key me-2"></i>Change Password
</a>
</li>
<li><hr class="dropdown-divider"></li>
<li>
<a class="dropdown-item text-danger" href="#" onclick="handleLogout()">
<i class="bi bi-box-arrow-right me-2"></i>Logout
</a>
</li>
</ul>
</div>
</div>
</div>
</header>
<div class="workflow-progress" id="workflowProgress">
<div class="workflow-step active" id="wpStep1">
<div class="workflow-step-dot">1</div>
<span>Upload</span>
</div>
<div class="workflow-connector" id="wpConn1"></div>
<div class="workflow-step" id="wpStep2">
<div class="workflow-step-dot">2</div>
<span>Edit & Generate</span>
</div>
<div class="workflow-connector" id="wpConn2"></div>
<div class="workflow-step" id="wpStep3">
<div class="workflow-step-dot">3</div>
<span>Read & Export</span>
</div>
</div>
<main class="main-content">
<ul class="nav nav-tabs main-tabs" id="mainTabs" role="tablist">
<li class="nav-item">
<button class="nav-link active" id="editor-tab" data-bs-toggle="tab"
data-bs-target="#editorPanel" type="button">
<i class="bi bi-pencil-square me-1"></i> Audiobook Maker Editor
</button>
</li>
<li class="nav-item">
<button class="nav-link" id="reader-tab" data-bs-toggle="tab"
data-bs-target="#readerPanel" type="button">
<i class="bi bi-book me-1"></i> Interactive Reader
<span class="reader-tab-badge" id="readerTabBadge" style="display:none;">
Ready
</span>
</button>
</li>
</ul>
<div class="tab-content" id="mainTabContent">
<div class="tab-pane fade show active" id="editorPanel" role="tabpanel">
<div class="upload-section" id="uploadSection">
<div class="upload-zone-wrapper" style="min-height: 380px; border: 2px dashed var(--border-color); border-radius: var(--border-radius-lg); overflow: hidden; background: var(--bg-tertiary); transition: border-color 0.3s;">
<div class="upload-zone" id="uploadZone" style="width: 100%; display: flex; align-items: center; justify-content: center; padding: 48px 32px; cursor: pointer; transition: all 0.3s;">
<input type="file" id="docInput" accept=".pdf,.doc,.docx" hidden>
<div class="upload-content" style="text-align: center; max-width: 500px;">
<i class="bi bi-file-earmark-arrow-up upload-icon"></i>
<h4>Upload Your Document</h4>
<p class="text-muted mb-3">
Drag & drop a file here, or click the button below to browse
</p>
<div class="d-flex gap-2 justify-content-center flex-wrap mb-3">
<span class="badge bg-danger bg-opacity-10 text-danger px-3 py-2">
<i class="bi bi-file-earmark-pdf me-1"></i>PDF
</span>
<span class="badge bg-primary bg-opacity-10 text-primary px-3 py-2">
<i class="bi bi-file-earmark-word me-1"></i>DOC
</span>
</div>
<button class="btn btn-primary btn-lg" onclick="event.stopPropagation(); document.getElementById('docInput').click()">
<i class="bi bi-upload me-2"></i>Choose File
</button>
<p class="upload-hint-text">
<i class="bi bi-magic me-1"></i>
AI will auto-detect chapters, fix broken paragraphs, and structure your book
</p>
</div>
</div>
</div>
</div>
<div class="editor-section" id="editorSection" style="display:none">
<div class="audiobook-maker-panel" id="audiobookMakerPanel" style="display:none;">
<div class="amp-left">
<div>
<div class="amp-label">Voice</div>
<select class="amp-voice-select" id="ampVoiceSelect"
onchange="handleVoiceChange(this.value)">
<option value="af_heart">Heart (US Female)</option>
</select>
</div>
<div>
<div class="amp-label">Blocks to generate</div>
<div class="amp-block-count-group">
<input type="number" class="amp-block-count-input" id="ampBlockCount"
value="10" min="1" max="999"
onchange="handleBlockCountChange(this.value)"
onkeyup="handleBlockCountChange(this.value)">
<div class="amp-count-arrows">
<button class="amp-count-arrow" onclick="adjustBlockCount(1)" title="Increase">
<i class="bi bi-chevron-up"></i>
</button>
<button class="amp-count-arrow" onclick="adjustBlockCount(-1)" title="Decrease">
<i class="bi bi-chevron-down"></i>
</button>
</div>
</div>
</div>
<div>
<div class="amp-label">Starting from</div>
<div class="amp-start-indicator" id="ampStartIndicator"
onclick="togglePickMode()" title="Click to pick a different starting block">
<i class="bi bi-cursor-fill"></i>
Block <span class="start-block-num" id="ampStartBlockNum">1</span>
</div>
</div>
</div>
<div class="amp-right">
<button class="amp-generate-btn" id="ampGenerateBtn" onclick="generateFromPanel()">
<i class="bi bi-play-fill"></i>
Generate
</button>
</div>
<div class="amp-info">
<div class="amp-stat">
<i class="bi bi-layers"></i>
Total Blocks: <strong id="ampTotalBlocks">0</strong>
</div>
<div class="amp-stat">
<i class="bi bi-check-circle"></i>
Generated: <strong id="ampGeneratedBlocks">0</strong>
</div>
<div class="amp-stat">
<i class="bi bi-hourglass-split"></i>
Remaining: <strong id="ampRemainingBlocks">0</strong>
</div>
</div>
</div>
<div class="editor-layout">
<aside class="document-outline" id="documentOutlineSidebar" style="display:none;">
<h6 class="outline-title"><i class="bi bi-list-nested"></i> Document Outline</h6>
<ul class="outline-list" id="documentOutlineList">
<li class="text-muted small">No sections found.</li>
</ul>
</aside>
<div class="editor-container" id="markdownEditor">
<div class="empty-editor-message" id="emptyEditorMessage">
<i class="bi bi-file-text"></i>
<p>Upload a document to create content</p>
<p class="text-muted small">Click anywhere to add a new block</p>
</div>
</div>
</div>
</div>
</div>
<div class="tab-pane fade" id="readerPanel" role="tabpanel">
<div class="editor-layout">
<aside class="document-outline" id="readerOutlineSidebar" style="display:none;">
<h6 class="outline-title"><i class="bi bi-list-nested"></i> Outline</h6>
<ul class="outline-list" id="readerOutlineList">
<li class="text-muted small">No sections found.</li>
</ul>
</aside>
<div class="reader-container" id="readerContainer" style="flex: 1; max-width: 100%;">
<div class="reader-empty-state">
<i class="bi bi-book"></i>
<p>Generate audio to view the interactive reader</p>
<p class="text-muted">Go to the Editor tab, then click <strong>"Generate"</strong> on the panel</p>
<button class="btn btn-primary mt-3" onclick="switchToEditorTab()">
<i class="bi bi-arrow-left me-1"></i> Go to Editor
</button>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<div class="modal fade" id="archiveModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-archive me-2"></i>Project Archive
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div id="projectList"></div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="ttsEditModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-mic me-2"></i>Edit Text for TTS Generation
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<p class="text-muted small mb-2">
<i class="bi bi-info-circle me-1"></i>
This text will be used for audio generation. The original markdown content will be preserved.
</p>
<textarea id="ttsTextInput" class="form-control" rows="8"></textarea>
<input type="hidden" id="ttsBlockId">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="saveTtsText()">
<i class="bi bi-check-lg me-1"></i>Save
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="changePasswordModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<i class="bi bi-key me-2"></i>Change Password
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label for="currentPassword" class="form-label">Current Password</label>
<input type="password" class="form-control" id="currentPassword" required>
</div>
<div class="mb-3">
<label for="newPassword" class="form-label">New Password</label>
<input type="password" class="form-control" id="newPassword" required minlength="4">
</div>
<div class="mb-3">
<label for="confirmPassword" class="form-label">Confirm New Password</label>
<input type="password" class="form-control" id="confirmPassword" required>
</div>
<div class="alert alert-danger" id="changePasswordError" style="display:none;"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="submitChangePassword()">
<i class="bi bi-check-lg me-1"></i>Change Password
</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="/static/js/app.js"></script>
<script src="/static/js/markdown-editor.js"></script>
<script src="/static/js/pdf-handler.js"></script>
<script src="/static/js/generation.js"></script>
<script src="/static/js/interactive-reader.js"></script>
</body>
</html>

345
templates/login.html Normal file
View File

@@ -0,0 +1,345 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login - Audiobook Maker Pro</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-color: #4f46e5;
--primary-hover: #4338ca;
}
* { box-sizing: border-box; }
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
padding: 24px;
}
.login-container {
width: 100%;
max-width: 420px;
}
.login-card {
background: white;
border-radius: 20px;
padding: 48px 40px;
box-shadow: 0 25px 60px rgba(0, 0, 0, 0.3);
animation: slideUp 0.4s ease;
}
@keyframes slideUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.login-header {
text-align: center;
margin-bottom: 36px;
}
.login-logo {
width: 64px;
height: 64px;
border-radius: 16px;
background: linear-gradient(135deg, var(--primary-color) 0%, #7c3aed 100%);
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 16px;
font-size: 1.75rem;
color: white;
}
.login-header h1 {
font-size: 1.5rem;
font-weight: 700;
color: #1e293b;
margin-bottom: 4px;
}
.login-header p {
color: #64748b;
font-size: 0.9rem;
margin: 0;
}
.form-label {
font-weight: 600;
color: #374151;
font-size: 0.85rem;
margin-bottom: 6px;
}
.form-control {
padding: 12px 16px;
border: 2px solid #e2e8f0;
border-radius: 10px;
font-size: 0.95rem;
transition: all 0.2s;
}
.form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}
.input-group-text {
background: #f8fafc;
border: 2px solid #e2e8f0;
border-right: none;
border-radius: 10px 0 0 10px;
color: #94a3b8;
}
.input-group .form-control {
border-left: none;
border-radius: 0 10px 10px 0;
}
.input-group:focus-within .input-group-text {
border-color: var(--primary-color);
}
.btn-login {
width: 100%;
padding: 12px;
background: linear-gradient(135deg, var(--primary-color) 0%, #7c3aed 100%);
border: none;
border-radius: 10px;
color: white;
font-weight: 600;
font-size: 1rem;
transition: all 0.2s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-login:hover {
transform: translateY(-1px);
box-shadow: 0 8px 25px rgba(79, 70, 229, 0.4);
color: white;
}
.btn-login:active {
transform: translateY(0);
}
.btn-login:disabled {
opacity: 0.7;
transform: none;
box-shadow: none;
}
.login-error {
background: #fef2f2;
border: 1px solid #fecaca;
color: #dc2626;
border-radius: 10px;
padding: 12px 16px;
font-size: 0.85rem;
display: none;
align-items: center;
gap: 8px;
margin-bottom: 20px;
animation: shakeError 0.4s ease;
}
.login-error.visible {
display: flex;
}
@keyframes shakeError {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-8px); }
75% { transform: translateX(8px); }
}
.login-footer {
text-align: center;
margin-top: 24px;
color: #94a3b8;
font-size: 0.78rem;
}
.password-toggle {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: #94a3b8;
cursor: pointer;
padding: 4px;
z-index: 5;
}
.password-toggle:hover {
color: #64748b;
}
.password-wrapper {
position: relative;
}
.password-wrapper .form-control {
padding-right: 44px;
}
.spinner-border-sm {
width: 1rem;
height: 1rem;
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-card">
<div class="login-header">
<div class="login-logo">
<i class="bi bi-soundwave"></i>
</div>
<h1>Audiobook Maker Pro</h1>
<p>Sign in to your account</p>
</div>
<div class="login-error" id="loginError">
<i class="bi bi-exclamation-triangle-fill"></i>
<span id="loginErrorText"></span>
</div>
<form id="loginForm" onsubmit="handleLogin(event)">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-person"></i></span>
<input type="text" class="form-control" id="username"
placeholder="Enter your username" required autofocus
autocomplete="username">
</div>
</div>
<div class="mb-4">
<label for="password" class="form-label">Password</label>
<div class="input-group">
<span class="input-group-text"><i class="bi bi-lock"></i></span>
<div class="password-wrapper" style="flex:1;">
<input type="password" class="form-control" id="password"
placeholder="Enter your password" required
autocomplete="current-password">
<button type="button" class="password-toggle" onclick="togglePassword()">
<i class="bi bi-eye" id="passwordToggleIcon"></i>
</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-login" id="loginBtn">
<span id="loginBtnText">Sign In</span>
<div class="spinner-border spinner-border-sm" id="loginSpinner" style="display:none;" role="status"></div>
</button>
</form>
<div class="login-footer">
<i class="bi bi-shield-lock me-1"></i>
Audiobook Maker Pro v3.1
</div>
</div>
</div>
<script>
function togglePassword() {
const input = document.getElementById('password');
const icon = document.getElementById('passwordToggleIcon');
if (input.type === 'password') {
input.type = 'text';
icon.classList.remove('bi-eye');
icon.classList.add('bi-eye-slash');
} else {
input.type = 'password';
icon.classList.remove('bi-eye-slash');
icon.classList.add('bi-eye');
}
}
async function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
const errorDiv = document.getElementById('loginError');
const errorText = document.getElementById('loginErrorText');
const loginBtn = document.getElementById('loginBtn');
const btnText = document.getElementById('loginBtnText');
const spinner = document.getElementById('loginSpinner');
// Hide previous error
errorDiv.classList.remove('visible');
// Show loading
loginBtn.disabled = true;
btnText.textContent = 'Signing in...';
spinner.style.display = 'inline-block';
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.error) {
errorText.textContent = data.error;
errorDiv.classList.add('visible');
loginBtn.disabled = false;
btnText.textContent = 'Sign In';
spinner.style.display = 'none';
// Shake the password field
document.getElementById('password').select();
return;
}
// Success — redirect
btnText.textContent = 'Redirecting...';
window.location.href = '/';
} catch (error) {
errorText.textContent = 'Network error. Please try again.';
errorDiv.classList.add('visible');
loginBtn.disabled = false;
btnText.textContent = 'Sign In';
spinner.style.display = 'none';
}
}
// Handle Enter key
document.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
document.getElementById('loginForm').requestSubmit();
}
});
</script>
</body>
</html>

516
templates/public_home.html Normal file
View File

@@ -0,0 +1,516 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audiobook Library</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@600;700;900&display=swap" rel="stylesheet">
<style>
* { box-sizing: border-box; }
body {
font-family: 'Inter', sans-serif;
margin: 0;
background: #f5e9d6;
min-height: 100vh;
color: #3e2723;
}
/* Header */
.library-header {
background: linear-gradient(135deg, #4a2c2a 0%, #6b4226 100%);
color: #f5e9d6;
padding: 24px 32px;
box-shadow: 0 4px 20px rgba(0,0,0,0.15);
position: sticky;
top: 0;
z-index: 100;
}
.header-container {
max-width: 1400px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
flex-wrap: wrap;
}
.library-title {
font-family: 'Playfair Display', serif;
font-weight: 900;
font-size: 1.8rem;
margin: 0;
display: flex;
align-items: center;
gap: 12px;
}
.library-title i { color: #f0c97a; }
.header-actions {
display: flex;
gap: 12px;
align-items: center;
}
.search-box {
background: rgba(255,255,255,0.1);
border: 1.5px solid rgba(255,255,255,0.25);
color: #f5e9d6;
border-radius: 24px;
padding: 8px 18px 8px 40px;
min-width: 240px;
font-size: 0.9rem;
position: relative;
}
.search-wrapper {
position: relative;
}
.search-wrapper i {
position: absolute;
left: 14px;
top: 50%;
transform: translateY(-50%);
color: rgba(245,233,214,0.6);
font-size: 0.9rem;
}
.search-box::placeholder { color: rgba(245,233,214,0.5); }
.search-box:focus {
outline: none;
border-color: #f0c97a;
background: rgba(255,255,255,0.15);
}
.btn-login-link {
background: rgba(255,255,255,0.15);
border: 1.5px solid rgba(255,255,255,0.3);
color: #f5e9d6;
padding: 8px 20px;
border-radius: 24px;
font-weight: 600;
font-size: 0.88rem;
text-decoration: none;
transition: all 0.2s;
display: flex;
align-items: center;
gap: 6px;
}
.btn-login-link:hover {
background: rgba(255,255,255,0.25);
color: #fff;
}
/* Bookcase container */
.bookcase-container {
max-width: 1400px;
margin: 0 auto;
padding: 40px 24px;
}
.library-intro {
text-align: center;
margin-bottom: 32px;
}
.library-intro h2 {
font-family: 'Playfair Display', serif;
font-size: 2.2rem;
font-weight: 700;
color: #4a2c2a;
margin-bottom: 8px;
}
.library-intro p {
color: #6b4226;
font-size: 1.05rem;
opacity: 0.85;
}
/* Bookcase shelf */
.bookcase {
background: linear-gradient(180deg, #c8a87b 0%, #a67c52 100%);
border-radius: 16px;
padding: 24px;
box-shadow: 0 12px 40px rgba(74,44,42,0.3), inset 0 2px 4px rgba(255,255,255,0.2);
position: relative;
}
.shelf {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 24px;
padding: 20px 16px 36px;
position: relative;
border-bottom: 8px solid #6b4226;
box-shadow: 0 6px 0 #5a3520, 0 8px 12px rgba(0,0,0,0.2);
margin-bottom: 24px;
border-radius: 6px;
}
.shelf:last-child {
margin-bottom: 0;
}
/* Book card */
.book-card {
cursor: pointer;
transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
transform-origin: bottom center;
position: relative;
}
.book-card:hover {
transform: translateY(-12px) scale(1.04);
}
.book-cover {
width: 100%;
aspect-ratio: 2 / 3;
border-radius: 4px 8px 8px 4px;
overflow: hidden;
box-shadow:
-2px 2px 0 rgba(0,0,0,0.1),
-4px 4px 0 rgba(0,0,0,0.08),
4px 6px 16px rgba(0,0,0,0.3);
position: relative;
background: linear-gradient(135deg, #2c3e50, #4a6278);
display: flex;
flex-direction: column;
justify-content: flex-end;
padding: 16px;
color: white;
}
.book-cover::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 4px;
background: linear-gradient(90deg, rgba(0,0,0,0.3), transparent);
}
.book-cover img {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: 0;
}
.book-cover-overlay {
position: absolute;
inset: 0;
background: linear-gradient(to bottom, transparent 40%, rgba(0,0,0,0.85));
z-index: 1;
}
.book-cover-content {
position: relative;
z-index: 2;
}
.book-cover-default {
background: linear-gradient(135deg, #2c3e50 0%, #4a6278 100%);
}
.book-cover-default::after {
content: '';
position: absolute;
top: 12px;
right: 12px;
left: 12px;
bottom: 12px;
border: 2px solid rgba(255,255,255,0.2);
border-radius: 2px;
z-index: 1;
}
.book-title {
font-family: 'Playfair Display', serif;
font-size: 1rem;
font-weight: 700;
line-height: 1.25;
margin-bottom: 4px;
text-shadow: 0 2px 4px rgba(0,0,0,0.5);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.book-author {
font-size: 0.75rem;
opacity: 0.85;
font-weight: 500;
font-style: italic;
}
.book-meta {
margin-top: 12px;
padding: 0 4px;
text-align: center;
}
.book-meta-title {
font-size: 0.85rem;
font-weight: 600;
color: #4a2c2a;
margin-bottom: 2px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.book-meta-stats {
font-size: 0.72rem;
color: #6b4226;
opacity: 0.7;
display: flex;
justify-content: center;
gap: 8px;
align-items: center;
}
.book-meta-stats i { font-size: 0.7rem; }
/* Empty state */
.empty-state {
text-align: center;
padding: 80px 24px;
color: #6b4226;
}
.empty-state i {
font-size: 4rem;
opacity: 0.4;
margin-bottom: 16px;
}
.empty-state h3 {
font-family: 'Playfair Display', serif;
font-weight: 700;
margin-bottom: 8px;
}
/* Loading */
.loading-state {
text-align: center;
padding: 80px 24px;
color: #6b4226;
}
/* Responsive */
@media (max-width: 768px) {
.header-container {
flex-direction: column;
align-items: stretch;
}
.header-actions {
justify-content: space-between;
}
.search-box {
min-width: 0;
width: 100%;
}
.shelf {
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 16px;
padding: 16px 12px 28px;
}
.library-intro h2 {
font-size: 1.6rem;
}
.bookcase {
padding: 16px;
}
}
@media (max-width: 480px) {
.shelf {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
}
.book-title { font-size: 0.85rem; }
.book-author { font-size: 0.7rem; }
}
/* Footer */
.library-footer {
text-align: center;
padding: 32px 24px;
color: #6b4226;
font-size: 0.85rem;
opacity: 0.7;
}
</style>
</head>
<body>
<header class="library-header">
<div class="header-container">
<h1 class="library-title">
<i class="bi bi-book-half"></i>
Audiobook Library
</h1>
<div class="header-actions">
<div class="search-wrapper">
<i class="bi bi-search"></i>
<input type="text" class="search-box" id="searchInput"
placeholder="Search books..." oninput="filterBooks(this.value)">
</div>
<a href="/login" class="btn-login-link">
<i class="bi bi-person-circle"></i>
<span>Sign In</span>
</a>
</div>
</div>
</header>
<main class="bookcase-container">
<div class="library-intro">
<h2>Discover Stories That Speak</h2>
<p>Browse our collection of interactive audiobooks</p>
</div>
<div id="bookcaseContainer">
<div class="loading-state">
<div class="spinner-border" role="status" style="color: #6b4226;"></div>
<p class="mt-3">Loading library...</p>
</div>
</div>
</main>
<footer class="library-footer">
<p>Powered by Audiobook Maker Pro v4.2</p>
</footer>
<script>
let allBooks = [];
async function loadBooks() {
try {
const resp = await fetch('/api/public/books');
const data = await resp.json();
allBooks = data.books || [];
renderBookcase(allBooks);
} catch (e) {
document.getElementById('bookcaseContainer').innerHTML = `
<div class="empty-state">
<i class="bi bi-exclamation-circle"></i>
<h3>Failed to load library</h3>
<p>Please refresh the page to try again.</p>
</div>
`;
}
}
function renderBookcase(books) {
const container = document.getElementById('bookcaseContainer');
if (!books || books.length === 0) {
container.innerHTML = `
<div class="empty-state">
<i class="bi bi-book"></i>
<h3>No books yet</h3>
<p>The library is being curated. Check back soon!</p>
</div>
`;
return;
}
// Group books into shelves (6 books per shelf approx)
const booksPerShelf = 6;
const shelves = [];
for (let i = 0; i < books.length; i += booksPerShelf) {
shelves.push(books.slice(i, i + booksPerShelf));
}
let html = '<div class="bookcase">';
for (const shelf of shelves) {
html += '<div class="shelf">';
for (const book of shelf) {
html += renderBookCard(book);
}
html += '</div>';
}
html += '</div>';
container.innerHTML = html;
}
function renderBookCard(book) {
const thumbnailHtml = book.thumbnail_data
? `<img src="data:image/${book.thumbnail_format};base64,${book.thumbnail_data}" alt="${escapeHtml(book.name)}">
<div class="book-cover-overlay"></div>`
: '';
const coverClass = book.thumbnail_data ? '' : 'book-cover-default';
const author = book.author || 'Unknown Author';
return `
<div class="book-card" onclick="openBook(${book.id})" title="${escapeHtml(book.name)}">
<div class="book-cover ${coverClass}">
${thumbnailHtml}
<div class="book-cover-content">
<div class="book-title">${escapeHtml(book.name)}</div>
<div class="book-author">by ${escapeHtml(author)}</div>
</div>
</div>
<!--<div class="book-meta">
<div class="book-meta-stats">
<span><i class="bi bi-bookmark"></i> ${book.chapter_count} ch</span>
<span><i class="bi bi-eye"></i> ${book.view_count}</span>
</div>
</div>-->
</div>
`;
}
function openBook(bookId) {
window.location.href = `/read/${bookId}`;
}
function filterBooks(query) {
query = query.toLowerCase().trim();
if (!query) {
renderBookcase(allBooks);
return;
}
const filtered = allBooks.filter(b =>
b.name.toLowerCase().includes(query) ||
(b.author && b.author.toLowerCase().includes(query)) ||
(b.description && b.description.toLowerCase().includes(query))
);
renderBookcase(filtered);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text || '';
return div.innerHTML;
}
loadBooks();
</script>
</body>
</html>

View File

@@ -0,0 +1,827 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audiobook Reader</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Lora:ital,wght@0,400..700;1,400..700&family=Poppins:wght@500;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
@keyframes spin { to { transform: rotate(360deg); } }
html { scroll-behavior: smooth; }
body {
background-image: linear-gradient(to top, #f3e7e9 0%, #e3eeff 99%, #e3eeff 100%);
color: #1f2937; font-family: "Lora", serif; margin: 0;
}
.top-nav {
background: rgba(255,255,255,0.9);
backdrop-filter: blur(12px);
padding: 12px 24px;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
display: flex;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 50;
}
.back-btn {
display: flex;
align-items: center;
gap: 8px;
color: #4a2c2a;
text-decoration: none;
font-weight: 600;
font-family: 'Inter', sans-serif;
font-size: 0.9rem;
padding: 8px 14px;
border-radius: 8px;
transition: background 0.2s;
}
.back-btn:hover { background: rgba(74,44,42,0.08); color: #4a2c2a; }
.story-title { font-family: "Poppins", sans-serif; font-weight: 700; font-size: 2.5rem; color: #111827; }
.story-subtitle { font-family: "Poppins", sans-serif; color: #4b5563; font-weight: 500; font-size: 1.1rem; }
.main-content-card {
background-color: rgba(255,255,255,0.9); backdrop-filter: blur(12px);
border-radius: 1rem; padding: 3rem 4rem; box-shadow: 0 10px 35px rgba(0,0,0,0.08);
border: 1px solid rgba(255,255,255,0.2); max-width: 1400px; margin: 0 auto;
animation: fadeIn 0.5s ease-in-out;
}
.reader-layout { display: flex; gap: 32px; align-items: flex-start; text-align: left; }
.document-outline {
width: 280px; flex-shrink: 0; position: sticky; top: 80px;
background: white; border-radius: 12px; padding: 20px;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);
border: 1px solid #e2e8f0; max-height: calc(100vh - 100px); overflow-y: auto;
}
.outline-title {
font-family: "Poppins", sans-serif; font-weight: 700; font-size: 0.95rem;
color: #64748b; text-transform: uppercase; margin-bottom: 16px;
border-bottom: 1px solid #e2e8f0; padding-bottom: 12px;
letter-spacing: 0.5px;
}
.outline-list { list-style: none; padding: 0; margin: 0; }
.outline-list li {
padding: 10px 14px; font-size: 0.9rem; color: #334155; cursor: pointer;
border-radius: 8px; transition: all 0.2s; white-space: nowrap;
overflow: hidden; text-overflow: ellipsis; font-family: "Inter", sans-serif;
margin-bottom: 4px;
border-left: 3px solid transparent;
}
.outline-list li:hover { background: #f8fafc; color: #4f46e5; }
.outline-list li.active {
background: #e0e7ff;
color: #3730a3;
font-weight: 600;
border-left: 3px solid #4f46e5;
padding-left: 11px;
}
.reader-content-area { flex: 1; min-width: 0; }
.story-text-container { font-size: 32px; line-height: 2.1; color: #1f2937; cursor: pointer; }
.story-text-container h1, .story-text-container h2, .story-text-container h3 {
font-family: "Poppins", sans-serif; color: #111827; line-height: 1.8;
margin-top: 1.5em; margin-bottom: 0.8em;
}
.story-text-container p { margin-bottom: 1.2em; }
.story-text-container img { max-width: 100%; height: auto; border-radius: 8px; margin: 16px auto; display: block; }
.block-loading-spinner {
display: inline-flex; align-items: center; gap: 8px;
color: #6b7280; font-size: 0.9rem; font-family: "Inter", sans-serif;
padding: 8px 0;
}
.block-loading-spinner::before {
content: ''; width: 16px; height: 16px;
border: 2px solid #e2e8f0; border-top-color: #5753c9;
border-radius: 50%; animation: spin 0.8s linear infinite;
}
.word { transition: all 0.15s ease; border-radius: 3px; cursor: pointer; }
.word:hover { background-color: #f1f5f9; }
.current-sentence-bg {
-webkit-box-decoration-break: clone; box-decoration-break: clone;
background-color: #e0e7ff; padding: 0.1em 0.25em; margin: 0 -0.2em; border-radius: 8px;
}
.current-word { color: #3d4e81; text-decoration: underline; text-decoration-thickness: 3px; text-underline-offset: 3px; font-weight: 700; }
.story-image-block { text-align: center; margin: 24px 0; }
.story-image-block img { max-width: 100%; height: auto; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
/* Floating Player Button — Fixed RIGHT side */
#floating-player-btn {
position: fixed;
top: 5rem;
right: 24px;
height: 56px;
min-width: 56px;
padding: 0 24px;
border-radius: 30px;
background-image: linear-gradient(45deg, #3d4e81 0%, #5753c9 50%, #6e78da 100%);
border: none;
color: white;
box-shadow: 0 8px 25px rgba(0,0,0,0.3);
display: none;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 60;
transition: transform 0.2s, opacity 0.3s, width 0.3s, padding 0.3s, border-radius 0.3s;
gap: 8px;
}
#floating-player-btn.visible { display: flex; }
#floating-player-btn:hover { transform: scale(1.05); }
#floating-player-btn:active { transform: scale(0.95); }
#floating-player-btn svg { width: 24px; height: 24px; }
#fp-start-text {
font-weight: 600;
font-family: "Poppins", sans-serif;
font-size: 1rem;
}
#floating-player-btn.active-mode {
width: 56px;
padding: 0;
border-radius: 50%;
gap: 0;
}
#floating-player-btn.active-mode #fp-start-text { display: none; }
#floating-player-btn.loading { background: linear-gradient(45deg, #6b7280, #9ca3af); cursor: wait; }
#fp-loading-spinner {
width: 24px; height: 24px;
border: 3px solid rgba(255,255,255,0.3); border-top-color: white;
border-radius: 50%; animation: spin 0.8s linear infinite;
display: none;
}
#floating-player-btn.loading #fp-loading-spinner { display: block; }
#floating-player-btn.loading #fp-play-icon,
#floating-player-btn.loading #fp-pause-icon,
#floating-player-btn.loading #fp-start-text { display: none !important; }
.reader-toast {
position: fixed; bottom: 2rem; left: 50%; transform: translateX(-50%);
background: rgba(30, 41, 59, 0.95); color: white;
padding: 12px 24px; border-radius: 24px;
font-family: "Inter", sans-serif; font-size: 0.9rem;
box-shadow: 0 8px 24px rgba(0,0,0,0.2);
z-index: 1100; opacity: 0; transition: opacity 0.3s;
pointer-events: none; display: flex; align-items: center; gap: 8px;
}
.reader-toast.visible { opacity: 1; }
.reader-toast .spinner {
width: 14px; height: 14px;
border: 2px solid rgba(255,255,255,0.3); border-top-color: white;
border-radius: 50%; animation: spin 0.8s linear infinite;
}
/* Block highlight on outline click */
.story-block.highlight-section,
.story-image-block.highlight-section {
animation: highlightPulse 2s ease-out;
border-radius: 12px;
}
@keyframes highlightPulse {
0% {
background-color: rgba(79, 70, 229, 0.18);
box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.25);
}
100% {
background-color: transparent;
box-shadow: 0 0 0 0 transparent;
}
}
@media (max-width: 992px) {
.reader-layout { flex-direction: column; }
.document-outline { width: 100%; position: relative; top: 0; max-height: 300px; }
}
@media (max-width: 768px) {
.main-content-card { padding: 1.5rem; }
.story-text-container { font-size: 22px; line-height: 1.9; }
#floating-player-btn {
top: auto;
bottom: 1rem;
right: 1rem;
height: 50px;
min-width: 50px;
}
#floating-player-btn.active-mode { width: 50px; }
}
</style>
</head>
<body>
<nav class="top-nav">
<a href="/home" class="back-btn">
<svg width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
<path d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
</svg>
Back to Library
</a>
</nav>
<button id="floating-player-btn">
<svg id="fp-play-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
<svg id="fp-pause-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" style="display:none;"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>
<span id="fp-start-text">Start</span>
<div id="fp-loading-spinner"></div>
</button>
<div id="reader-toast" class="reader-toast">
<div class="spinner"></div>
<span id="reader-toast-text">Loading…</span>
</div>
<div class="container-fluid my-4 px-md-5">
<main id="main-content" class="main-content-card">
<header class="text-center mb-5" id="main-header">
<h1 class="story-title" id="book-title">Loading...</h1>
<p class="story-subtitle" id="book-subtitle">Please wait</p>
</header>
<div class="reader-layout">
<aside class="document-outline" id="story-nav" style="display: none;">
<h6 class="outline-title">Table of Sections</h6>
<ul class="outline-list" id="story-nav-list"></ul>
</aside>
<div class="reader-content-area">
<div id="stories-main-container"></div>
</div>
</div>
</main>
</div>
<script>
/**
* Public Reader — Smart Preload Architecture (v3)
*
* Loading Strategy:
* 1. TEXT + TIMESTAMPS: loaded eagerly from /api/public/books/<id> in single batch.
* 2. AUDIO: base64 → Blob URL conversion is DEFERRED until needed.
* 3. Smart preload: when block N plays, preload blob URLs for N+1, N+2.
* At 70% mark of N, ensure N+1 is ready (safety net).
* 4. Memory cap: keep at most MAX_AUDIO_LOADED blob URLs alive;
* revoke distant past audio to free browser memory.
*
* Scroll Strategy:
* - Manual navigation (Start / outline click / word click): scroll to block.
* - Auto-advance (audio ended → next): NO block scroll — word highlighter carries user.
*/
const pathParts = window.location.pathname.split('/');
const BOOK_ID = parseInt(pathParts[pathParts.length - 1], 10);
document.addEventListener("DOMContentLoaded", async () => {
const mainContainer = document.getElementById("stories-main-container");
const floatingPlayerBtn = document.getElementById("floating-player-btn");
const storyNav = document.getElementById("story-nav");
const storyNavList = document.getElementById("story-nav-list");
const toastEl = document.getElementById("reader-toast");
const toastText = document.getElementById("reader-toast-text");
let storyInstances = [];
let currentlyPlayingInstance = null;
let currentlyPlayingIndex = -1;
let hasStarted = false;
let navObserver = null;
// Tunables (matches reader_templates/index.html)
const PRELOAD_AHEAD = 2;
const MID_PRELOAD_THRESHOLD = 0.7;
const MAX_AUDIO_LOADED = 5;
const KEEP_BEHIND = 1;
floatingPlayerBtn.addEventListener("click", handleFloatingBtnClick);
mainContainer.addEventListener("click", handleTextClick);
// ===================================================
// UI Helpers
// ===================================================
function showToast(msg) { toastText.textContent = msg; toastEl.classList.add("visible"); }
function hideToast() { toastEl.classList.remove("visible"); }
function setButtonLoading(b) { floatingPlayerBtn.classList.toggle("loading", b); }
function updateFloatingButton(state) {
const fpPauseIcon = document.getElementById("fp-pause-icon");
const fpPlayIcon = document.getElementById("fp-play-icon");
if (hasStarted) {
floatingPlayerBtn.classList.add("active-mode");
}
if (state === "playing") {
fpPauseIcon.style.display = "block";
fpPlayIcon.style.display = "none";
} else {
fpPauseIcon.style.display = "none";
fpPlayIcon.style.display = "block";
}
}
// ===================================================
// INITIAL LOAD
// ===================================================
try {
const resp = await fetch(`/api/public/books/${BOOK_ID}`);
if (!resp.ok) throw new Error('Failed to load book');
const book = await resp.json();
document.getElementById("book-title").textContent = book.name;
document.getElementById("book-subtitle").textContent = book.author ? `by ${book.author}` : 'An interactive audiobook';
document.title = book.name + ' - Audiobook Reader';
// Build flat list of blocks across chapters
let globalIdx = 0;
for (const chapter of book.chapters) {
let firstInChapter = true;
for (const block of chapter.blocks) {
const isImage = block.block_type === 'image' ||
(block.content && block.content.trim().startsWith('![') && block.content.includes(']('));
if (isImage) {
const imgBlockId = `img-block-${globalIdx}`;
let imgHtml = `<div id="${imgBlockId}" class="story-image-block" data-chapter="${chapter.chapter_number}">`;
if (block.images && block.images.length > 0) {
for (const img of block.images) {
if (img.data) {
imgHtml += `<img src="data:image/${img.format};base64,${img.data}" alt="Image" loading="lazy">`;
}
}
}
imgHtml += '</div>';
mainContainer.insertAdjacentHTML("beforeend", imgHtml);
if (firstInChapter) addOutlineEntry(chapter.title, chapter.chapter_number, imgBlockId);
firstInChapter = false;
globalIdx++;
continue;
}
if (!block.audio_data) continue;
const blockId = `story-block-${globalIdx}`;
if (firstInChapter) addOutlineEntry(chapter.title, chapter.chapter_number, blockId);
firstInChapter = false;
mainContainer.insertAdjacentHTML("beforeend", `
<div id="${blockId}" class="story-block mt-4" data-instance-index="${storyInstances.length}" data-chapter="${chapter.chapter_number}">
<article class="story-text-container"></article>
<audio class="audio-player" preload="none" style="display:none;"></audio>
</div>
`);
storyInstances.push({
index: storyInstances.length,
blockEl: document.getElementById(blockId),
block: block,
chapter: chapter,
audio: null,
audioUrl: null, // blob URL ref for cleanup
audioReady: false,
audioLoadingPromise: null,
midPreloadTriggered: false,
wordSpans: [],
wordMap: [],
sentenceData: [],
animFrameId: null,
lastWordSpan: null,
lastSentenceSpans: []
});
globalIdx++;
}
}
// Render text + sync for each instance (cheap, in-memory)
for (const inst of storyInstances) {
renderMarkdownInto(inst);
smartSync(inst);
}
storyNav.style.display = 'block';
floatingPlayerBtn.classList.add("visible");
setupNavObserver();
} catch (e) {
console.error(e);
mainContainer.innerHTML = `<p class="text-center text-danger">Error loading book: ${e.message}</p>`;
}
// ===================================================
// Outline / Navigation
// ===================================================
function addOutlineEntry(title, chapter, targetId) {
const li = document.createElement("li");
li.textContent = title;
li.title = title;
li.dataset.chapter = chapter;
li.dataset.targetId = targetId;
li.onclick = () => {
const target = document.getElementById(targetId);
if (!target) return;
const offset = target.getBoundingClientRect().top + window.pageYOffset - 80;
window.scrollTo({ top: offset, behavior: 'smooth' });
target.classList.remove('highlight-section');
void target.offsetWidth;
target.classList.add('highlight-section');
setTimeout(() => target.classList.remove('highlight-section'), 2000);
storyNavList.querySelectorAll('li').forEach(l => l.classList.remove('active'));
li.classList.add('active');
};
storyNavList.appendChild(li);
}
function setupNavObserver() {
if (navObserver) navObserver.disconnect();
navObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const chapter = entry.target.dataset.chapter;
if (chapter) {
storyNavList.querySelectorAll('li').forEach(l => l.classList.remove('active'));
const active = storyNavList.querySelector(`li[data-chapter='${chapter}']`);
if (active) active.classList.add('active');
}
}
});
}, { threshold: 0.3, rootMargin: '-80px 0px -40% 0px' });
document.querySelectorAll('.story-block, .story-image-block').forEach(b => navObserver.observe(b));
}
// ===================================================
// Render & Sync
// ===================================================
function renderMarkdownInto(inst) {
const container = inst.blockEl.querySelector(".story-text-container");
container.innerHTML = "";
inst.wordSpans = [];
const div = document.createElement("div");
div.innerHTML = marked.parse(inst.block.content, { breaks: true, gfm: true });
(function processNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const words = node.textContent.split(/(\s+)/);
const frag = document.createDocumentFragment();
words.forEach(part => {
if (part.trim().length > 0) {
const span = document.createElement("span");
span.className = "word";
span.textContent = part;
inst.wordSpans.push(span);
frag.appendChild(span);
} else frag.appendChild(document.createTextNode(part));
});
node.parentNode.replaceChild(frag, node);
} else if (node.nodeType === Node.ELEMENT_NODE) {
Array.from(node.childNodes).forEach(processNode);
}
})(div);
while (div.firstChild) container.appendChild(div.firstChild);
}
function smartSync(inst) {
const transcription = inst.block.transcription || [];
inst.wordMap = new Array(inst.wordSpans.length).fill(undefined);
let ai = 0;
inst.wordSpans.forEach((span, i) => {
const tw = span.textContent.toLowerCase().replace(/[^\w]/g, "");
for (let o = 0; o < 5; o++) {
if (ai + o >= transcription.length) break;
const aw = transcription[ai + o].word.toLowerCase().replace(/[^\w]/g, "");
if (tw === aw) { inst.wordMap[i] = ai + o; ai += o + 1; return; }
}
});
inst.sentenceData = [];
let buf = [], si = 0;
inst.wordSpans.forEach((s, i) => {
buf.push(s);
if (/[.!?]["'\u201D\u2019]?$/.test(s.textContent.trim())) {
let sT = 0, eT = 0;
for (let k = si; k <= i; k++) if (inst.wordMap[k] !== undefined) { sT = transcription[inst.wordMap[k]].start; break; }
for (let k = i; k >= si; k--) if (inst.wordMap[k] !== undefined) { eT = transcription[inst.wordMap[k]].end; break; }
if (eT > sT) inst.sentenceData.push({ spans: [...buf], startTime: sT, endTime: eT });
buf = []; si = i + 1;
}
});
if (buf.length > 0) {
let sT = 0, eT = 0;
for (let k = si; k < inst.wordSpans.length; k++) if (inst.wordMap[k] !== undefined) { sT = transcription[inst.wordMap[k]].start; break; }
for (let k = inst.wordSpans.length - 1; k >= si; k--) if (inst.wordMap[k] !== undefined) { eT = transcription[inst.wordMap[k]].end; break; }
if (eT > sT) inst.sentenceData.push({ spans: [...buf], startTime: sT, endTime: eT });
}
}
// ===================================================
// AUDIO LAZY LOADING + MEMORY MANAGEMENT
// ===================================================
function ensureAudioLoaded(inst) {
if (inst.audioReady && inst.audio) return Promise.resolve(inst);
if (inst.audioLoadingPromise) return inst.audioLoadingPromise;
inst.audioLoadingPromise = new Promise((resolve, reject) => {
if (!inst.block.audio_data) {
inst.audioLoadingPromise = null;
return reject(new Error('No audio data'));
}
try {
const audio = inst.blockEl.querySelector('.audio-player');
const blob = base64ToBlob(inst.block.audio_data, `audio/${inst.block.audio_format || 'mp3'}`);
const url = URL.createObjectURL(blob);
const onCanPlay = () => {
audio.removeEventListener('error', onError);
inst.audio = audio;
inst.audioUrl = url;
inst.audioReady = true;
wireAudioEvents(inst);
resolve(inst);
};
const onError = () => {
audio.removeEventListener('canplay', onCanPlay);
try { URL.revokeObjectURL(url); } catch (e) {}
inst.audioLoadingPromise = null;
reject(new Error('Audio failed to load'));
};
audio.addEventListener('canplay', onCanPlay, { once: true });
audio.addEventListener('error', onError, { once: true });
audio.preload = 'auto';
audio.src = url;
audio.load();
} catch (err) {
inst.audioLoadingPromise = null;
reject(err);
}
});
return inst.audioLoadingPromise;
}
function wireAudioEvents(inst) {
const audio = inst.audio;
audio.addEventListener('play', () => {
startHighlightLoop(inst);
updateFloatingButton('playing');
});
audio.addEventListener('pause', () => {
stopHighlightLoop(inst);
updateFloatingButton('paused');
});
audio.addEventListener('ended', () => {
stopHighlightLoop(inst);
clearHighlights(inst);
const nextIdx = inst.index + 1;
if (nextIdx < storyInstances.length) {
playInstance(nextIdx, 0, { autoAdvance: true });
} else {
currentlyPlayingInstance = null;
currentlyPlayingIndex = -1;
updateFloatingButton('paused');
}
});
// Mid-play safety net
audio.addEventListener('timeupdate', () => {
if (inst.midPreloadTriggered) return;
if (!audio.duration || isNaN(audio.duration)) return;
if ((audio.currentTime / audio.duration) >= MID_PRELOAD_THRESHOLD) {
inst.midPreloadTriggered = true;
const nextIdx = inst.index + 1;
if (nextIdx < storyInstances.length) {
ensureAudioLoaded(storyInstances[nextIdx]).catch(() => {});
}
}
});
}
/**
* Preload N audio blocks ahead (fire-and-forget).
*/
function preloadAhead(fromIndex) {
for (let i = 1; i <= PRELOAD_AHEAD; i++) {
const idx = fromIndex + i;
if (idx >= storyInstances.length) break;
ensureAudioLoaded(storyInstances[idx]).catch(() => {});
}
}
/**
* Memory management: keep only sliding window of audio elements loaded.
* Window = [currentIndex - KEEP_BEHIND, currentIndex + PRELOAD_AHEAD]
* Bounded to MAX_AUDIO_LOADED total.
*/
function pruneLoadedAudio(currentIndex) {
const loaded = storyInstances.filter(i => i.audioReady && i.audio && i.audioUrl);
if (loaded.length <= MAX_AUDIO_LOADED) return;
const keepLow = currentIndex - KEEP_BEHIND;
const keepHigh = currentIndex + PRELOAD_AHEAD;
const candidates = loaded
.filter(inst => inst !== currentlyPlayingInstance)
.map(inst => ({
inst,
inWindow: inst.index >= keepLow && inst.index <= keepHigh,
distance: Math.abs(inst.index - currentIndex)
}))
.sort((a, b) => {
if (a.inWindow !== b.inWindow) return a.inWindow ? 1 : -1;
return b.distance - a.distance;
});
let toEvict = loaded.length - MAX_AUDIO_LOADED;
for (const c of candidates) {
if (toEvict <= 0) break;
releaseAudio(c.inst);
toEvict--;
}
}
function releaseAudio(inst) {
if (!inst.audio) return;
try {
inst.audio.pause();
inst.audio.removeAttribute('src');
inst.audio.load();
} catch (e) { /* ignore */ }
if (inst.audioUrl) {
try { URL.revokeObjectURL(inst.audioUrl); } catch (e) {}
inst.audioUrl = null;
}
inst.audioReady = false;
inst.audioLoadingPromise = null;
inst.midPreloadTriggered = false;
}
// ===================================================
// PLAYBACK
// ===================================================
async function playInstance(idx, ts = 0, opts = {}) {
if (idx < 0 || idx >= storyInstances.length) return;
const inst = storyInstances[idx];
const isAutoAdvance = opts.autoAdvance === true;
if (currentlyPlayingInstance && currentlyPlayingInstance !== inst) {
stopAndResetInstance(currentlyPlayingInstance);
}
currentlyPlayingInstance = inst;
currentlyPlayingIndex = idx;
hasStarted = true;
inst.midPreloadTriggered = false;
const needsLoad = !inst.audioReady;
if (needsLoad) {
setButtonLoading(true);
showToast("Loading audio…");
}
try {
await ensureAudioLoaded(inst);
if (needsLoad) {
hideToast();
setButtonLoading(false);
}
inst.audio.currentTime = ts;
await inst.audio.play();
updateFloatingButton('playing');
// Block-level scroll ONLY for manual navigation
if (!isAutoAdvance) {
const rect = inst.blockEl.getBoundingClientRect();
if (rect.top < 0 || rect.top > window.innerHeight * 0.6) {
inst.blockEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}
preloadAhead(idx);
pruneLoadedAudio(idx);
} catch (err) {
console.error(err);
setButtonLoading(false);
showToast("Failed to load audio. Tap again to retry.");
setTimeout(hideToast, 3000);
updateFloatingButton('paused');
}
}
function stopAndResetInstance(inst) {
if (inst.audio) {
try {
inst.audio.pause();
inst.audio.currentTime = 0;
} catch (e) {}
}
stopHighlightLoop(inst);
clearHighlights(inst);
}
function handleFloatingBtnClick() {
if (!hasStarted) { playInstance(0, 0); return; }
if (currentlyPlayingInstance && currentlyPlayingInstance.audio) {
const audio = currentlyPlayingInstance.audio;
if (audio.paused) {
audio.play().catch(console.error);
updateFloatingButton('playing');
} else {
audio.pause();
updateFloatingButton('paused');
}
} else {
playInstance(0, 0);
}
}
function handleTextClick(e) {
const wordSpan = e.target.closest('.word');
if (!wordSpan) return;
const block = e.target.closest('.story-block');
if (!block) return;
const idx = parseInt(block.dataset.instanceIndex, 10);
const inst = storyInstances[idx];
if (!inst) return;
const wordIdx = inst.wordSpans.indexOf(wordSpan);
const aiIdx = inst.wordMap[wordIdx];
if (aiIdx === undefined) return;
playInstance(idx, inst.block.transcription[aiIdx].start);
}
// ===================================================
// Highlighting
// ===================================================
function startHighlightLoop(inst) {
cancelAnimationFrame(inst.animFrameId);
inst.animFrameId = requestAnimationFrame(() => highlightLoop(inst));
}
function stopHighlightLoop(inst) { cancelAnimationFrame(inst.animFrameId); }
function highlightLoop(inst) {
if (!inst.audio || inst.audio.paused) return;
const t = inst.audio.currentTime;
const transcription = inst.block.transcription || [];
const ai = transcription.findIndex(w => t >= w.start && t < w.end);
if (ai !== -1) {
const ti = inst.wordMap.findIndex(i => i === ai);
if (ti !== -1) {
const sp = inst.wordSpans[ti];
if (sp !== inst.lastWordSpan) {
if (inst.lastWordSpan) inst.lastWordSpan.classList.remove('current-word');
sp.classList.add('current-word');
const r = sp.getBoundingClientRect();
if (r.top < window.innerHeight * 0.2 || r.bottom > window.innerHeight * 0.8) {
sp.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
inst.lastWordSpan = sp;
}
}
}
const sent = inst.sentenceData.find(s => t >= s.startTime && t <= s.endTime);
if (sent && sent.spans !== inst.lastSentenceSpans) {
inst.lastSentenceSpans.forEach(s => s.classList.remove('current-sentence-bg'));
sent.spans.forEach(s => s.classList.add('current-sentence-bg'));
inst.lastSentenceSpans = sent.spans;
}
inst.animFrameId = requestAnimationFrame(() => highlightLoop(inst));
}
function clearHighlights(inst) {
if (inst.lastWordSpan) inst.lastWordSpan.classList.remove('current-word');
inst.lastSentenceSpans.forEach(s => s.classList.remove('current-sentence-bg'));
inst.lastWordSpan = null;
inst.lastSentenceSpans = [];
}
// ===================================================
// Utility
// ===================================================
function base64ToBlob(b64, mime) {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) arr[i] = bin.charCodeAt(i);
return new Blob([arr], { type: mime });
}
});
</script>
</body>
</html>