Files
QueryByHumming/demo/app.js
T

303 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(function () {
'use strict';
const { decodeText, splitParagraphs, buildChunks, offsetFromViewport, progressPercent, formatTime } = Core;
// ---------- 模拟存储层(Demo 中用内存 + localStorage 代替 IndexedDB) ----------
const STORE_KEY = 'txt-reader-demo-progress';
const SETTING_KEY = 'txt-reader-demo-settings';
const progressStore = JSON.parse(localStorage.getItem(STORE_KEY) || '{}');
const settings = Object.assign(
{ fontSize: 18, lineHeight: 1.9 },
JSON.parse(localStorage.getItem(SETTING_KEY) || '{}')
);
function saveProgress() {
localStorage.setItem(STORE_KEY, JSON.stringify(progressStore));
}
function saveSettings() {
localStorage.setItem(SETTING_KEY, JSON.stringify(settings));
applySettings();
}
// 书籍内存模型:{ id, title, importedAt, offset, totalChars, paragraphs, offsets }
const books = [];
// ---------- 书架 ----------
const bookListEl = document.getElementById('book-list');
const shelfEmptyEl = document.getElementById('shelf-empty');
function renderShelf() {
bookListEl.innerHTML = '';
shelfEmptyEl.classList.toggle('hidden', books.length > 0);
const sorted = [...books].sort((a, b) => b.importedAt - a.importedAt);
for (const book of sorted) {
const pct = progressPercent(book.offset, book.totalChars);
const card = document.createElement('div');
card.className = 'book-card';
card.innerHTML = `
<div class="book-cover">${book.title.slice(0, 1)}</div>
<div class="book-info">
<div class="book-title"></div>
<div class="book-meta">导入于 ${formatTime(book.importedAt)} · 约 ${(book.totalChars / 10000).toFixed(1)} 万字</div>
<div class="progress-bar"><div style="width:${pct}%"></div></div>
</div>
<div class="book-progress-num">${pct}%</div>
<button class="book-delete" title="删除">删除</button>
`;
card.querySelector('.book-title').textContent = book.title;
card.addEventListener('click', () => openBook(book.id));
card.querySelector('.book-delete').addEventListener('click', (e) => {
e.stopPropagation();
removeBook(book.id);
});
bookListEl.appendChild(card);
}
}
function addBook(title, text) {
const paragraphs = splitParagraphs(text);
// 与真实文本一致:按段落重连后的字符数作为进度总量
const totalChars = paragraphs.reduce((n, p) => n + p.length, 0);
const offsets = [];
let acc = 0;
for (const p of paragraphs) {
offsets.push(acc);
acc += p.length;
}
books.push({
id: (self.crypto && crypto.randomUUID) ? crypto.randomUUID() : 'book-' + Date.now() + '-' + Math.floor(Math.random() * 1e9),
title,
importedAt: Date.now(),
offset: 0,
totalChars,
paragraphs,
offsets,
});
renderShelf();
toast(`《${title}》已导入书架`);
}
function removeBook(id) {
const idx = books.findIndex((b) => b.id === id);
if (idx < 0) return;
const title = books[idx].title;
books.splice(idx, 1);
delete progressStore[id];
saveProgress();
renderShelf();
toast(`《${title}》已删除`);
}
// ---------- 阅读页 ----------
const shelfView = document.getElementById('shelf-view');
const readerView = document.getElementById('reader-view');
const readerBody = document.getElementById('reader-body');
const readerContent = document.getElementById('reader-content');
const readerTitle = document.getElementById('reader-title');
const readerProgress = document.getElementById('reader-progress');
const settingsPanel = document.getElementById('settings-panel');
const settingsBtn = document.getElementById('settings-btn');
let currentBook = null;
let chunkCursor = 0; // 已渲染到的 chunk 下标
const CHUNK_CHARS = 3000; // 每个渲染块的字符数(模拟大文件按需渲染)
let restorePendingOffset = null;
function openBook(id) {
const book = books.find((b) => b.id === id);
if (!book) return;
currentBook = book;
readerTitle.textContent = book.title;
readerContent.innerHTML = '';
chunkCursor = 0;
// 进度恢复:优先取已保存的字符偏移
restorePendingOffset = progressStore[id] != null ? progressStore[id].offset : 0;
if (restorePendingOffset > 0) {
toast('已回到上次阅读位置');
}
shelfView.classList.add('hidden');
readerView.classList.remove('hidden');
renderMoreChunks();
applySettings();
if (restorePendingOffset == null) readerBody.scrollTop = 0;
}
function backToShelf() {
saveCurrentOffset();
currentBook = null;
readerView.classList.add('hidden');
shelfView.classList.remove('hidden');
renderShelf();
}
function saveCurrentOffset() {
if (!currentBook) return;
const offset = estimateOffset();
progressStore[currentBook.id] = { offset, savedAt: Date.now() };
saveProgress();
}
// 由滚动位置估算当前字符偏移(视口顶部所在段落)
function estimateOffset() {
if (!currentBook) return 0;
const ps = readerContent.querySelectorAll('[data-offset]');
if (ps.length === 0) return 0;
const scrollTop = readerBody.scrollTop + 60;
let ans = 0;
for (const p of ps) {
if (p.offsetTop <= scrollTop) ans = Number(p.dataset.offset);
else break;
}
return ans;
}
function renderMoreChunks() {
if (!currentBook) return;
const chunks = buildChunks(currentBook.paragraphs, CHUNK_CHARS);
// buildChunks 每次重算开销大,这里缓存一份
if (!currentBook._chunks) currentBook._chunks = chunks;
if (chunkCursor >= currentBook._chunks.length) return;
const chunk = currentBook._chunks[chunkCursor];
const frag = document.createDocumentFragment();
for (const item of chunk.items) {
if (/^第.+章/.test(item.text)) {
const h = document.createElement('h2');
h.textContent = item.text;
frag.appendChild(h);
} else {
const p = document.createElement('p');
p.dataset.offset = item.offset;
p.textContent = item.text;
frag.appendChild(p);
}
}
readerContent.appendChild(frag);
chunkCursor++;
maybeRestoreScroll();
}
// 首次进入时按保存的偏移恢复滚动位置
function maybeRestoreScroll() {
if (restorePendingOffset == null || !currentBook) return;
const target = restorePendingOffset;
const ps = readerContent.querySelectorAll('[data-offset]');
let last = null;
for (const p of ps) {
if (Number(p.dataset.offset) <= target) last = p;
else break;
}
// 目标位置还没渲染出来,继续加载更多块
if (!last && chunkCursor < (currentBook._chunks || []).length) {
renderMoreChunks();
return;
}
if (last) {
readerBody.scrollTop = last.offsetTop - 20;
updateProgressLabel();
}
if (chunkCursor >= (currentBook._chunks || []).length) {
restorePendingOffset = null; // 全部渲染完,结束恢复流程
}
}
function updateProgressLabel() {
if (!currentBook) return;
readerProgress.textContent = progressPercent(estimateOffset(), currentBook.totalChars) + '%';
}
// 滚动按需加载更多块 + 实时更新进度
readerBody.addEventListener('scroll', () => {
if (!currentBook) return;
const nearBottom =
readerBody.scrollTop + readerBody.clientHeight >= readerBody.scrollHeight - 400;
if (nearBottom) renderMoreChunks();
updateProgressLabel();
});
// ---------- 设置 ----------
function applySettings() {
document.documentElement.style.setProperty('--reader-font-size', settings.fontSize + 'px');
document.documentElement.style.setProperty('--reader-line-height', settings.lineHeight);
document.getElementById('font-value').textContent = settings.fontSize;
document.getElementById('lh-value').textContent = settings.lineHeight.toFixed(1);
}
document.getElementById('font-plus').addEventListener('click', () => {
settings.fontSize = Math.min(28, settings.fontSize + 2); saveSettings();
});
document.getElementById('font-minus').addEventListener('click', () => {
settings.fontSize = Math.max(14, settings.fontSize - 2); saveSettings();
});
document.getElementById('lh-plus').addEventListener('click', () => {
settings.lineHeight = Math.min(2.6, settings.lineHeight + 0.1); saveSettings();
});
document.getElementById('lh-minus').addEventListener('click', () => {
settings.lineHeight = Math.max(1.5, Math.round((settings.lineHeight - 0.1) * 10) / 10); saveSettings();
});
settingsBtn.addEventListener('click', () => {
settingsPanel.classList.toggle('hidden');
settingsBtn.classList.toggle('active', !settingsPanel.classList.contains('hidden'));
});
// ---------- 导入 ----------
document.getElementById('import-btn').addEventListener('click', () => {
document.getElementById('file-input').click();
});
document.getElementById('file-input').addEventListener('change', async (e) => {
for (const file of e.target.files) {
const buffer = await file.arrayBuffer();
const text = decodeText(buffer);
addBook(file.name.replace(/\.txt$/i, ''), text);
}
e.target.value = '';
});
document.getElementById('back-btn').addEventListener('click', backToShelf);
// ---------- Toast ----------
let toastTimer = null;
function toast(msg) {
let el = document.querySelector('.toast');
if (!el) {
el = document.createElement('div');
el.className = 'toast';
document.body.appendChild(el);
}
el.textContent = msg;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.remove(), 2200);
}
// ---------- 初始化:载入模拟数据 ----------
window.addEventListener('beforeunload', saveCurrentOffset);
for (const mb of MockData.MOCK_BOOKS) {
const paragraphs = splitParagraphs(mb.text);
const totalChars = paragraphs.reduce((n, p) => n + p.length, 0);
const offsets = [];
let acc = 0;
for (const p of paragraphs) {
offsets.push(acc);
acc += p.length;
}
books.push({
id: mb.id,
title: mb.title,
importedAt: mb.importedAt,
// 模拟"已有阅读进度";若 localStorage 已有进度(演示过一次),以本地为准
offset: progressStore[mb.id] != null ? progressStore[mb.id].offset : Math.round(totalChars * mb.progressRatio),
totalChars,
paragraphs,
offsets,
});
}
progressStoreInit:
for (const b of books) {
if (progressStore[b.id] == null && b.offset > 0) {
progressStore[b.id] = { offset: b.offset, savedAt: Date.now() };
}
}
saveProgress();
renderShelf();
})();