856 lines
37 KiB
HTML
Executable File
856 lines
37 KiB
HTML
Executable File
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<title>Interactive 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>
|
|
|
|
<script>
|
|
const INJECTED_MANIFEST = /*{{MANIFEST_DATA}}*/ null;
|
|
</script>
|
|
|
|
<style>
|
|
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
|
|
@keyframes spin { to { transform: rotate(360deg); } }
|
|
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
|
|
|
html { scroll-behavior: smooth; }
|
|
body {
|
|
background-image: linear-gradient(to top, #f3e7e9 0%, #e3eeff 99%, #e3eeff 100%);
|
|
color: #1f2937; font-family: "Lora", serif;
|
|
}
|
|
.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: 40px;
|
|
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 - 80px); overflow-y: auto;
|
|
opacity: 0; transform: translateX(-20px);
|
|
transition: opacity 0.4s ease-out, transform 0.4s ease-out;
|
|
}
|
|
.document-outline.visible { opacity: 1; transform: translateX(0); }
|
|
|
|
.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;
|
|
display: flex; align-items: center; gap: 8px; 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;
|
|
}
|
|
.outline-list li:hover { background: #f8fafc; color: #4f46e5; }
|
|
.outline-list li.active { background: #e0e7ff; color: #3730a3; font-weight: 600; }
|
|
|
|
.reader-content-area { flex: 1; min-width: 0; }
|
|
.story-text-container { font-size: 36px; 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 h1 { font-size: 2.2em; }
|
|
.story-text-container h2 { font-size: 1.8em; }
|
|
.story-text-container h3 { font-size: 1.5em; }
|
|
.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; }
|
|
|
|
.word { transition: all 0.15s ease; border-radius: 3px; }
|
|
.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); }
|
|
|
|
.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;
|
|
}
|
|
|
|
#floating-player-btn {
|
|
position: fixed; top: 2rem; height: 60px; min-width: 60px; padding: 0 24px;
|
|
border-radius: 30px; background-image: linear-gradient(45deg, #3d4e81 0%, #5753c9 50%, #6e78da 100%);
|
|
background-size: 200% auto; 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: 1050;
|
|
transition: transform 0.2s, opacity 0.3s, width 0.3s, padding 0.3s, border-radius 0.3s;
|
|
opacity: 0; transform: scale(0.8);
|
|
}
|
|
#floating-player-btn.visible { display: flex; opacity: 1; transform: scale(1); }
|
|
#floating-player-btn:hover { transform: scale(1.05); }
|
|
#floating-player-btn:active { transform: scale(0.95); }
|
|
#floating-player-btn svg { width: 28px; height: 28px; }
|
|
#fp-start-text { font-weight: 600; margin-right: 10px; font-family: "Poppins", sans-serif; font-size: 1.1rem; }
|
|
#floating-player-btn.active-mode { width: 60px; padding: 0; border-radius: 50%; }
|
|
#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;
|
|
}
|
|
|
|
@media (max-width: 992px) {
|
|
.reader-layout { flex-direction: column; }
|
|
.document-outline { width: 100%; position: relative; top: 0; max-height: 300px; margin-bottom: 24px; }
|
|
}
|
|
@media (max-width: 768px) {
|
|
.main-content-card { padding: 1.5rem; }
|
|
.story-text-container { font-size: 24px; line-height: 1.9; }
|
|
#floating-player-btn { top: 1rem; right: 1rem !important; height: 50px; min-width: 50px; }
|
|
#floating-player-btn.active-mode { width: 50px; }
|
|
}
|
|
|
|
.highlight-section { animation: highlightPulse 2s ease-out; }
|
|
@keyframes highlightPulse {
|
|
0% { background-color: rgba(79, 70, 229, 0.15); border-left: 4px solid #4f46e5; border-radius: 8px; }
|
|
100% { background-color: transparent; border-left: 4px solid transparent; border-radius: 8px; }
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<button id="floating-player-btn">
|
|
<span id="fp-start-text">Start</span>
|
|
<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>
|
|
<svg id="fp-play-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" style="display:none;"><path d="M8 5v14l11-7z"/></svg>
|
|
<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-5 px-md-5">
|
|
<main id="main-content" class="main-content-card">
|
|
<header class="text-center mb-5" id="main-header">
|
|
<h1 class="story-title">Interactive Reader</h1>
|
|
<p class="story-subtitle">Loading book...</p>
|
|
</header>
|
|
<div id="resume-alert" class="alert alert-info d-flex justify-content-between align-items-center" style="display:none;">
|
|
<span>Welcome back! Resume from where you left off?</span>
|
|
<button id="resume-btn" class="btn btn-primary btn-sm">Resume Playback</button>
|
|
</div>
|
|
|
|
<div class="reader-layout">
|
|
<aside class="document-outline" id="story-nav" style="display: none;">
|
|
<h6 class="outline-title">
|
|
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
|
|
<path fill-rule="evenodd" d="M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z"/>
|
|
</svg>
|
|
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>
|
|
/**
|
|
* Interactive Reader — Smart Preload Architecture (v3)
|
|
*
|
|
* Loading Strategy:
|
|
* 1. TEXT + JSON: eager parallel batch (small files, fast).
|
|
* 2. AUDIO: preload="none" by default → no auto-download of 200+ MP3s.
|
|
* 3. Smart preload: when block N starts playing, preload N+1, N+2.
|
|
* At 70% through N's audio, ensure N+1 is ready (safety net).
|
|
* 4. Memory management: keep at most MAX_AUDIO_LOADED audio sources in
|
|
* memory. When user moves forward, release distant past audio.
|
|
*
|
|
* Scroll Strategy:
|
|
* - Manual navigation (Start / outline / word click): scroll block to top.
|
|
* - Auto-advance (audio ended → next block): NO block scroll, let the
|
|
* word highlighter smoothly carry the user. Prevents jarring jumps.
|
|
*/
|
|
document.addEventListener("DOMContentLoaded", async () => {
|
|
const mainContainer = document.getElementById("stories-main-container");
|
|
const mainContentCard = document.getElementById("main-content");
|
|
const floatingPlayerBtn = document.getElementById("floating-player-btn");
|
|
const fpStartText = document.getElementById("fp-start-text");
|
|
const fpPauseIcon = document.getElementById("fp-pause-icon");
|
|
const fpPlayIcon = document.getElementById("fp-play-icon");
|
|
const storyNav = document.getElementById("story-nav");
|
|
const storyNavList = document.getElementById("story-nav-list");
|
|
const resumeAlert = document.getElementById("resume-alert");
|
|
const resumeBtn = document.getElementById("resume-btn");
|
|
const toastEl = document.getElementById("reader-toast");
|
|
const toastText = document.getElementById("reader-toast-text");
|
|
|
|
// --- State ---
|
|
let storyInstances = [];
|
|
let currentlyPlayingInstance = null;
|
|
let currentlyPlayingIndex = -1;
|
|
let hasStarted = false;
|
|
let navObserver = null;
|
|
let currentBookId = null;
|
|
|
|
// --- Tunables ---
|
|
const PROGRESS_KEY = "interactiveReaderProgress";
|
|
const TEXT_BATCH_SIZE = 8; // parallel text/json fetches
|
|
const PRELOAD_AHEAD = 2; // preload N blocks ahead of current
|
|
const MID_PRELOAD_THRESHOLD = 0.7; // at 70% of current audio, ensure next is ready
|
|
const MAX_AUDIO_LOADED = 5; // keep at most this many audio sources in memory
|
|
const KEEP_BEHIND = 1; // keep this many past blocks loaded (for back-seek)
|
|
|
|
// --- Event bindings ---
|
|
floatingPlayerBtn.addEventListener("click", handleFloatingBtnClick);
|
|
mainContainer.addEventListener("click", handleTextClick);
|
|
window.addEventListener("beforeunload", saveCurrentProgress);
|
|
window.addEventListener("resize", positionUI);
|
|
window.addEventListener("scroll", positionUI);
|
|
|
|
// ===================================================
|
|
// UI helpers
|
|
// ===================================================
|
|
function positionUI() {
|
|
const rect = mainContentCard.getBoundingClientRect();
|
|
const btnRight = window.innerWidth - rect.right - 8;
|
|
floatingPlayerBtn.style.right = Math.max(btnRight, 8) + "px";
|
|
floatingPlayerBtn.style.left = "auto";
|
|
}
|
|
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) {
|
|
if (hasStarted) { fpStartText.style.display = "none"; 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"; }
|
|
}
|
|
|
|
// ===================================================
|
|
// Progress persistence
|
|
// ===================================================
|
|
function saveCurrentProgress() {
|
|
if (!currentlyPlayingInstance || !currentBookId || !currentlyPlayingInstance.audio) return;
|
|
try {
|
|
localStorage.setItem(PROGRESS_KEY, JSON.stringify({
|
|
bookId: currentBookId,
|
|
instanceIndex: currentlyPlayingIndex,
|
|
timestamp: currentlyPlayingInstance.audio.currentTime,
|
|
lastUpdate: Date.now()
|
|
}));
|
|
} catch (e) { /* quota errors ignored */ }
|
|
}
|
|
function loadProgress(bookId) {
|
|
const saved = localStorage.getItem(PROGRESS_KEY);
|
|
if (!saved) return;
|
|
let p; try { p = JSON.parse(saved); } catch (e) { return; }
|
|
if (p.bookId !== bookId) return;
|
|
if (p.instanceIndex < 0 || p.instanceIndex >= storyInstances.length) return;
|
|
resumeAlert.style.display = "flex";
|
|
resumeBtn.onclick = () => {
|
|
resumeAlert.style.display = "none";
|
|
hasStarted = true;
|
|
playInstanceAt(p.instanceIndex, p.timestamp);
|
|
};
|
|
}
|
|
|
|
// ===================================================
|
|
// INITIAL RENDER
|
|
// ===================================================
|
|
try {
|
|
let manifest = (typeof INJECTED_MANIFEST !== 'undefined' && INJECTED_MANIFEST) ? INJECTED_MANIFEST : null;
|
|
if (!manifest) {
|
|
const resp = await fetch("manifest.json");
|
|
manifest = await resp.json();
|
|
}
|
|
|
|
document.getElementById("main-header").querySelector(".story-title").textContent = manifest.title || "Interactive Reader";
|
|
document.getElementById("main-header").querySelector(".story-subtitle").textContent = "An interactive reading experience.";
|
|
|
|
const audioAssets = (manifest.assets || []).filter(a => a.textFile && a.audioFile && a.jsonFile);
|
|
if (audioAssets.length === 0) {
|
|
mainContainer.innerHTML = '<p class="text-center text-muted">No playable content found.</p>';
|
|
return;
|
|
}
|
|
|
|
const chapterTitles = {};
|
|
if (manifest.assets) {
|
|
manifest.assets.forEach(asset => {
|
|
if (asset.sortKey) {
|
|
const ch = asset.sortKey.split('.')[0];
|
|
if (!chapterTitles[ch] && asset.sectionName) chapterTitles[ch] = asset.sectionName;
|
|
}
|
|
});
|
|
}
|
|
|
|
const allSortKeys = new Set();
|
|
const audioPrefixSet = new Set();
|
|
for (const asset of audioAssets) {
|
|
const m = asset.prefix.match(/^([\d]+\.[\d]+)_/);
|
|
if (m) { allSortKeys.add(m[1]); audioPrefixSet.add(m[1]); }
|
|
}
|
|
|
|
const imageMap = new Map();
|
|
if (Array.isArray(manifest.images)) {
|
|
manifest.images.forEach(img => {
|
|
allSortKeys.add(img.sortKey);
|
|
if (!imageMap.has(img.sortKey)) imageMap.set(img.sortKey, []);
|
|
imageMap.get(img.sortKey).push(img.file);
|
|
});
|
|
}
|
|
|
|
const sortedKeys = Array.from(allSortKeys).sort((a, b) => {
|
|
const [aMa, aMi] = a.split(".").map(Number);
|
|
const [bMa, bMi] = b.split(".").map(Number);
|
|
return aMa !== bMa ? aMa - bMa : aMi - bMi;
|
|
});
|
|
|
|
currentBookId = audioAssets.map(a => a.prefix).join("|");
|
|
|
|
let audioInstanceIndex = 0;
|
|
let lastChapter = null;
|
|
|
|
for (const sortKey of sortedKeys) {
|
|
const chapter = sortKey.split(".")[0];
|
|
const isAudio = audioPrefixSet.has(sortKey);
|
|
const hasImages = imageMap.has(sortKey);
|
|
|
|
if (isAudio) {
|
|
const asset = audioAssets.find(a => a.prefix.startsWith(sortKey + "_"));
|
|
if (!asset) continue;
|
|
const blockId = `story-block-${audioInstanceIndex}`;
|
|
|
|
if (chapter !== lastChapter) {
|
|
addOutlineEntry(chapterTitles[chapter] || `Section ${chapter}`, chapter, blockId);
|
|
lastChapter = chapter;
|
|
}
|
|
|
|
mainContainer.insertAdjacentHTML("beforeend", `
|
|
<div id="${blockId}" class="story-block mt-4"
|
|
data-instance-index="${audioInstanceIndex}"
|
|
data-sort-key="${sortKey}">
|
|
<div class="image-container text-center mb-4"></div>
|
|
<article class="story-text-container">
|
|
<div class="block-loading-spinner">Loading content…</div>
|
|
</article>
|
|
<audio class="audio-player" preload="none" style="display:none;"></audio>
|
|
</div>
|
|
`);
|
|
|
|
if (hasImages) {
|
|
const imgContainer = document.getElementById(blockId).querySelector(".image-container");
|
|
for (const imgUrl of imageMap.get(sortKey)) {
|
|
const img = document.createElement("img");
|
|
img.src = imgUrl; img.loading = "lazy";
|
|
img.className = "img-fluid rounded shadow-sm";
|
|
img.style.maxHeight = "60vh";
|
|
imgContainer.appendChild(img);
|
|
}
|
|
}
|
|
|
|
storyInstances.push({
|
|
index: audioInstanceIndex,
|
|
asset: asset,
|
|
blockEl: null,
|
|
audio: null,
|
|
wordTimestamps: [],
|
|
wordMap: [],
|
|
sentenceData: [],
|
|
allWordSpans: [],
|
|
animationFrameId: null,
|
|
lastHighlightedWordSpan: null,
|
|
lastHighlightedSentenceSpans: [],
|
|
textReady: false,
|
|
audioReady: false,
|
|
audioLoadingPromise: null,
|
|
midPreloadTriggered: false // prevents repeated trigger of mid-play preload
|
|
});
|
|
audioInstanceIndex++;
|
|
} else if (hasImages) {
|
|
const imgBlockId = `story-image-block-${sortKey.replace('.', '-')}`;
|
|
if (chapter !== lastChapter) {
|
|
addOutlineEntry(chapterTitles[chapter] || `Section ${chapter}`, chapter, imgBlockId);
|
|
lastChapter = chapter;
|
|
}
|
|
const imgDiv = document.createElement("div");
|
|
imgDiv.id = imgBlockId;
|
|
imgDiv.className = "story-image-block mt-4";
|
|
imgDiv.dataset.sortKey = sortKey;
|
|
for (const imgUrl of imageMap.get(sortKey)) {
|
|
const img = document.createElement("img");
|
|
img.src = imgUrl; img.loading = "lazy";
|
|
img.className = "img-fluid rounded shadow-sm";
|
|
img.style.maxHeight = "70vh";
|
|
imgDiv.appendChild(img);
|
|
}
|
|
mainContainer.appendChild(imgDiv);
|
|
}
|
|
}
|
|
|
|
storyInstances.forEach(inst => { inst.blockEl = document.getElementById(`story-block-${inst.index}`); });
|
|
|
|
storyNav.style.display = 'block';
|
|
storyNav.classList.add("visible");
|
|
floatingPlayerBtn.classList.add("visible");
|
|
setupNavObserver();
|
|
setTimeout(positionUI, 100);
|
|
|
|
loadAllTextContent().then(() => loadProgress(currentBookId));
|
|
|
|
} catch (e) {
|
|
console.error(e);
|
|
mainContainer.innerHTML = `<p class="text-center text-danger">Error loading: ${e.message}</p>`;
|
|
}
|
|
|
|
async function loadAllTextContent() {
|
|
for (let i = 0; i < storyInstances.length; i += TEXT_BATCH_SIZE) {
|
|
const batch = storyInstances.slice(i, i + TEXT_BATCH_SIZE);
|
|
await Promise.all(batch.map(loadTextForInstance));
|
|
}
|
|
}
|
|
|
|
async function loadTextForInstance(inst) {
|
|
if (inst.textReady) return;
|
|
try {
|
|
const [textResp, jsonResp] = await Promise.all([
|
|
fetch(inst.asset.textFile),
|
|
fetch(inst.asset.jsonFile)
|
|
]);
|
|
if (!textResp.ok || !jsonResp.ok) throw new Error('fetch failed');
|
|
const [text, timestamps] = await Promise.all([textResp.text(), jsonResp.json()]);
|
|
inst.wordTimestamps = timestamps;
|
|
renderMarkdownInto(inst, text);
|
|
smartSync(inst);
|
|
inst.textReady = true;
|
|
} catch (err) {
|
|
console.warn(`Text load failed for block ${inst.index}:`, err);
|
|
const container = inst.blockEl.querySelector(".story-text-container");
|
|
if (container) container.innerHTML = '<p class="text-muted small">Content failed to load.</p>';
|
|
}
|
|
}
|
|
|
|
// ===================================================
|
|
// AUDIO LAZY LOADING + MEMORY MANAGEMENT
|
|
// ===================================================
|
|
function ensureAudioLoaded(inst) {
|
|
if (inst.audioReady && inst.audio && inst.audio.src) return Promise.resolve(inst);
|
|
if (inst.audioLoadingPromise) return inst.audioLoadingPromise;
|
|
|
|
inst.audioLoadingPromise = new Promise((resolve, reject) => {
|
|
const audio = inst.blockEl.querySelector(".audio-player");
|
|
if (!audio) return reject(new Error('No audio element'));
|
|
|
|
const onCanPlay = () => {
|
|
audio.removeEventListener("error", onError);
|
|
inst.audio = audio;
|
|
inst.audioReady = true;
|
|
wireAudioEvents(inst);
|
|
resolve(inst);
|
|
};
|
|
const onError = () => {
|
|
audio.removeEventListener("canplay", onCanPlay);
|
|
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 = inst.asset.audioFile;
|
|
audio.load();
|
|
});
|
|
return inst.audioLoadingPromise;
|
|
}
|
|
|
|
function wireAudioEvents(inst) {
|
|
const audio = inst.audio;
|
|
audio.addEventListener("play", () => {
|
|
startHighlightLoop(inst);
|
|
updateFloatingButton("playing");
|
|
});
|
|
audio.addEventListener("pause", () => {
|
|
stopHighlightLoop(inst);
|
|
updateFloatingButton("paused");
|
|
saveCurrentProgress();
|
|
});
|
|
audio.addEventListener("ended", () => {
|
|
stopHighlightLoop(inst);
|
|
clearHighlights(inst);
|
|
playNextInstance();
|
|
});
|
|
// Safety-net mid-play preload: when current passes 70%, ensure next is ready.
|
|
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 the next N audio blocks (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 a sliding window of audio elements loaded.
|
|
* Releases audio resources for blocks too far from the current one.
|
|
*
|
|
* Window = [currentIndex - KEEP_BEHIND, currentIndex + PRELOAD_AHEAD]
|
|
* Bounded to MAX_AUDIO_LOADED total.
|
|
*/
|
|
function pruneLoadedAudio(currentIndex) {
|
|
// Find all currently-loaded instances
|
|
const loaded = storyInstances.filter(i => i.audioReady && i.audio && i.audio.src);
|
|
if (loaded.length <= MAX_AUDIO_LOADED) return;
|
|
|
|
const keepLow = currentIndex - KEEP_BEHIND;
|
|
const keepHigh = currentIndex + PRELOAD_AHEAD;
|
|
|
|
// Sort candidates for eviction: outside window first, then by distance from current
|
|
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) => {
|
|
// Out-of-window first
|
|
if (a.inWindow !== b.inWindow) return a.inWindow ? 1 : -1;
|
|
// Then by farthest distance
|
|
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(); // reset to empty state, free decoder
|
|
} catch (e) { /* ignore */ }
|
|
inst.audioReady = false;
|
|
inst.audioLoadingPromise = null;
|
|
inst.midPreloadTriggered = false;
|
|
// NOTE: we intentionally keep inst.audio reference; events are still bound,
|
|
// but a fresh ensureAudioLoaded() call will re-set the src and work.
|
|
// To be fully clean, we'd null it out — but element is needed for re-load.
|
|
}
|
|
|
|
// ===================================================
|
|
// PLAYBACK
|
|
// ===================================================
|
|
async function playInstanceAt(index, timestamp = 0, opts = {}) {
|
|
if (index < 0 || index >= storyInstances.length) return;
|
|
const inst = storyInstances[index];
|
|
const isAutoAdvance = opts.autoAdvance === true;
|
|
|
|
if (currentlyPlayingInstance && currentlyPlayingInstance !== inst) {
|
|
stopAndResetInstance(currentlyPlayingInstance);
|
|
}
|
|
currentlyPlayingInstance = inst;
|
|
currentlyPlayingIndex = index;
|
|
hasStarted = true;
|
|
inst.midPreloadTriggered = false; // reset for this play session
|
|
|
|
// For auto-advance, audio is usually preloaded → no spinner flicker.
|
|
// Only show spinner if audio truly isn't ready yet.
|
|
const needsLoad = !inst.audioReady;
|
|
if (needsLoad) {
|
|
setButtonLoading(true);
|
|
showToast("Loading audio…");
|
|
}
|
|
|
|
try {
|
|
if (!inst.textReady) await loadTextForInstance(inst);
|
|
await ensureAudioLoaded(inst);
|
|
|
|
if (needsLoad) {
|
|
hideToast();
|
|
setButtonLoading(false);
|
|
}
|
|
|
|
inst.audio.currentTime = timestamp;
|
|
await inst.audio.play();
|
|
updateFloatingButton("playing");
|
|
|
|
// Block-level scroll ONLY for manual navigation, not auto-advance.
|
|
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(index);
|
|
pruneLoadedAudio(index);
|
|
} catch (err) {
|
|
console.error(err);
|
|
setButtonLoading(false);
|
|
showToast("Failed to load audio. Tap again to retry.");
|
|
setTimeout(hideToast, 3000);
|
|
updateFloatingButton("paused");
|
|
}
|
|
}
|
|
|
|
function playNextInstance() {
|
|
const next = currentlyPlayingIndex + 1;
|
|
if (next < storyInstances.length) {
|
|
playInstanceAt(next, 0, { autoAdvance: true });
|
|
} else {
|
|
updateFloatingButton("paused");
|
|
currentlyPlayingInstance = null;
|
|
currentlyPlayingIndex = -1;
|
|
}
|
|
}
|
|
|
|
function stopAndResetInstance(inst) {
|
|
if (inst.audio) { inst.audio.pause(); inst.audio.currentTime = 0; }
|
|
stopHighlightLoop(inst);
|
|
clearHighlights(inst);
|
|
}
|
|
|
|
function handleFloatingBtnClick() {
|
|
if (!hasStarted) { playInstanceAt(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 {
|
|
playInstanceAt(0, 0);
|
|
}
|
|
}
|
|
|
|
async function handleTextClick(event) {
|
|
const wordSpan = event.target.closest(".word");
|
|
if (!wordSpan) return;
|
|
const storyBlock = event.target.closest(".story-block");
|
|
if (!storyBlock) return;
|
|
const idx = parseInt(storyBlock.dataset.instanceIndex, 10);
|
|
if (isNaN(idx)) return;
|
|
const inst = storyInstances[idx];
|
|
|
|
if (!inst.textReady) {
|
|
showToast("Loading…");
|
|
await loadTextForInstance(inst);
|
|
hideToast();
|
|
}
|
|
const timestamp = getTimeForSpan(inst, wordSpan);
|
|
if (timestamp === null) return;
|
|
playInstanceAt(idx, timestamp);
|
|
}
|
|
|
|
// ===================================================
|
|
// Outline / Nav
|
|
// ===================================================
|
|
function addOutlineEntry(title, chapter, targetBlockId) {
|
|
const li = document.createElement("li");
|
|
li.textContent = title; li.title = title;
|
|
li.dataset.chapter = chapter;
|
|
li.onclick = () => {
|
|
const target = document.getElementById(targetBlockId);
|
|
if (target) {
|
|
const offset = target.getBoundingClientRect().top + window.pageYOffset - 120;
|
|
window.scrollTo({ top: offset, behavior: 'smooth' });
|
|
target.classList.add('highlight-section');
|
|
setTimeout(() => target.classList.remove('highlight-section'), 2000);
|
|
}
|
|
};
|
|
storyNavList.appendChild(li);
|
|
}
|
|
|
|
function setupNavObserver() {
|
|
if (navObserver) navObserver.disconnect();
|
|
navObserver = new IntersectionObserver((entries) => {
|
|
entries.forEach(entry => {
|
|
if (entry.isIntersecting) {
|
|
const sk = entry.target.dataset.sortKey;
|
|
if (sk) {
|
|
const ch = sk.split(".")[0];
|
|
storyNavList.querySelectorAll("li").forEach(l => l.classList.remove("active"));
|
|
const al = storyNavList.querySelector(`li[data-chapter='${ch}']`);
|
|
if (al) al.classList.add("active");
|
|
}
|
|
}
|
|
});
|
|
}, { threshold: 0.4 });
|
|
document.querySelectorAll(".story-block, .story-image-block").forEach(b => navObserver.observe(b));
|
|
}
|
|
|
|
// ===================================================
|
|
// Render & Sync
|
|
// ===================================================
|
|
function renderMarkdownInto(inst, text) {
|
|
const container = inst.blockEl.querySelector(".story-text-container");
|
|
container.innerHTML = "";
|
|
inst.allWordSpans = [];
|
|
const div = document.createElement("div");
|
|
div.innerHTML = marked.parse(text, { breaks: true, gfm: true });
|
|
|
|
(function processNode(node) {
|
|
if (node.nodeType === Node.TEXT_NODE) {
|
|
const words = node.textContent.split(/(\s+)/);
|
|
const fragment = document.createDocumentFragment();
|
|
words.forEach(part => {
|
|
if (part.trim().length > 0) {
|
|
const span = document.createElement("span");
|
|
span.className = "word";
|
|
span.textContent = part;
|
|
inst.allWordSpans.push(span);
|
|
fragment.appendChild(span);
|
|
} else fragment.appendChild(document.createTextNode(part));
|
|
});
|
|
node.parentNode.replaceChild(fragment, 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) {
|
|
inst.wordMap = new Array(inst.allWordSpans.length).fill(undefined);
|
|
let ai = 0;
|
|
inst.allWordSpans.forEach((span, i) => {
|
|
const tw = span.textContent.toLowerCase().replace(/[^\w]/g, "");
|
|
for (let o = 0; o < 5; o++) {
|
|
if (ai + o >= inst.wordTimestamps.length) break;
|
|
const aw = inst.wordTimestamps[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.allWordSpans.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 = inst.wordTimestamps[inst.wordMap[k]].start; break; }
|
|
for (let k = i; k >= si; k--) if (inst.wordMap[k] !== undefined) { eT = inst.wordTimestamps[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.allWordSpans.length; k++) if (inst.wordMap[k] !== undefined) { sT = inst.wordTimestamps[inst.wordMap[k]].start; break; }
|
|
for (let k = inst.allWordSpans.length - 1; k >= si; k--) if (inst.wordMap[k] !== undefined) { eT = inst.wordTimestamps[inst.wordMap[k]].end; break; }
|
|
if (eT > sT) inst.sentenceData.push({ spans: [...buf], startTime: sT, endTime: eT });
|
|
}
|
|
}
|
|
|
|
function getTimeForSpan(inst, wordSpan) {
|
|
const idx = inst.allWordSpans.indexOf(wordSpan);
|
|
if (idx < 0) return null;
|
|
const ai = inst.wordMap[idx];
|
|
return ai !== undefined ? inst.wordTimestamps[ai].start : null;
|
|
}
|
|
|
|
function startHighlightLoop(inst) {
|
|
cancelAnimationFrame(inst.animationFrameId);
|
|
inst.animationFrameId = requestAnimationFrame(() => hlLoop(inst));
|
|
}
|
|
function stopHighlightLoop(inst) { cancelAnimationFrame(inst.animationFrameId); }
|
|
function hlLoop(inst) {
|
|
if (!inst.audio || inst.audio.paused) return;
|
|
const t = inst.audio.currentTime;
|
|
const ai = inst.wordTimestamps.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.allWordSpans[ti];
|
|
if (sp !== inst.lastHighlightedWordSpan) {
|
|
if (inst.lastHighlightedWordSpan) inst.lastHighlightedWordSpan.classList.remove("current-word");
|
|
sp.classList.add("current-word");
|
|
const r = sp.getBoundingClientRect();
|
|
// Slightly relaxed threshold (20% / 80%) for smoother scroll
|
|
if (r.top < window.innerHeight * 0.2 || r.bottom > window.innerHeight * 0.8) {
|
|
sp.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
}
|
|
inst.lastHighlightedWordSpan = sp;
|
|
}
|
|
}
|
|
}
|
|
const sent = inst.sentenceData.find(s => t >= s.startTime && t <= s.endTime);
|
|
if (sent && sent.spans !== inst.lastHighlightedSentenceSpans) {
|
|
inst.lastHighlightedSentenceSpans.forEach(s => s.classList.remove("current-sentence-bg"));
|
|
sent.spans.forEach(s => s.classList.add("current-sentence-bg"));
|
|
inst.lastHighlightedSentenceSpans = sent.spans;
|
|
}
|
|
inst.animationFrameId = requestAnimationFrame(() => hlLoop(inst));
|
|
}
|
|
function clearHighlights(inst) {
|
|
if (inst.lastHighlightedWordSpan) inst.lastHighlightedWordSpan.classList.remove("current-word");
|
|
inst.lastHighlightedSentenceSpans.forEach(s => s.classList.remove("current-sentence-bg"));
|
|
inst.lastHighlightedWordSpan = null;
|
|
inst.lastHighlightedSentenceSpans = [];
|
|
}
|
|
});
|
|
</script>
|
|
</body>
|
|
</html>
|