chore: ignore demo/ and docs/ and untrack them from repo

This commit is contained in:
2026-09-13 00:41:50 +08:00
parent 78a67b5f97
commit 514a84a055
8 changed files with 2 additions and 846 deletions
+2
View File
@@ -2,3 +2,5 @@
.v2c/ .v2c/
node_modules/ node_modules/
dist/ dist/
demo/
docs/
-302
View File
@@ -1,302 +0,0 @@
(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();
})();
-85
View File
@@ -1,85 +0,0 @@
// 纯逻辑函数,供页面与测试共用(可在 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
View File
@@ -1,171 +0,0 @@
<!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>
-60
View File
@@ -1,60 +0,0 @@
// 模拟数据:预置几本"书",用程序生成的正文代替真实文件
(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);
-56
View File
@@ -1,56 +0,0 @@
// 用 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');
});
-61
View File
@@ -1,61 +0,0 @@
# 电子书阅读器 — 产品设计文档(MVP)
## 1. 产品定位
一个轻量的本地 TXT 电子书阅读器,解决"把一本书读完"的最基本需求:导入、阅读、记住进度。
- **形态**:纯网页应用(无后端),数据存储在浏览器 IndexedDB
- **首版格式**:仅支持 TXT 文本文件
- **原则**:最短路径闭环,所有增强功能后置迭代
## 2. MVP 功能范围
### 2.1 导入 TXT
- 通过文件选择器导入 `.txt` 文件
- **编码自动检测**:优先按 UTF-8 解码,检测到乱码/失败时回退 GBK/GB18030(中文 TXT 常见编码),保证导入不乱码
- 导入后自动登记到书架
### 2.2 书架
- 展示已导入的书籍列表(书名、导入时间、阅读进度)
- 点击进入阅读;支持删除书籍
- 再次导入同名文件视为更新/重新导入
### 2.3 阅读页
- 以滚动方式连续阅读正文
- 基本阅读设置:字号大小、行距
- 仅明亮主题(颜色统一收拢到 CSS 变量,便于后续扩展深色/护眼主题)
### 2.4 进度记忆
- 以**字符偏移量(offset)**记录阅读位置,退出后重新打开自动恢复到上次位置
- 书架中显示进度百分比
## 3. 技术要点与约束
| 事项 | 决策 |
|------|------|
| 存储 | IndexedDB:存原始文本(或 Blob)、元数据、进度 |
| 编码检测 | UTF-8 优先,失败回退 GBK/GB18030;可选 jschardet 辅助 |
| 大文件渲染 | 不一次性渲染全文;按段落分块/切片,滚动按需渲染,避免长篇小说卡死 |
| 进度定位 | 字符偏移量,与窗口尺寸无关,可精确恢复 |
| 主题 | 颜色变量化,仅明亮主题 |
## 4. 明确不做(后续迭代候选)
- EPUB / PDF / MOBI 等格式
- 深色、护眼主题
- 书签、划线、批注、笔记
- 目录/章节(备注:后续可用正则识别"第X章"等模式生成伪目录)
- 书内搜索
- 云同步、多设备
- 阅读统计、阅读目标
## 5. 验收标准(MVP 完成的定义)
1. 导入一个 GBK 编码的中文 TXT,正文无乱码
2. 导入一个数 MB 的长篇小说,滚动阅读流畅
3. 关闭页面后重新打开,自动回到上次阅读位置,书架显示正确进度
4. 可调整字号/行距,可删除书籍
-111
View File
@@ -1,111 +0,0 @@
# 技术方案 — TXT 电子书阅读器(MVP)
> 对应产品设计文档:[product-design.md](./product-design.md)
> 形态:**纯 Web 应用**(无后端)。Electron 等桌面壳后置,待出现文件系统/系统集成类需求时再迁移(Web 版代码可直接复用)。
## 1. 技术选型总览
| 层面 | 选型 | 理由 |
|------|------|------|
| 构建 | Vite 5+ | 零配置起步,开发体验好 |
| 语言 | TypeScript | 编码检测、虚拟滚动、offset 映射均为逻辑密集型,需要类型保障 |
| 框架 | Vue 3 + `<script setup>` | 页面仅 2~3 个,只需要轻量状态管理与组件化;也可换 React,方案不受影响 |
| 路由 | vue-router(hash 模式) | 书架 / 阅读页两个路由;hash 模式便于静态部署 |
| 存储 | IndexedDB(原生 API,薄封装) | 文档已定;数据量不大,不必引入 Dexie(可选) |
| 编码检测 | `TextDecoder` + `jschardet` 辅助 | 见 §3 |
| 测试 | Vitest | 纯逻辑模块单元测试 |
| 样式 | 原生 CSS + CSS 变量 | 主题颜色收拢到变量,满足后续扩展 |
不引入的依赖及原因:
- **UI 组件库**:页面结构极简,自己写样式成本更低、体积更小。
- **状态管理库(Pinia)**:仅书架列表一个全局状态,用 `reactive` 单例即可。
- **虚拟列表库**:阅读器按"段落 → DOM 节点"增量插入,与通用虚拟列表模型不同,手写更贴合(见 §5)。
## 2. 项目结构
```
src/
main.ts # 入口
App.vue
router.ts
core/ # 纯逻辑模块,不依赖 Vue,全部可单测
encoding.ts # 编码检测与解码(§3)
chunker.ts # 文本 → 段落分块(§4)
offset.ts # 字符偏移量 ↔ 滚动位置换算(§6)
db.ts # IndexedDB 薄封装(§7)
store/
bookshelf.ts # 书架状态(reactive 单例)
views/
BookshelfView.vue # 书架
ReaderView.vue # 阅读页
components/
ReaderCanvas.vue # 分块渲染容器
SettingsPanel.vue # 字号 / 行距
styles/
variables.css # 颜色 / 字号 / 行距 CSS 变量(明亮主题)
tests/
encoding.test.ts
chunker.test.ts
offset.test.ts
```
原则:**所有可测试逻辑收拢在 `core/`,Vue 层只做视图绑定。**
## 3. 编码检测(core/encoding.ts)
1. 读文件为 `ArrayBuffer`。
2. 先按 UTF-8 严格解码:`new TextDecoder('utf-8', { fatal: true })`。成功且结果中不含 U+FFFD → 采用。
3. 失败则回退:`new TextDecoder('gbk')`(浏览器原生支持,覆盖 GBK/GB2312;GB18030 场景同样先尝试 gbk,结果异常时换 `gb18030`)。
4. 若 gbk 解码仍含大量 U+FFFD(如 > 0.1%),用 `jschardet.detect()`(作用于前 64KB)给出的 charset 再尝试一次;仍失败则按 `gb18030` 兜底(GB18030 对任意字节序列均有映射)。
注意:
- 检测只针对前 64KB 采样,避免大文件全量扫描。
- 该模块是验收标准 1(GBK 无乱码)的关键,必须有单元测试覆盖:UTF-8、GBK、GB18030、混合异常字节用例。
## 4. 文本分块(core/chunker.ts)
- 导入时**不做**重排,原文以解码后的字符串(或 Blob)整体入库;分块是**渲染期**行为。
- `chunker.split(text)`:按 `\n`(及 `\r\n`)切分为段落数组,空行合并为段间距;返回 `{ paragraphs: string[], offsets: number[] }`,`offsets[i]` 为第 i 段在原文中的字符偏移量——这是进度恢复的桥梁。
- 渲染:阅读器容器内维护"已渲染区间 `[start, end)`",随滚动通过 IntersectionObserver 哨兵节点向前后各追加 N 段(如 30 段)、移除远离窗口的段落,保证 DOM 节点数恒定在数百以内。
## 5. 阅读页交互
- **设置**:字号、行距写入 CSS 变量(`--reader-font-size`、`--reader-line-height`),持久化到 localStorage。
- **主题**:颜色全部定义在 `styles/variables.css`,本期仅明亮主题。
- **重排与进度**:字号/行距变化会引起重排,进度恢复只依赖字符偏移量,不受窗口/字号影响(见 §6)。
## 6. 进度记忆(core/offset.ts)
- 阅读时以节流方式(如每 2s 或滚动停止 500ms)计算当前视口顶部所在段落的字符偏移量 `offset`,连同 `{ bookId, offset, updatedAt, percent }` 写入 IndexedDB。
- 恢复:打开书后先完成首屏渲染,再根据 `offset` 二分 `offsets[]` 定位段落,`scrollIntoView` 到该段。
- 百分比:`offset / totalChars`,显示在书架卡片上。
## 7. 数据模型(core/db.ts)
IndexedDB 单库 `txt-reader`,两个 store:
- `books`(keyPath: `id`)
- `id`: 文件名 hash(同名再导入视为更新,覆盖文本与元数据,保留阅读进度)
- `{ id, title, text, totalChars, importedAt }`
- `progress`(keyPath: `bookId`)
- `{ bookId, offset, percent, updatedAt }`
封装为 Promise 风格的 ~6 个函数(`putBook / getBook / listBooks / deleteBook / saveProgress / getProgress`),不引第三方库。
## 8. 测试计划
按 AGENTS.md 要求,每次改动交付前全部测试通过:
- `encoding.test.ts`:UTF-8 / GBK / GB18030 样本解码正确,异常字节不崩溃。
- `chunker.test.ts`:段落切分正确、`offsets` 与原文对齐(可用 `text.slice(offsets[i], offsets[i+1])` 反向校验)。
- `offset.test.ts`:给定 offset 能定位正确段落索引;百分比计算正确。
- 手动验收:产品文档 §5 的四条验收标准(GBK 导入、大文件流畅、进度恢复、设置与删除)。
## 9. 里程碑
1. **M1 骨架**:Vite + Vue3 脚手架,两个路由跑通,IndexedDB 封装 + 单测。
2. **M2 导入闭环**:编码检测 + 入库 + 书架展示/删除(验收 1、4 的前半)。
3. **M3 阅读器**:分块渲染 + 设置面板(验收 2)。
4. **M4 进度**:offset 记录与恢复(验收 3、4 完整闭环)。