feat: implement TXT reader MVP per product/tech design
- Vite + Vue 3 + TS scaffold with hash router (bookshelf / reader) - core/: encoding detection (UTF-8 strict, GBK fallback, gb18030 last resort), paragraph chunker with original-text offsets, offset utils, IndexedDB wrapper - Reader: windowed paragraph rendering with estimated spacers (constant ~240 DOM paragraphs), font-size/line-height settings via CSS vars persisted to localStorage - Progress: character-offset based, debounced save + flush on back/unload, exact restore via binary search; shelf shows percent - 21 vitest unit tests for core modules
This commit is contained in:
@@ -1,2 +1,4 @@
|
|||||||
.mimosa/
|
.mimosa/
|
||||||
.v2c/
|
.v2c/
|
||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
|||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>TXT 阅读器</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+2381
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "txt-reader",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vue-tsc -b && vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"test": "vitest run"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"jschardet": "^3.1.4",
|
||||||
|
"vue": "^3.5.13",
|
||||||
|
"vue-router": "^4.5.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.20.2",
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"@vue/test-utils": "^2.4.6",
|
||||||
|
"@vue/tsconfig": "^0.7.0",
|
||||||
|
"fake-indexeddb": "^6.0.0",
|
||||||
|
"iconv-lite": "^0.7.3",
|
||||||
|
"typescript": "~5.7.2",
|
||||||
|
"vite": "^6.0.7",
|
||||||
|
"vitest": "^3.0.4",
|
||||||
|
"vue-tsc": "^2.2.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<template>
|
||||||
|
<router-view />
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
// 分块渲染容器(§4):维护已渲染区间 [start, end),随滚动增删段落。
|
||||||
|
// 上下占位符记录未渲染段落的估算高度(按当前窗口实测平均段高 × 段数),
|
||||||
|
// 窗口移动时同步补偿 scrollTop,保证视口锚定的段落不动。
|
||||||
|
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
|
import { paragraphIndexForOffset } from '../core/offset'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
paragraphs: string[]
|
||||||
|
offsets: number[]
|
||||||
|
restoreOffset: number
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
(e: 'offset', offset: number): void
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const BATCH = 30
|
||||||
|
const WINDOW = 240 // 窗口内最多保留的段落数
|
||||||
|
const EDGE = 600 // 距边缘多少像素时触发增删
|
||||||
|
|
||||||
|
const root = ref<HTMLElement | null>(null)
|
||||||
|
const topSpacer = ref<HTMLElement | null>(null)
|
||||||
|
const bottomSpacer = ref<HTMLElement | null>(null)
|
||||||
|
|
||||||
|
let start = 0
|
||||||
|
let end = 0
|
||||||
|
let mounted = false
|
||||||
|
let restoring = false
|
||||||
|
// 窗口内实测平均段高(含 margin),用于估算占位符
|
||||||
|
let avgHeight = 40
|
||||||
|
|
||||||
|
function isChapter(text: string): boolean {
|
||||||
|
return /^第[0-9零一二三四五六七八九十百千两]+[章回节卷]|^序章|^楔子|^后记|^尾声/.test(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
function createNode(idx: number): HTMLElement {
|
||||||
|
const text = props.paragraphs[idx]
|
||||||
|
if (isChapter(text)) {
|
||||||
|
const h = document.createElement('h2')
|
||||||
|
h.className = 'reader-chapter'
|
||||||
|
h.dataset.idx = String(idx)
|
||||||
|
h.textContent = text
|
||||||
|
return h
|
||||||
|
}
|
||||||
|
const p = document.createElement('p')
|
||||||
|
p.className = 'reader-para'
|
||||||
|
p.dataset.idx = String(idx)
|
||||||
|
p.textContent = text
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// 渲染 [a, b) 的段落,插入到 bottomSpacer 之前,返回累计高度
|
||||||
|
function insertRange(a: number, b: number): number {
|
||||||
|
const container = root.value!
|
||||||
|
const sentinel = bottomSpacer.value!
|
||||||
|
let height = 0
|
||||||
|
for (let i = a; i < b; i++) {
|
||||||
|
const node = createNode(i)
|
||||||
|
container.insertBefore(node, sentinel)
|
||||||
|
height += node.offsetHeight
|
||||||
|
}
|
||||||
|
return height
|
||||||
|
}
|
||||||
|
|
||||||
|
// 移除 [a, b) 区间的段落节点
|
||||||
|
function removeRange(a: number, b: number): void {
|
||||||
|
const nodes = root.value!.querySelectorAll<HTMLElement>('[data-idx]')
|
||||||
|
for (const node of nodes) {
|
||||||
|
const idx = Number(node.dataset.idx)
|
||||||
|
if (idx >= a && idx < b) node.remove()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function measureAvg() {
|
||||||
|
const nodes = root.value!.querySelectorAll<HTMLElement>('[data-idx]')
|
||||||
|
if (nodes.length === 0) return
|
||||||
|
let sum = 0
|
||||||
|
for (const n of nodes) sum += n.offsetHeight
|
||||||
|
avgHeight = sum / nodes.length
|
||||||
|
}
|
||||||
|
|
||||||
|
// 占位符高度 = 段数 × 平均段高;返回顶部占位符相对变化量
|
||||||
|
function applySpacers(): number {
|
||||||
|
const total = props.paragraphs.length
|
||||||
|
const ts = topSpacer.value!
|
||||||
|
const oldTop = ts.offsetHeight
|
||||||
|
ts.style.height = start * avgHeight + 'px'
|
||||||
|
bottomSpacer.value!.style.height = (total - end) * avgHeight + 'px'
|
||||||
|
return ts.offsetHeight - oldTop
|
||||||
|
}
|
||||||
|
|
||||||
|
function appendBatch() {
|
||||||
|
const total = props.paragraphs.length
|
||||||
|
if (end >= total) return
|
||||||
|
insertRange(end, Math.min(total, end + BATCH))
|
||||||
|
end = Math.min(total, end + BATCH)
|
||||||
|
measureAvg()
|
||||||
|
trimAbove()
|
||||||
|
root.value!.scrollTop += applySpacers()
|
||||||
|
}
|
||||||
|
|
||||||
|
function prependBatch() {
|
||||||
|
if (start === 0) return
|
||||||
|
const a = Math.max(0, start - BATCH)
|
||||||
|
const firstPara = root.value!.querySelector<HTMLElement>('[data-idx]')
|
||||||
|
for (let i = a; i < start; i++) {
|
||||||
|
root.value!.insertBefore(createNode(i), firstPara)
|
||||||
|
}
|
||||||
|
start = a
|
||||||
|
measureAvg()
|
||||||
|
trimBelow()
|
||||||
|
root.value!.scrollTop += applySpacers()
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimAbove() {
|
||||||
|
const limit = end - WINDOW
|
||||||
|
if (start >= limit) return
|
||||||
|
removeRange(start, limit)
|
||||||
|
start = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimBelow() {
|
||||||
|
const total = props.paragraphs.length
|
||||||
|
const limit = start + WINDOW
|
||||||
|
if (end <= limit) return
|
||||||
|
removeRange(limit, end)
|
||||||
|
end = limit
|
||||||
|
}
|
||||||
|
|
||||||
|
// 当前视口顶部所在段落的字符偏移量
|
||||||
|
function currentOffset(): number {
|
||||||
|
const nodes = root.value!.querySelectorAll<HTMLElement>('[data-idx]')
|
||||||
|
const top = root.value!.scrollTop + 1
|
||||||
|
let best = -1
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (node.offsetTop <= top) {
|
||||||
|
const i = Number(node.dataset.idx)
|
||||||
|
if (best === -1 || i > best) best = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best >= 0 ? props.offsets[best] : props.offsets[0] ?? 0
|
||||||
|
}
|
||||||
|
|
||||||
|
function onScroll() {
|
||||||
|
if (!mounted || restoring) return
|
||||||
|
const el = root.value!
|
||||||
|
if (el.scrollHeight - el.scrollTop - el.clientHeight < EDGE) appendBatch()
|
||||||
|
if (el.scrollTop < EDGE && start > 0) prependBatch()
|
||||||
|
emit('offset', currentOffset())
|
||||||
|
}
|
||||||
|
|
||||||
|
async function restoreTo(offset: number) {
|
||||||
|
if (offset <= 0 || props.offsets.length === 0) return
|
||||||
|
const idx = paragraphIndexForOffset(props.offsets, offset)
|
||||||
|
start = Math.max(0, idx - 10)
|
||||||
|
end = Math.min(props.paragraphs.length, idx + BATCH * 2)
|
||||||
|
insertRange(start, end)
|
||||||
|
measureAvg()
|
||||||
|
// 目标段落在窗口内的位置 + 顶部占位符估算高度 = 绝对滚动位置
|
||||||
|
const target = root.value!.querySelector<HTMLElement>(`[data-idx="${idx}"]`)
|
||||||
|
const innerTop = target ? target.offsetTop : 0
|
||||||
|
applySpacers()
|
||||||
|
root.value!.scrollTop = Math.max(0, innerTop + start * avgHeight - 8)
|
||||||
|
emit('offset', props.offsets[idx])
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
restoring = true
|
||||||
|
mounted = true
|
||||||
|
await restoreTo(props.restoreOffset)
|
||||||
|
if (end === 0) {
|
||||||
|
// 无进度:渲染首屏
|
||||||
|
end = Math.min(props.paragraphs.length, BATCH * 2)
|
||||||
|
insertRange(start, end)
|
||||||
|
measureAvg()
|
||||||
|
applySpacers()
|
||||||
|
root.value!.scrollTop = 0
|
||||||
|
emit('offset', 0)
|
||||||
|
}
|
||||||
|
restoring = false
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
mounted = false
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div ref="root" class="reader-canvas" @scroll.passive="onScroll">
|
||||||
|
<div ref="topSpacer" class="spacer"></div>
|
||||||
|
<div ref="bottomSpacer" class="spacer"></div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.reader-canvas {
|
||||||
|
position: relative;
|
||||||
|
height: 100%;
|
||||||
|
overflow-y: auto;
|
||||||
|
scroll-behavior: auto;
|
||||||
|
}
|
||||||
|
.spacer {
|
||||||
|
width: 1px;
|
||||||
|
}
|
||||||
|
.reader-canvas :deep(.reader-para) {
|
||||||
|
font-size: var(--reader-font-size);
|
||||||
|
line-height: var(--reader-line-height);
|
||||||
|
margin: 0 0 1em;
|
||||||
|
text-indent: 2em;
|
||||||
|
}
|
||||||
|
.reader-canvas :deep(.reader-chapter) {
|
||||||
|
font-size: calc(var(--reader-font-size) + 4px);
|
||||||
|
line-height: var(--reader-line-height);
|
||||||
|
margin: 1.6em 0 1em;
|
||||||
|
font-weight: 600;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
// 字号 / 行距设置:写入 CSS 变量并持久化到 localStorage(§5)
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
const SETTINGS_KEY = 'txt-reader-settings'
|
||||||
|
|
||||||
|
interface Settings {
|
||||||
|
fontSize: number
|
||||||
|
lineHeight: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function load(): Settings {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(SETTINGS_KEY)
|
||||||
|
if (raw) {
|
||||||
|
const s = JSON.parse(raw) as Partial<Settings>
|
||||||
|
return {
|
||||||
|
fontSize: clamp(s.fontSize ?? 18, 14, 28),
|
||||||
|
lineHeight: Math.round(clamp(s.lineHeight ?? 1.9, 1.5, 2.6) * 10) / 10,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* ignore corrupt settings */
|
||||||
|
}
|
||||||
|
return { fontSize: 18, lineHeight: 1.9 }
|
||||||
|
}
|
||||||
|
|
||||||
|
function clamp(v: number, min: number, max: number): number {
|
||||||
|
return Math.min(max, Math.max(min, v))
|
||||||
|
}
|
||||||
|
|
||||||
|
const fontSize = ref(load().fontSize)
|
||||||
|
const lineHeight = ref(load().lineHeight)
|
||||||
|
|
||||||
|
function apply() {
|
||||||
|
document.documentElement.style.setProperty('--reader-font-size', fontSize.value + 'px')
|
||||||
|
document.documentElement.style.setProperty('--reader-line-height', String(lineHeight.value))
|
||||||
|
localStorage.setItem(SETTINGS_KEY, JSON.stringify({ fontSize: fontSize.value, lineHeight: lineHeight.value }))
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeFontSize(delta: number) {
|
||||||
|
fontSize.value = clamp(fontSize.value + delta, 14, 28)
|
||||||
|
apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeLineHeight(delta: number) {
|
||||||
|
lineHeight.value = Math.round(clamp(lineHeight.value + delta, 1.5, 2.6) * 10) / 10
|
||||||
|
apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
apply()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="settings-panel">
|
||||||
|
<div class="row">
|
||||||
|
<span class="label">字号</span>
|
||||||
|
<button class="step" @click="changeFontSize(-2)">A−</button>
|
||||||
|
<span class="value">{{ fontSize }}</span>
|
||||||
|
<button class="step" @click="changeFontSize(2)">A+</button>
|
||||||
|
</div>
|
||||||
|
<div class="row">
|
||||||
|
<span class="label">行距</span>
|
||||||
|
<button class="step" @click="changeLineHeight(-0.1)">−</button>
|
||||||
|
<span class="value">{{ lineHeight.toFixed(1) }}</span>
|
||||||
|
<button class="step" @click="changeLineHeight(0.1)">+</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.settings-panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 14px 18px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
|
||||||
|
}
|
||||||
|
.row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.label {
|
||||||
|
width: 36px;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.value {
|
||||||
|
width: 40px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.step {
|
||||||
|
width: 36px;
|
||||||
|
height: 30px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: var(--color-bg);
|
||||||
|
}
|
||||||
|
.step:hover {
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
// 文本 → 段落切分(§4):按 \n / \r\n 切段,空行只影响视觉段间距(CSS margin),不产生段落
|
||||||
|
export interface Chunk {
|
||||||
|
paragraphs: string[]
|
||||||
|
// paragraphs[i] 首字符在原文中的字符偏移量
|
||||||
|
offsets: number[]
|
||||||
|
totalChars: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export function splitParagraphs(text: string): Chunk {
|
||||||
|
const paragraphs: string[] = []
|
||||||
|
const offsets: number[] = []
|
||||||
|
let i = 0
|
||||||
|
while (i < text.length) {
|
||||||
|
let lineEnd = text.indexOf('\n', i)
|
||||||
|
let next: number
|
||||||
|
if (lineEnd === -1) {
|
||||||
|
lineEnd = text.length
|
||||||
|
next = text.length
|
||||||
|
} else if (lineEnd > i && text[lineEnd - 1] === '\r') {
|
||||||
|
next = lineEnd + 1
|
||||||
|
lineEnd--
|
||||||
|
} else {
|
||||||
|
next = lineEnd + 1
|
||||||
|
}
|
||||||
|
const raw = text.slice(i, lineEnd)
|
||||||
|
const trimmedStart = raw.length - raw.trimStart().length
|
||||||
|
const trimmed = raw.trim()
|
||||||
|
if (trimmed.length > 0) {
|
||||||
|
offsets.push(i + trimmedStart)
|
||||||
|
paragraphs.push(trimmed)
|
||||||
|
}
|
||||||
|
i = next
|
||||||
|
}
|
||||||
|
let total = 0
|
||||||
|
for (const p of paragraphs) total += p.length
|
||||||
|
return { paragraphs, offsets, totalChars: total }
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// IndexedDB 薄封装(§7):单库 txt-reader,books / progress 两个 store
|
||||||
|
export interface BookRecord {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
text: string
|
||||||
|
totalChars: number
|
||||||
|
importedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ProgressRecord {
|
||||||
|
bookId: string
|
||||||
|
offset: number
|
||||||
|
percent: number
|
||||||
|
updatedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const DB_NAME = 'txt-reader'
|
||||||
|
const DB_VERSION = 1
|
||||||
|
|
||||||
|
let dbPromise: Promise<IDBDatabase> | null = null
|
||||||
|
|
||||||
|
function openDb(): Promise<IDBDatabase> {
|
||||||
|
if (dbPromise) return dbPromise
|
||||||
|
dbPromise = new Promise((resolve, reject) => {
|
||||||
|
const req = indexedDB.open(DB_NAME, DB_VERSION)
|
||||||
|
req.onupgradeneeded = () => {
|
||||||
|
const db = req.result
|
||||||
|
if (!db.objectStoreNames.contains('books')) db.createObjectStore('books', { keyPath: 'id' })
|
||||||
|
if (!db.objectStoreNames.contains('progress')) db.createObjectStore('progress', { keyPath: 'bookId' })
|
||||||
|
}
|
||||||
|
req.onsuccess = () => resolve(req.result)
|
||||||
|
req.onerror = () => reject(req.error)
|
||||||
|
})
|
||||||
|
return dbPromise
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestAsPromise<T>(req: IDBRequest<T>): Promise<T> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
req.onsuccess = () => resolve(req.result)
|
||||||
|
req.onerror = () => reject(req.error)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function withStore<T>(
|
||||||
|
name: 'books' | 'progress',
|
||||||
|
mode: IDBTransactionMode,
|
||||||
|
fn: (store: IDBObjectStore) => IDBRequest<T>
|
||||||
|
): Promise<T> {
|
||||||
|
const db = await openDb()
|
||||||
|
const tx = db.transaction(name, mode)
|
||||||
|
return requestAsPromise(fn(tx.objectStore(name)))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function putBook(book: BookRecord): Promise<void> {
|
||||||
|
await withStore('books', 'readwrite', (s) => s.put(book))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getBook(id: string): Promise<BookRecord | undefined> {
|
||||||
|
return withStore('books', 'readonly', (s) => s.get(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listBooks(): Promise<BookRecord[]> {
|
||||||
|
const all = await withStore('books', 'readonly', (s) => s.getAll())
|
||||||
|
return all.sort((a, b) => b.importedAt - a.importedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteBook(id: string): Promise<void> {
|
||||||
|
await withStore('books', 'readwrite', (s) => s.delete(id))
|
||||||
|
await withStore('progress', 'readwrite', (s) => s.delete(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveProgress(progress: ProgressRecord): Promise<void> {
|
||||||
|
await withStore('progress', 'readwrite', (s) => s.put(progress))
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getProgress(bookId: string): Promise<ProgressRecord | undefined> {
|
||||||
|
return withStore('progress', 'readonly', (s) => s.get(bookId))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件名 → 书籍 id:同名文件再导入视为更新(覆盖内容、保留进度)
|
||||||
|
export function bookIdFromFilename(filename: string): string {
|
||||||
|
return filename.replace(/\.txt$/i, '').toLowerCase()
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// 编码检测与解码:UTF-8 优先,失败回退 GBK/GB18030(§3)
|
||||||
|
import jschardet from 'jschardet'
|
||||||
|
|
||||||
|
const SAMPLE_BYTES = 64 * 1024
|
||||||
|
|
||||||
|
function countReplacement(s: string): number {
|
||||||
|
let n = 0
|
||||||
|
for (const ch of s) if (ch === '\uFFFD') n++
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// 严格 UTF-8 解码:失败或含 U+FFFD 视为非 UTF-8
|
||||||
|
function tryUtf8(buffer: ArrayBuffer): string | null {
|
||||||
|
try {
|
||||||
|
const dec = new TextDecoder('utf-8', { fatal: true })
|
||||||
|
const text = dec.decode(buffer)
|
||||||
|
if (text.includes('\uFFFD')) return null
|
||||||
|
return text
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function detectCharset(buffer: ArrayBuffer): string | null {
|
||||||
|
try {
|
||||||
|
const sample = new TextDecoder('latin1').decode(buffer.slice(0, SAMPLE_BYTES))
|
||||||
|
const r = jschardet.detect(sample) as { encoding: string; confidence: number } | null
|
||||||
|
return r && r.confidence > 0.5 ? r.encoding : null
|
||||||
|
} catch {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeWith(charset: string, buffer: ArrayBuffer): string {
|
||||||
|
return new TextDecoder(charset).decode(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解码 TXT 文件为字符串。
|
||||||
|
* 1) UTF-8 严格解码成功即采用;
|
||||||
|
* 2) 否则按 GBK 解码,若替换符比例过高(>0.1%),
|
||||||
|
* 3) 用 jschardet 检测前 64KB 采样的 charset 再试;仍失败则 gb18030 兜底(对任意字节序列均有映射)。
|
||||||
|
*/
|
||||||
|
export function decodeText(buffer: ArrayBuffer): string {
|
||||||
|
const utf8 = tryUtf8(buffer)
|
||||||
|
if (utf8 !== null) return utf8
|
||||||
|
|
||||||
|
const gbk = decodeWith('gbk', buffer)
|
||||||
|
const ratio = countReplacement(gbk) / Math.max(1, gbk.length)
|
||||||
|
if (ratio <= 0.001) return gbk
|
||||||
|
|
||||||
|
const charset = detectCharset(buffer)
|
||||||
|
if (charset) {
|
||||||
|
const normalized = charset.toLowerCase().replace(/[^a-z0-9-]/g, '')
|
||||||
|
const candidates: string[] = []
|
||||||
|
if (normalized.includes('18030')) candidates.push('gb18030')
|
||||||
|
if (normalized.includes('gb')) candidates.push('gbk')
|
||||||
|
if (normalized.includes('big5')) candidates.push('big5')
|
||||||
|
if (normalized.includes('shift')) candidates.push('shift_jis')
|
||||||
|
for (const c of candidates) {
|
||||||
|
try {
|
||||||
|
const text = decodeWith(c, buffer)
|
||||||
|
if (countReplacement(text) / Math.max(1, text.length) <= 0.001) return text
|
||||||
|
} catch {
|
||||||
|
/* unsupported charset, continue */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return decodeWith('gb18030', buffer)
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// 字符偏移量 ↔ 段落索引换算(§6)
|
||||||
|
|
||||||
|
// 二分查找:给定字符 offset,返回它所在段落的索引
|
||||||
|
export function paragraphIndexForOffset(offsets: number[], offset: number): number {
|
||||||
|
if (offsets.length === 0) return -1
|
||||||
|
let lo = 0
|
||||||
|
let hi = offsets.length - 1
|
||||||
|
let ans = 0
|
||||||
|
while (lo <= hi) {
|
||||||
|
const mid = (lo + hi) >> 1
|
||||||
|
if (offsets[mid] <= offset) {
|
||||||
|
ans = mid
|
||||||
|
lo = mid + 1
|
||||||
|
} else {
|
||||||
|
hi = mid - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ans
|
||||||
|
}
|
||||||
|
|
||||||
|
export function progressPercent(offset: number, totalChars: number): number {
|
||||||
|
if (!totalChars) return 0
|
||||||
|
return Math.min(100, Math.max(0, Math.round((offset / totalChars) * 100)))
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
import { router } from './router'
|
||||||
|
import './styles/variables.css'
|
||||||
|
import './styles/main.css'
|
||||||
|
|
||||||
|
createApp(App).use(router).mount('#app')
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { createRouter, createWebHashHistory } from 'vue-router'
|
||||||
|
import BookshelfView from './views/BookshelfView.vue'
|
||||||
|
import ReaderView from './views/ReaderView.vue'
|
||||||
|
|
||||||
|
export const router = createRouter({
|
||||||
|
history: createWebHashHistory(),
|
||||||
|
routes: [
|
||||||
|
{ path: '/', name: 'bookshelf', component: BookshelfView },
|
||||||
|
{ path: '/read/:id', name: 'reader', component: ReaderView },
|
||||||
|
],
|
||||||
|
})
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { reactive } from 'vue'
|
||||||
|
import { listBooks, type BookRecord, getProgress } from '../core/db'
|
||||||
|
import { progressPercent } from '../core/offset'
|
||||||
|
|
||||||
|
export interface ShelfItem {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
totalChars: number
|
||||||
|
importedAt: number
|
||||||
|
percent: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export const bookshelf = reactive({
|
||||||
|
items: [] as ShelfItem[],
|
||||||
|
loading: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
export async function refreshShelf(): Promise<void> {
|
||||||
|
bookshelf.loading = true
|
||||||
|
try {
|
||||||
|
const books: BookRecord[] = await listBooks()
|
||||||
|
const items: ShelfItem[] = []
|
||||||
|
for (const b of books) {
|
||||||
|
const p = await getProgress(b.id)
|
||||||
|
items.push({
|
||||||
|
id: b.id,
|
||||||
|
title: b.title,
|
||||||
|
totalChars: b.totalChars,
|
||||||
|
importedAt: b.importedAt,
|
||||||
|
percent: p ? p.percent : 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
bookshelf.items = items
|
||||||
|
} finally {
|
||||||
|
bookshelf.loading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { progressPercent }
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--color-bg);
|
||||||
|
color: var(--color-text);
|
||||||
|
font-family: 'PingFang SC', 'Microsoft YaHei', 'Noto Sans CJK SC', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
:root {
|
||||||
|
/* 明亮主题:所有颜色收拢到变量,便于后续扩展深色/护眼主题 */
|
||||||
|
--color-bg: #f5f4f0;
|
||||||
|
--color-surface: #ffffff;
|
||||||
|
--color-text: #2b2b2b;
|
||||||
|
--color-text-secondary: #8a8a8a;
|
||||||
|
--color-border: #e3e1db;
|
||||||
|
--color-accent: #4a7c59;
|
||||||
|
--color-accent-light: #e7efe9;
|
||||||
|
--color-danger: #c0392b;
|
||||||
|
|
||||||
|
/* 阅读设置(运行时由设置面板覆写) */
|
||||||
|
--reader-font-size: 18px;
|
||||||
|
--reader-line-height: 1.9;
|
||||||
|
--reader-max-width: 720px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { decodeText } from '../core/encoding'
|
||||||
|
import { splitParagraphs } from '../core/chunker'
|
||||||
|
import { putBook, deleteBook, getProgress, bookIdFromFilename } from '../core/db'
|
||||||
|
import { bookshelf, refreshShelf } from '../store/bookshelf'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const fileInput = ref<HTMLInputElement | null>(null)
|
||||||
|
const importing = ref(false)
|
||||||
|
|
||||||
|
onMounted(refreshShelf)
|
||||||
|
|
||||||
|
function pickFiles() {
|
||||||
|
fileInput.value?.click()
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtTime(ts: number): string {
|
||||||
|
const d = new Date(ts)
|
||||||
|
const p = (n: number) => String(n).padStart(2, '0')
|
||||||
|
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function fmtChars(n: number): string {
|
||||||
|
return n >= 10000 ? `${(n / 10000).toFixed(1)} 万字` : `${n} 字`
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onFilesChosen(e: Event) {
|
||||||
|
const input = e.target as HTMLInputElement
|
||||||
|
const files = input.files
|
||||||
|
if (!files || files.length === 0) return
|
||||||
|
importing.value = true
|
||||||
|
try {
|
||||||
|
for (const file of files) {
|
||||||
|
const buffer = await file.arrayBuffer()
|
||||||
|
const text = decodeText(buffer)
|
||||||
|
const { totalChars } = splitParagraphs(text)
|
||||||
|
const id = bookIdFromFilename(file.name)
|
||||||
|
await putBook({
|
||||||
|
id,
|
||||||
|
title: file.name.replace(/\.txt$/i, ''),
|
||||||
|
text,
|
||||||
|
totalChars,
|
||||||
|
importedAt: Date.now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
await refreshShelf()
|
||||||
|
} finally {
|
||||||
|
importing.value = false
|
||||||
|
input.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openBook(id: string) {
|
||||||
|
// 离开书架前进阅读页,进度恢复在阅读页完成
|
||||||
|
await router.push(`/read/${encodeURIComponent(id)}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeBook(id: string) {
|
||||||
|
const item = bookshelf.items.find((b) => b.id === id)
|
||||||
|
if (!confirm(`确定删除《${item?.title ?? id}》?删除后进度不可恢复。`)) return
|
||||||
|
await deleteBook(id)
|
||||||
|
await refreshShelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 书架卡片需要展示"是否有进度"以外还想知道更新时间,这里取进度记录
|
||||||
|
async function touchProgress(id: string) {
|
||||||
|
await getProgress(id)
|
||||||
|
}
|
||||||
|
void touchProgress
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="shelf-page">
|
||||||
|
<header class="shelf-header">
|
||||||
|
<h1>书架</h1>
|
||||||
|
<button class="btn btn-primary" :disabled="importing" @click="pickFiles">
|
||||||
|
{{ importing ? '导入中…' : '导入 TXT' }}
|
||||||
|
</button>
|
||||||
|
<input ref="fileInput" type="file" accept=".txt,text/plain" multiple hidden @change="onFilesChosen" />
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<p v-if="bookshelf.items.length === 0 && !bookshelf.loading" class="empty">
|
||||||
|
书架还是空的,导入一个 .txt 文件开始阅读吧。
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<ul class="book-list">
|
||||||
|
<li v-for="item in bookshelf.items" :key="item.id" class="book-card" @click="openBook(item.id)">
|
||||||
|
<div class="cover">{{ item.title.slice(0, 1) }}</div>
|
||||||
|
<div class="info">
|
||||||
|
<div class="title">{{ item.title }}</div>
|
||||||
|
<div class="meta">导入于 {{ fmtTime(item.importedAt) }} · {{ fmtChars(item.totalChars) }}</div>
|
||||||
|
<div class="progress-bar">
|
||||||
|
<div class="progress-fill" :style="{ width: item.percent + '%' }"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="percent">{{ item.percent }}%</div>
|
||||||
|
<button class="btn-delete" @click.stop="removeBook(item.id)">删除</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.shelf-page {
|
||||||
|
max-width: 720px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 24px 16px;
|
||||||
|
}
|
||||||
|
.shelf-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
.shelf-header h1 {
|
||||||
|
font-size: 22px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.btn {
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
}
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--color-accent);
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
.empty {
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
text-align: center;
|
||||||
|
padding: 48px 0;
|
||||||
|
}
|
||||||
|
.book-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.book-card {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 14px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.book-card:hover {
|
||||||
|
border-color: var(--color-accent);
|
||||||
|
}
|
||||||
|
.cover {
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--color-accent-light);
|
||||||
|
color: var(--color-accent);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 20px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.info {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.title {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.meta {
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: 12px;
|
||||||
|
margin: 4px 0 6px;
|
||||||
|
}
|
||||||
|
.progress-bar {
|
||||||
|
height: 4px;
|
||||||
|
border-radius: 2px;
|
||||||
|
background: var(--color-border);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.progress-fill {
|
||||||
|
height: 100%;
|
||||||
|
background: var(--color-accent);
|
||||||
|
}
|
||||||
|
.percent {
|
||||||
|
width: 44px;
|
||||||
|
text-align: right;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.btn-delete {
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-size: 13px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
// 阅读页:加载书籍 → 恢复进度 → 节流保存 offset(§6)
|
||||||
|
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import ReaderCanvas from '../components/ReaderCanvas.vue'
|
||||||
|
import SettingsPanel from '../components/SettingsPanel.vue'
|
||||||
|
import { getBook, saveProgress, getProgress } from '../core/db'
|
||||||
|
import { splitParagraphs, type Chunk } from '../core/chunker'
|
||||||
|
import { progressPercent } from '../core/offset'
|
||||||
|
import { refreshShelf } from '../store/bookshelf'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const title = ref('')
|
||||||
|
const chunk = ref<Chunk | null>(null)
|
||||||
|
const restoreOffset = ref(0)
|
||||||
|
const percent = ref(0)
|
||||||
|
const showSettings = ref(false)
|
||||||
|
const notFound = ref(false)
|
||||||
|
|
||||||
|
const SAVE_INTERVAL_MS = 2000
|
||||||
|
|
||||||
|
let lastSavedOffset = 0
|
||||||
|
let lastSaveAt = 0
|
||||||
|
let saveTimer: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
// 离开页面时 route.params 已失效,bookId 必须在进入时捕获
|
||||||
|
const bookId = decodeURIComponent(String(route.params.id))
|
||||||
|
|
||||||
|
function onOffsetChange(offset: number) {
|
||||||
|
percent.value = progressPercent(offset, chunk.value?.totalChars ?? 0)
|
||||||
|
lastSavedOffset = offset
|
||||||
|
// 防抖尾随保存:滚动停止 1s 后落库,保证最后位置不丢
|
||||||
|
if (saveTimer) clearTimeout(saveTimer)
|
||||||
|
saveTimer = setTimeout(() => {
|
||||||
|
saveTimer = null
|
||||||
|
persist(lastSavedOffset)
|
||||||
|
}, 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
function persist(offset: number) {
|
||||||
|
if (!chunk.value) return
|
||||||
|
if (saveTimer) {
|
||||||
|
clearTimeout(saveTimer)
|
||||||
|
saveTimer = null
|
||||||
|
}
|
||||||
|
lastSavedOffset = offset
|
||||||
|
lastSaveAt = Date.now()
|
||||||
|
void saveProgress({
|
||||||
|
bookId,
|
||||||
|
offset,
|
||||||
|
percent: progressPercent(offset, chunk.value.totalChars),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兜底:离开页面 / 关闭标签页时把最新 offset 写库
|
||||||
|
function flushOnHide() {
|
||||||
|
if (document.visibilityState === 'hidden' && lastSavedOffset > 0) persist(lastSavedOffset)
|
||||||
|
}
|
||||||
|
|
||||||
|
function goBack() {
|
||||||
|
persist(lastSavedOffset)
|
||||||
|
void refreshShelf()
|
||||||
|
void router.push('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
document.addEventListener('visibilitychange', flushOnHide)
|
||||||
|
const book = await getBook(bookId)
|
||||||
|
if (!book) {
|
||||||
|
notFound.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
title.value = book.title
|
||||||
|
// 先取进度再渲染,保证 ReaderCanvas 挂载时 restoreOffset 就绪
|
||||||
|
const p = await getProgress(book.id)
|
||||||
|
restoreOffset.value = p ? p.offset : 0
|
||||||
|
percent.value = p ? p.percent : 0
|
||||||
|
// 未发生滚动就退出时,不应把进度覆写回 0
|
||||||
|
lastSavedOffset = restoreOffset.value
|
||||||
|
chunk.value = splitParagraphs(book.text)
|
||||||
|
})
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
document.removeEventListener('visibilitychange', flushOnHide)
|
||||||
|
persist(lastSavedOffset)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="reader-page">
|
||||||
|
<header class="reader-header">
|
||||||
|
<button class="back" @click="goBack">‹ 返回</button>
|
||||||
|
<div class="title">{{ title }}</div>
|
||||||
|
<div class="right">
|
||||||
|
<span class="percent">{{ percent }}%</span>
|
||||||
|
<button class="settings-btn" @click="showSettings = !showSettings">设置</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<transition name="fade">
|
||||||
|
<div v-if="showSettings" class="settings-float">
|
||||||
|
<SettingsPanel />
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
|
||||||
|
<p v-if="notFound" class="not-found">找不到这本书,可能已被删除。</p>
|
||||||
|
<ReaderCanvas
|
||||||
|
v-else-if="chunk"
|
||||||
|
class="reader-body"
|
||||||
|
:paragraphs="chunk.paragraphs"
|
||||||
|
:offsets="chunk.offsets"
|
||||||
|
:restore-offset="restoreOffset"
|
||||||
|
@offset="onOffsetChange"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.reader-page {
|
||||||
|
height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.reader-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 16px;
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.title {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
font-size: 15px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
.back,
|
||||||
|
.settings-btn {
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
background: var(--color-surface);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 6px 12px;
|
||||||
|
font-size: 14px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.percent {
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
min-width: 38px;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
.settings-float {
|
||||||
|
position: fixed;
|
||||||
|
top: 56px;
|
||||||
|
right: 16px;
|
||||||
|
z-index: 10;
|
||||||
|
}
|
||||||
|
.fade-enter-active,
|
||||||
|
.fade-leave-active {
|
||||||
|
transition: opacity 0.15s ease;
|
||||||
|
}
|
||||||
|
.fade-enter-from,
|
||||||
|
.fade-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
.not-found {
|
||||||
|
text-align: center;
|
||||||
|
color: var(--color-text-secondary);
|
||||||
|
padding: 48px 0;
|
||||||
|
}
|
||||||
|
.reader-body {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
max-width: var(--reader-max-width);
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 16px 16px 48px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { splitParagraphs } from '../src/core/chunker'
|
||||||
|
|
||||||
|
describe('splitParagraphs', () => {
|
||||||
|
it('按 \\n 切分并去除首尾空白', () => {
|
||||||
|
const { paragraphs } = splitParagraphs(' 第一段 \n第二段\n\n 第三段 ')
|
||||||
|
expect(paragraphs).toEqual(['第一段', '第二段', '第三段'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('处理 \\r\\n 换行', () => {
|
||||||
|
const { paragraphs } = splitParagraphs('甲\r\n乙\r\n丙')
|
||||||
|
expect(paragraphs).toEqual(['甲', '乙', '丙'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('空行不产生段落,连续空行只算段间距', () => {
|
||||||
|
const { paragraphs } = splitParagraphs('a\n\n\n\nb')
|
||||||
|
expect(paragraphs).toEqual(['a', 'b'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('offsets 与原文对齐:slice 反向校验', () => {
|
||||||
|
const text = '第一段落内容\n\n第二段落:很长一点。\r\n第三段'
|
||||||
|
const { paragraphs, offsets } = splitParagraphs(text)
|
||||||
|
for (let i = 0; i < paragraphs.length; i++) {
|
||||||
|
const end = i + 1 < offsets.length ? offsets[i + 1] : text.length
|
||||||
|
// 该段文本必然出现在 text.slice(offsets[i], end) 中
|
||||||
|
expect(text.slice(offsets[i], end)).toContain(paragraphs[i])
|
||||||
|
}
|
||||||
|
expect(text.slice(offsets[0], offsets[0] + paragraphs[0].length)).toBe(paragraphs[0])
|
||||||
|
expect(text.slice(offsets[1], offsets[1] + paragraphs[1].length)).toBe(paragraphs[1])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('totalChars 等于各段长度之和', () => {
|
||||||
|
const { paragraphs, offsets, totalChars } = splitParagraphs('hello\nworld!')
|
||||||
|
expect(totalChars).toBe(paragraphs.reduce((n, p) => n + p.length, 0))
|
||||||
|
expect(totalChars).toBe(11)
|
||||||
|
expect(offsets).toEqual([0, 6])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('空文本返回空结果', () => {
|
||||||
|
const r = splitParagraphs('')
|
||||||
|
expect(r.paragraphs).toEqual([])
|
||||||
|
expect(r.offsets).toEqual([])
|
||||||
|
expect(r.totalChars).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('大文本性能与正确性:10 万段', () => {
|
||||||
|
const text = Array.from({ length: 100000 }, (_, i) => `第${i}段内容`).join('\n')
|
||||||
|
const r = splitParagraphs(text)
|
||||||
|
expect(r.paragraphs.length).toBe(100000)
|
||||||
|
expect(r.offsets.length).toBe(100000)
|
||||||
|
expect(text.slice(r.offsets[99999], r.offsets[99999] + 10)).toBe(r.paragraphs[99999])
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import * as iconv from 'iconv-lite'
|
||||||
|
import { decodeText } from '../src/core/encoding'
|
||||||
|
|
||||||
|
function bytes(...groups: Array<number[] | string>): ArrayBuffer {
|
||||||
|
const parts: number[] = []
|
||||||
|
for (const g of groups) {
|
||||||
|
if (typeof g === 'string') for (const ch of g) parts.push(ch.charCodeAt(0))
|
||||||
|
else parts.push(...g)
|
||||||
|
}
|
||||||
|
return new Uint8Array(parts).buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
function encode(text: string, enc: 'gbk' | 'gb18030'): ArrayBuffer {
|
||||||
|
const buf = iconv.encode(text, enc)
|
||||||
|
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
|
||||||
|
}
|
||||||
|
|
||||||
|
const utf8Text = '第一行:Hello 世界!\n第二行:编码检测测试。'
|
||||||
|
|
||||||
|
describe('decodeText', () => {
|
||||||
|
it('UTF-8 文本正确解码', () => {
|
||||||
|
const buf = Buffer.from(utf8Text, 'utf8')
|
||||||
|
expect(decodeText(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))).toBe(utf8Text)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GBK 中文文本回退正确、无乱码', () => {
|
||||||
|
expect(decodeText(encode('白日依山尽,黄河入海流。', 'gbk'))).toBe('白日依山尽,黄河入海流。')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('GB18030 生僻字文本正确解码', () => {
|
||||||
|
const text = '魜喡玤嘦(生僻字测试)'
|
||||||
|
expect(decodeText(encode(text, 'gb18030'))).not.toContain('\uFFFD')
|
||||||
|
expect(decodeText(encode(text, 'gb18030'))).toContain('生僻字测试')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('不含 U+FFFD 即视为成功:UTF-8 带 BOM', () => {
|
||||||
|
const buf = Buffer.from('\uFEFF' + utf8Text, 'utf8')
|
||||||
|
const out = decodeText(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength))
|
||||||
|
expect(out).toContain('Hello 世界')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('异常字节不崩溃', () => {
|
||||||
|
expect(() => decodeText(bytes([0xff, 0xfe, 0x00, 0x41]))).not.toThrow()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('空文件返回空字符串', () => {
|
||||||
|
expect(decodeText(new ArrayBuffer(0))).toBe('')
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { paragraphIndexForOffset, progressPercent } from '../src/core/offset'
|
||||||
|
import { splitParagraphs } from '../src/core/chunker'
|
||||||
|
|
||||||
|
describe('paragraphIndexForOffset', () => {
|
||||||
|
const offsets = [0, 10, 20, 30]
|
||||||
|
|
||||||
|
it('命中段落起点返回该段', () => {
|
||||||
|
expect(paragraphIndexForOffset(offsets, 0)).toBe(0)
|
||||||
|
expect(paragraphIndexForOffset(offsets, 10)).toBe(1)
|
||||||
|
expect(paragraphIndexForOffset(offsets, 30)).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('段落中间的 offset 归属该段', () => {
|
||||||
|
expect(paragraphIndexForOffset(offsets, 15)).toBe(1)
|
||||||
|
expect(paragraphIndexForOffset(offsets, 29)).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('超出末尾归属最后一段', () => {
|
||||||
|
expect(paragraphIndexForOffset(offsets, 100)).toBe(3)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('空数组返回 -1', () => {
|
||||||
|
expect(paragraphIndexForOffset([], 0)).toBe(-1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('与 chunker 联动:任意 offset 定位到正确段落', () => {
|
||||||
|
const text = Array.from({ length: 50 }, (_, i) => `段落${i}:${'内容'.repeat(i + 1)}`).join('\n\n')
|
||||||
|
const { paragraphs, offsets, totalChars } = splitParagraphs(text)
|
||||||
|
for (const target of [0, 1, totalChars - 1, Math.floor(totalChars / 2)]) {
|
||||||
|
const idx = paragraphIndexForOffset(offsets, target)
|
||||||
|
expect(text.slice(offsets[idx], offsets[idx] + paragraphs[idx].length)).toBe(paragraphs[idx])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('progressPercent', () => {
|
||||||
|
it('常规计算并四舍五入', () => {
|
||||||
|
expect(progressPercent(0, 1000)).toBe(0)
|
||||||
|
expect(progressPercent(500, 1000)).toBe(50)
|
||||||
|
expect(progressPercent(1234, 10000)).toBe(12)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('上限 100,下限 0', () => {
|
||||||
|
expect(progressPercent(1200, 1000)).toBe(100)
|
||||||
|
expect(progressPercent(-5, 1000)).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('总字数为 0 时不产生 NaN', () => {
|
||||||
|
expect(progressPercent(0, 0)).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||||
|
"types": ["node"],
|
||||||
|
"baseUrl": ".",
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.vue", "tests/**/*.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"files": [],
|
||||||
|
"references": [
|
||||||
|
{ "path": "./tsconfig.app.json" },
|
||||||
|
{ "path": "./tsconfig.node.json" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2023"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"noEmit": true,
|
||||||
|
"composite": true,
|
||||||
|
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
})
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: 'node',
|
||||||
|
include: ['tests/**/*.test.ts'],
|
||||||
|
},
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user