- 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
51 lines
1.8 KiB
TypeScript
51 lines
1.8 KiB
TypeScript
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('')
|
|
})
|
|
})
|