feat: add TXT reader demo with mock data (bookshelf, reader, progress restore)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{"touched":["F:\\zcode\\test20260912\\demo\\app.js"],"bashMutation":false,"reportedFindings":[],"findingEvents":[],"baseline":{"storageId":"mtykkxc9-41204-352eee7f13","createdAt":"2026-09-12T15:58:36.489Z","files":{"app.js":{"existed":true,"snapshot":"e07d531ac040ce3f40e0ce632ac2a059d7cd60f20e61f78268ac3be015b3b28f.source"}},"complete":false,"candidateLimit":5000,"discoveredFiles":0,"capturedFiles":1,"truncated":false,"omittedAtLeast":0,"firstOmitted":"","errors":[{"stage":"baseline-capture","target":".","reason":"global task baseline was unavailable; captured only the touched file"}]},"stateErrors":[],"omittedReportedFindings":0,"omittedFindingEvents":0,"processing":null,"updatedAt":"2026-09-12T15:58:38.907Z"}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
(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();
|
||||
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();
|
||||
})();
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"schemaVersion": "mimosa-hook-status/v1",
|
||||
"recordedAt": "2026-09-12T15:58:38.911Z",
|
||||
"sessionId": "sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921",
|
||||
"event": "PostToolUse",
|
||||
"toolName": "Edit",
|
||||
"file": "app.js",
|
||||
"outcome": "clear",
|
||||
"coverage": "complete",
|
||||
"findingCount": 0,
|
||||
"durationMs": 10,
|
||||
"hostState": "hook_complete",
|
||||
"reportHint": ".mimosa/reports/"
|
||||
}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
(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();
|
||||
})();
|
||||
@@ -0,0 +1,85 @@
|
||||
// 纯逻辑函数,供页面与测试共用(可在 Node 中直接 require)
|
||||
(function (root, factory) {
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = factory();
|
||||
else root.Core = factory();
|
||||
})(typeof self !== 'undefined' ? self : this, function () {
|
||||
'use strict';
|
||||
|
||||
// 编码检测:UTF-8 优先,失败回退 GBK/GB18030
|
||||
function decodeText(buffer) {
|
||||
try {
|
||||
const utf8 = new TextDecoder('utf-8', { fatal: true });
|
||||
return utf8.decode(buffer);
|
||||
} catch (e) {
|
||||
/* fallthrough */
|
||||
}
|
||||
try {
|
||||
const gbk = new TextDecoder('gb18030', { fatal: false });
|
||||
return gbk.decode(buffer);
|
||||
} catch (e) {
|
||||
return new TextDecoder('utf-8').decode(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// 把正文切分为段落数组(用于分块渲染与 offset 映射)
|
||||
function splitParagraphs(text) {
|
||||
return text.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
|
||||
}
|
||||
|
||||
// 段落数组 -> 带累计字符偏移的渲染块(每块 maxChars 个字符,避免一次性渲染全文)
|
||||
function buildChunks(paragraphs, maxChars) {
|
||||
const chunks = [];
|
||||
let cur = [];
|
||||
let curChars = 0;
|
||||
let offset = 0;
|
||||
for (const p of paragraphs) {
|
||||
cur.push({ text: p, offset });
|
||||
curChars += p.length;
|
||||
offset += p.length;
|
||||
if (curChars >= maxChars) {
|
||||
chunks.push({ startOffset: cur[0].offset, items: cur });
|
||||
cur = [];
|
||||
curChars = 0;
|
||||
}
|
||||
}
|
||||
if (cur.length > 0) chunks.push({ startOffset: cur[0].offset, items: cur });
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// 由滚动位置估算字符偏移:取当前视口顶部所在段落的首字符偏移
|
||||
function offsetFromViewport(paragraphOffsets, scrollTop, tops) {
|
||||
let lo = 0;
|
||||
let hi = tops.length - 1;
|
||||
let ans = 0;
|
||||
while (lo <= hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (tops[mid] <= scrollTop) {
|
||||
ans = paragraphOffsets[mid];
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
function progressPercent(offset, total) {
|
||||
if (!total) return 0;
|
||||
return Math.min(100, Math.round((offset / total) * 100));
|
||||
}
|
||||
|
||||
function formatTime(ts) {
|
||||
const d = new Date(ts);
|
||||
const p = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
return {
|
||||
decodeText,
|
||||
splitParagraphs,
|
||||
buildChunks,
|
||||
offsetFromViewport,
|
||||
progressPercent,
|
||||
formatTime,
|
||||
};
|
||||
});
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>TXT 阅读器 Demo</title>
|
||||
<style>
|
||||
:root {
|
||||
--c-bg: #f5f4f0;
|
||||
--c-surface: #ffffff;
|
||||
--c-text: #2b2b2b;
|
||||
--c-text-secondary: #8a8a8a;
|
||||
--c-primary: #2f6f4f;
|
||||
--c-primary-soft: #e4efe9;
|
||||
--c-border: #e4e2dc;
|
||||
--c-danger: #b4453c;
|
||||
--reader-font-size: 18px;
|
||||
--reader-line-height: 1.9;
|
||||
}
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body {
|
||||
font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
background: var(--c-bg);
|
||||
color: var(--c-text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
button { font: inherit; cursor: pointer; border: none; background: none; }
|
||||
.hidden { display: none !important; }
|
||||
|
||||
/* ---------- 书架 ---------- */
|
||||
.shelf-header {
|
||||
max-width: 720px; margin: 0 auto; padding: 40px 20px 16px;
|
||||
display: flex; align-items: baseline; justify-content: space-between;
|
||||
}
|
||||
.shelf-header h1 { font-size: 22px; }
|
||||
.shelf-header .demo-tag { font-size: 12px; color: var(--c-text-secondary); }
|
||||
.shelf {
|
||||
max-width: 720px; margin: 0 auto; padding: 8px 20px 60px;
|
||||
}
|
||||
.import-btn {
|
||||
display: flex; align-items: center; justify-content: center; gap: 8px;
|
||||
width: 100%; padding: 16px;
|
||||
border: 1.5px dashed var(--c-border); border-radius: 12px;
|
||||
color: var(--c-text-secondary); background: var(--c-surface);
|
||||
transition: border-color .15s, color .15s;
|
||||
}
|
||||
.import-btn:hover { border-color: var(--c-primary); color: var(--c-primary); }
|
||||
.book-list { margin-top: 16px; display: flex; flex-direction: column; gap: 12px; }
|
||||
.book-card {
|
||||
display: flex; align-items: center; gap: 16px;
|
||||
padding: 18px 20px; border-radius: 12px;
|
||||
background: var(--c-surface); border: 1px solid var(--c-border);
|
||||
cursor: pointer; transition: box-shadow .15s;
|
||||
}
|
||||
.book-card:hover { box-shadow: 0 2px 10px rgba(0,0,0,.06); }
|
||||
.book-cover {
|
||||
width: 52px; height: 72px; border-radius: 6px; flex-shrink: 0;
|
||||
background: linear-gradient(160deg, var(--c-primary-soft), #cfe0d6);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
color: var(--c-primary); font-size: 20px; font-weight: 600;
|
||||
}
|
||||
.book-info { flex: 1; min-width: 0; }
|
||||
.book-title { font-size: 17px; font-weight: 600; }
|
||||
.book-meta { font-size: 13px; color: var(--c-text-secondary); margin-top: 6px; }
|
||||
.progress-bar {
|
||||
margin-top: 10px; height: 4px; border-radius: 2px;
|
||||
background: var(--c-border); overflow: hidden;
|
||||
}
|
||||
.progress-bar > div { height: 100%; background: var(--c-primary); border-radius: 2px; }
|
||||
.book-progress-num { font-size: 14px; color: var(--c-primary); width: 48px; text-align: right; }
|
||||
.book-delete {
|
||||
padding: 6px 10px; border-radius: 8px; font-size: 13px;
|
||||
color: var(--c-text-secondary);
|
||||
}
|
||||
.book-delete:hover { color: var(--c-danger); background: #faf0ef; }
|
||||
.shelf-empty { text-align: center; color: var(--c-text-secondary); padding: 60px 0; }
|
||||
|
||||
/* ---------- 阅读页 ---------- */
|
||||
.reader { display: flex; flex-direction: column; height: 100vh; background: var(--c-bg); }
|
||||
.reader-header {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 12px 20px; background: var(--c-surface);
|
||||
border-bottom: 1px solid var(--c-border);
|
||||
position: sticky; top: 0; z-index: 10;
|
||||
}
|
||||
.reader-header .back { padding: 6px 12px; border-radius: 8px; color: var(--c-text-secondary); }
|
||||
.reader-header .back:hover { background: var(--c-bg); color: var(--c-text); }
|
||||
.reader-title { flex: 1; font-size: 15px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.reader-progress-label { font-size: 13px; color: var(--c-text-secondary); flex-shrink: 0; }
|
||||
.settings-toggle { padding: 6px 12px; border-radius: 8px; color: var(--c-text-secondary); font-size: 15px; }
|
||||
.settings-toggle:hover, .settings-toggle.active { background: var(--c-primary-soft); color: var(--c-primary); }
|
||||
.settings-panel {
|
||||
display: flex; gap: 32px; align-items: center; justify-content: center;
|
||||
padding: 12px 20px; background: var(--c-surface);
|
||||
border-bottom: 1px solid var(--c-border);
|
||||
}
|
||||
.setting-group { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--c-text-secondary); }
|
||||
.setting-group button {
|
||||
width: 30px; height: 30px; border-radius: 8px; background: var(--c-bg); color: var(--c-text);
|
||||
}
|
||||
.setting-group .value { min-width: 44px; text-align: center; color: var(--c-text); }
|
||||
.reader-body { flex: 1; overflow-y: auto; }
|
||||
.reader-content {
|
||||
max-width: 680px; margin: 0 auto; padding: 32px 24px 40vh;
|
||||
font-size: var(--reader-font-size);
|
||||
line-height: var(--reader-line-height);
|
||||
}
|
||||
.reader-content p { margin-bottom: 1em; text-align: justify; }
|
||||
.reader-content h2 {
|
||||
font-size: 1.15em; margin: 2em 0 1em; color: var(--c-primary);
|
||||
text-align: center; font-weight: 600;
|
||||
}
|
||||
.toast {
|
||||
position: fixed; left: 50%; bottom: 40px; transform: translateX(-50%);
|
||||
background: rgba(43,43,43,.9); color: #fff; padding: 10px 20px;
|
||||
border-radius: 20px; font-size: 14px; z-index: 99;
|
||||
animation: toast-in .2s ease;
|
||||
}
|
||||
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- 书架视图 -->
|
||||
<div id="shelf-view">
|
||||
<div class="shelf-header">
|
||||
<h1>书架</h1>
|
||||
<span class="demo-tag">Demo · 数据为模拟数据</span>
|
||||
</div>
|
||||
<div class="shelf">
|
||||
<button class="import-btn" id="import-btn">
|
||||
<span style="font-size:20px">+</span> 导入 TXT 文件
|
||||
</button>
|
||||
<input type="file" id="file-input" accept=".txt" multiple hidden />
|
||||
<div class="book-list" id="book-list"></div>
|
||||
<div class="shelf-empty hidden" id="shelf-empty">书架空空的,导入一本 TXT 开始阅读吧</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 阅读视图 -->
|
||||
<div id="reader-view" class="reader hidden">
|
||||
<div class="reader-header">
|
||||
<button class="back" id="back-btn">‹ 书架</button>
|
||||
<div class="reader-title" id="reader-title"></div>
|
||||
<span class="reader-progress-label" id="reader-progress">0%</span>
|
||||
<button class="settings-toggle" id="settings-btn" title="阅读设置">Aa</button>
|
||||
</div>
|
||||
<div class="settings-panel hidden" id="settings-panel">
|
||||
<div class="setting-group">
|
||||
字号
|
||||
<button id="font-minus">−</button>
|
||||
<span class="value" id="font-value">18</span>
|
||||
<button id="font-plus">+</button>
|
||||
</div>
|
||||
<div class="setting-group">
|
||||
行距
|
||||
<button id="lh-minus">−</button>
|
||||
<span class="value" id="lh-value">1.9</span>
|
||||
<button id="lh-plus">+</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="reader-body" id="reader-body">
|
||||
<div class="reader-content" id="reader-content"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="core.js"></script>
|
||||
<script src="mock-data.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,60 @@
|
||||
// 模拟数据:预置几本"书",用程序生成的正文代替真实文件
|
||||
(function (root) {
|
||||
'use strict';
|
||||
|
||||
const SENTENCES = [
|
||||
'山间的雾气还未散去,远处的村庄只剩下模糊的轮廓。',
|
||||
'他坐在门前的石阶上,手里握着一封没有拆开的信。',
|
||||
'风从北面吹来,带着初秋特有的凉意。',
|
||||
'江水在夜里显得格外安静,只有船桨偶尔划破水面。',
|
||||
'她说完这句话,便转身走进了人群,再没有回头。',
|
||||
'灯芯燃到一半,火苗忽然晃了一下,像是被谁惊动了。',
|
||||
'这条路他走过许多次,可这一次的感觉完全不同。',
|
||||
'少年抬头望着天空,觉得云的形状像极了故乡的山。',
|
||||
'账本上的数字一行行排下去,像一条看不到尽头的路。',
|
||||
'雨停之后,屋檐还在滴水,敲在青石板上,一声一声。',
|
||||
];
|
||||
|
||||
// 生成一本"书"的正文:chapterCount 章,每章若干段
|
||||
function generateBook(titleSeed, chapterCount, paragraphsPerChapter) {
|
||||
const parts = [];
|
||||
for (let c = 1; c <= chapterCount; c++) {
|
||||
parts.push(`第${c}章 山中来信`);
|
||||
for (let i = 0; i < paragraphsPerChapter; i++) {
|
||||
const s1 = SENTENCES[(titleSeed + c * 3 + i) % SENTENCES.length];
|
||||
const s2 = SENTENCES[(titleSeed * 2 + c * 7 + i * 3) % SENTENCES.length];
|
||||
parts.push(s1 + s2 + (i % 4 === 0 ? ' 他这样想着,把烟按灭了。' : ''));
|
||||
}
|
||||
parts.push('');
|
||||
}
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
// 预置书架:模拟"以前导入过、已有阅读进度"的状态
|
||||
const MOCK_BOOKS = [
|
||||
{
|
||||
id: 'mock-1',
|
||||
title: '山中来信',
|
||||
importedAt: Date.now() - 6 * 24 * 3600 * 1000,
|
||||
// 进度偏移量在页面初始化时按正文总长度换算
|
||||
progressRatio: 0.35,
|
||||
text: generateBook(1, 12, 40),
|
||||
},
|
||||
{
|
||||
id: 'mock-2',
|
||||
title: '长夜行',
|
||||
importedAt: Date.now() - 2 * 24 * 3600 * 1000,
|
||||
progressRatio: 0.08,
|
||||
text: generateBook(2, 20, 45),
|
||||
},
|
||||
{
|
||||
id: 'mock-3',
|
||||
title: '渡口',
|
||||
importedAt: Date.now() - 12 * 3600 * 1000,
|
||||
progressRatio: 0,
|
||||
text: generateBook(3, 8, 36),
|
||||
},
|
||||
];
|
||||
|
||||
root.MockData = { MOCK_BOOKS, generateBook };
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
@@ -0,0 +1,56 @@
|
||||
// 用 node:test 验证 core.js 的纯逻辑函数
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const Core = require('./core.js');
|
||||
|
||||
test('decodeText: UTF-8 正常解码', () => {
|
||||
const buf = Buffer.from('春江潮水连海平', 'utf8');
|
||||
assert.equal(Core.decodeText(buf), '春江潮水连海平');
|
||||
});
|
||||
|
||||
test('decodeText: GBK 编码回退不乱码', () => {
|
||||
// "山中何所有" 的 GBK 字节序列(Node Buffer 不支持 gbk 编码,手工构造)
|
||||
const buf = new Uint8Array([0xc9, 0xbd, 0xd6, 0xd0, 0xba, 0xce, 0xcb, 0xf9, 0xd3, 0xd0]);
|
||||
const text = Core.decodeText(buf);
|
||||
assert.equal(text, '山中何所有');
|
||||
});
|
||||
|
||||
test('splitParagraphs: 过滤空行并按换行分段', () => {
|
||||
const ps = Core.splitParagraphs('第一段\n\n 第二段 \r\n\r\n第三段');
|
||||
assert.deepEqual(ps, ['第一段', '第二段', '第三段']);
|
||||
});
|
||||
|
||||
test('buildChunks: 按字符数分块且偏移连续', () => {
|
||||
const ps = Core.splitParagraphs('aaa\nbbbb\ncc\nddddd');
|
||||
const chunks = Core.buildChunks(ps, 5);
|
||||
// 段落偏移: 0, 3, 7, 9; 总长 14
|
||||
let covered = 0;
|
||||
for (const c of chunks) {
|
||||
assert.ok(c.items.length > 0);
|
||||
assert.equal(c.startOffset, c.items[0].offset);
|
||||
for (const it of c.items) covered += it.text.length;
|
||||
}
|
||||
assert.equal(covered, 14);
|
||||
});
|
||||
|
||||
test('offsetFromViewport: 二分查找返回视口内段落偏移', () => {
|
||||
const offsets = [0, 10, 20, 30];
|
||||
const tops = [0, 100, 200, 300];
|
||||
assert.equal(Core.offsetFromViewport(offsets, 0, tops), 0);
|
||||
assert.equal(Core.offsetFromViewport(offsets, 150, tops), 10);
|
||||
assert.equal(Core.offsetFromViewport(offsets, 999, tops), 30);
|
||||
});
|
||||
|
||||
test('progressPercent: 边界处理', () => {
|
||||
assert.equal(Core.progressPercent(0, 100), 0);
|
||||
assert.equal(Core.progressPercent(50, 100), 50);
|
||||
assert.equal(Core.progressPercent(200, 100), 100);
|
||||
assert.equal(Core.progressPercent(0, 0), 0);
|
||||
});
|
||||
|
||||
test('formatTime: 格式化为 YYYY-MM-DD HH:mm', () => {
|
||||
assert.equal(Core.formatTime(new Date(2026, 8, 12, 9, 5).getTime()), '2026-09-12 09:05');
|
||||
});
|
||||
Reference in New Issue
Block a user