diff --git a/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.json b/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.json
new file mode 100644
index 0000000..9cb5280
--- /dev/null
+++ b/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.json
@@ -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"}
\ No newline at end of file
diff --git a/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.mtykkxc9-41204-352eee7f13.baseline/e07d531ac040ce3f40e0ce632ac2a059d7cd60f20e61f78268ac3be015b3b28f.source b/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.mtykkxc9-41204-352eee7f13.baseline/e07d531ac040ce3f40e0ce632ac2a059d7cd60f20e61f78268ac3be015b3b28f.source
new file mode 100644
index 0000000..f07402c
--- /dev/null
+++ b/demo/.mimosa/hook-state/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921.mtykkxc9-41204-352eee7f13.baseline/e07d531ac040ce3f40e0ce632ac2a059d7cd60f20e61f78268ac3be015b3b28f.source
@@ -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 = `
+
${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();
+ 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/.mimosa/hook-status/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921-7a57f0cbd7.json b/demo/.mimosa/hook-status/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921-7a57f0cbd7.json
new file mode 100644
index 0000000..046fe55
--- /dev/null
+++ b/demo/.mimosa/hook-status/sess_83bd86da-4bfb-41d3-9b5b-9be1ec259921-7a57f0cbd7.json
@@ -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/"
+}
diff --git a/demo/app.js b/demo/app.js
new file mode 100644
index 0000000..81d667c
--- /dev/null
+++ b/demo/app.js
@@ -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 = `
+ ${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
new file mode 100644
index 0000000..1548e55
--- /dev/null
+++ b/demo/core.js
@@ -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,
+ };
+});
diff --git a/demo/index.html b/demo/index.html
new file mode 100644
index 0000000..47edac8
--- /dev/null
+++ b/demo/index.html
@@ -0,0 +1,171 @@
+
+
+
+
+
+TXT 阅读器 Demo
+
+
+
+
+
+
+
+
+
+
+
+
书架空空的,导入一本 TXT 开始阅读吧
+
+
+
+
+
+
+
+
+ 字号
+
+ 18
+
+
+
+ 行距
+
+ 1.9
+
+
+
+
+
+
+
+
+
+
+
diff --git a/demo/mock-data.js b/demo/mock-data.js
new file mode 100644
index 0000000..c9d9202
--- /dev/null
+++ b/demo/mock-data.js
@@ -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);
diff --git a/demo/test.mjs b/demo/test.mjs
new file mode 100644
index 0000000..c2beaf7
--- /dev/null
+++ b/demo/test.mjs
@@ -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');
+});