feat: add TXT reader demo with mock data (bookshelf, reader, progress restore)

This commit is contained in:
2026-09-13 00:00:59 +08:00
parent 555ee92eb8
commit f714d006b6
8 changed files with 991 additions and 0 deletions
+85
View File
@@ -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,
};
});