Files
QueryByHumming/demo/core.js
T

86 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 纯逻辑函数,供页面与测试共用(可在 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,
};
});