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) }) })