From 514a84a055b60d1f40d0286fa627de8bc7520b68 Mon Sep 17 00:00:00 2001 From: Guichumo <836061373@qq.com> Date: Sun, 13 Sep 2026 00:41:50 +0800 Subject: [PATCH] chore: ignore demo/ and docs/ and untrack them from repo --- .gitignore | 2 + demo/app.js | 302 ----------------------------------------- demo/core.js | 85 ------------ demo/index.html | 171 ----------------------- demo/mock-data.js | 60 -------- demo/test.mjs | 56 -------- docs/product-design.md | 61 --------- docs/tech-design.md | 111 --------------- 8 files changed, 2 insertions(+), 846 deletions(-) delete mode 100644 demo/app.js delete mode 100644 demo/core.js delete mode 100644 demo/index.html delete mode 100644 demo/mock-data.js delete mode 100644 demo/test.mjs delete mode 100644 docs/product-design.md delete mode 100644 docs/tech-design.md diff --git a/.gitignore b/.gitignore index 7984d8a..9daab54 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ .v2c/ node_modules/ dist/ +demo/ +docs/ diff --git a/demo/app.js b/demo/app.js deleted file mode 100644 index 81d667c..0000000 --- a/demo/app.js +++ /dev/null @@ -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 = ` -
${book.title.slice(0, 1)}
-
-
-
导入于 ${formatTime(book.importedAt)} · 约 ${(book.totalChars / 10000).toFixed(1)} 万字
-
-
-
${pct}%
- - `; - 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(); -})(); diff --git a/demo/core.js b/demo/core.js deleted file mode 100644 index 1548e55..0000000 --- a/demo/core.js +++ /dev/null @@ -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, - }; -}); diff --git a/demo/index.html b/demo/index.html deleted file mode 100644 index 47edac8..0000000 --- a/demo/index.html +++ /dev/null @@ -1,171 +0,0 @@ - - - - - -TXT 阅读器 Demo - - - - - -
-
-

书架

- Demo · 数据为模拟数据 -
-
- - -
- -
-
- - - - - - - - - diff --git a/demo/mock-data.js b/demo/mock-data.js deleted file mode 100644 index c9d9202..0000000 --- a/demo/mock-data.js +++ /dev/null @@ -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); diff --git a/demo/test.mjs b/demo/test.mjs deleted file mode 100644 index c2beaf7..0000000 --- a/demo/test.mjs +++ /dev/null @@ -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'); -}); diff --git a/docs/product-design.md b/docs/product-design.md deleted file mode 100644 index 7884be0..0000000 --- a/docs/product-design.md +++ /dev/null @@ -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. 可调整字号/行距,可删除书籍 diff --git a/docs/tech-design.md b/docs/tech-design.md deleted file mode 100644 index 151f365..0000000 --- a/docs/tech-design.md +++ /dev/null @@ -1,111 +0,0 @@ -# 技术方案 — TXT 电子书阅读器(MVP) - -> 对应产品设计文档:[product-design.md](./product-design.md) -> 形态:**纯 Web 应用**(无后端)。Electron 等桌面壳后置,待出现文件系统/系统集成类需求时再迁移(Web 版代码可直接复用)。 - -## 1. 技术选型总览 - -| 层面 | 选型 | 理由 | -|------|------|------| -| 构建 | Vite 5+ | 零配置起步,开发体验好 | -| 语言 | TypeScript | 编码检测、虚拟滚动、offset 映射均为逻辑密集型,需要类型保障 | -| 框架 | Vue 3 + `