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

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>