Files
QueryByHumming/tests/offset.test.ts
T
836061373 24373e298a 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
2026-09-13 00:28:06 +08:00

53 lines
1.8 KiB
TypeScript
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.
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)
})
})