Skip to content

Commit 0dbbdea

Browse files
Lee Seongjooclaude
andcommitted
crawl: extract char-weighted progress into testable CrawlLayout.fraction
Move the crawl-fraction math out of AppState into CrawlLayout.fraction so it can be unit-tested, and drop the now-unused per-chunk sentence helpers (currentChunkText / currentSentences / currentSentenceIndex). Adds tests for CrawlLayout.fraction plus a hard-cut and a multi-line math-leak case. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
1 parent 5696129 commit 0dbbdea

3 files changed

Lines changed: 27 additions & 35 deletions

File tree

‎Sources/App/AppState.swift‎

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -178,32 +178,6 @@ final class AppState: ObservableObject {
178178
@Published var chunkSeconds: Double = 0 // seconds into the current paragraph
179179
@Published var chunkSentenceTimes: [[Double]] = [] // exact sentence start times per chunk (ElevenLabs); [] = estimate
180180
var showSubtitle: Bool { playbackMode == .tts ? subtitleTTS : subtitleExplain }
181-
var currentChunkText: String {
182-
let i = chunkIndex - 1
183-
return spokenChunks.indices.contains(i) ? spokenChunks[i] : ""
184-
}
185-
/// Current paragraph split into sentences (for the karaoke-style subtitle).
186-
var currentSentences: [String] { TextSplitter.sentences(currentChunkText) }
187-
/// Which sentence is being read now. Uses ElevenLabs character timestamps
188-
/// (exact) when available, else estimates from intra-paragraph progress
189-
/// weighted by sentence length. Audio stays paragraph-chunked either way.
190-
var currentSentenceIndex: Int {
191-
let s = currentSentences
192-
guard s.count > 1 else { return 0 }
193-
let ci = chunkIndex - 1
194-
if chunkSentenceTimes.indices.contains(ci), chunkSentenceTimes[ci].count == s.count {
195-
let t = chunkSeconds
196-
var idx = 0
197-
for (k, start) in chunkSentenceTimes[ci].enumerated() where t + 0.08 >= start { idx = k }
198-
return idx
199-
}
200-
let lengths = s.map { Double(max(1, $0.count)) }
201-
let total = lengths.reduce(0, +)
202-
let target = chunkProgress * total
203-
var acc = 0.0
204-
for (i, len) in lengths.enumerated() { acc += len; if target <= acc { return i } }
205-
return s.count - 1
206-
}
207181

208182
// MARK: - Continuous crawl (teleprompter over the WHOLE script)
209183

@@ -231,14 +205,8 @@ final class AppState: ObservableObject {
231205
/// chunk length (chars) so it tracks the voice smoothly via chunkProgress —
232206
/// QueuePlayer.progress is chunk-equal-weighted, which lurches per paragraph.
233207
var crawlFraction: Double {
234-
let lens = spokenChunks.map { Double(max(1, $0.count)) }
235-
let total = lens.reduce(0, +)
236-
guard total > 0 else { return 0 }
237-
let cur = chunkIndex - 1
238-
var read = 0.0
239-
for i in 0..<lens.count where i < cur { read += lens[i] }
240-
if lens.indices.contains(cur) { read += chunkProgress * lens[cur] }
241-
return min(1, read / total)
208+
CrawlLayout.fraction(chunkLengths: spokenChunks.map { Double(max(1, $0.count)) },
209+
chunkIndex: chunkIndex, chunkProgress: chunkProgress)
242210
}
243211

244212
/// Map ElevenLabs per-character start times to one start time per sentence

‎Sources/Core/CrawlLayout.swift‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,20 @@ enum CrawlLayout {
1212
readingAnchor * viewportHeight - CGFloat(progress) * contentHeight
1313
}
1414

15+
/// How far through playback (0…1), weighted by spoken-chunk length (chars) so
16+
/// the crawl tracks the voice rather than lurching per paragraph. `chunkIndex`
17+
/// is 1-based (0 before playback starts); `chunkProgress` is the 0…1 position
18+
/// within the current chunk.
19+
static func fraction(chunkLengths: [Double], chunkIndex: Int, chunkProgress: Double) -> Double {
20+
let total = chunkLengths.reduce(0, +)
21+
guard total > 0 else { return 0 }
22+
let cur = chunkIndex - 1
23+
var read = 0.0
24+
for i in 0..<chunkLengths.count where i < cur { read += chunkLengths[i] }
25+
if chunkLengths.indices.contains(cur) { read += chunkProgress * chunkLengths[cur] }
26+
return Swift.min(1, read / total)
27+
}
28+
1529
/// Clamp a panel of `size` to stay within `visible`, returning the adjusted
1630
/// bottom-left origin (Cocoa coords). Used so the HUD never drifts off-screen.
1731
static func clampOrigin(_ origin: CGPoint, size: CGSize, in visible: CGRect) -> CGPoint {

‎Tests/main.swift‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ print("TextSplitter.paragraphs / cleanInput")
2424
eq("blank-line paragraphs", TextSplitter.paragraphs("문단1\n\n문단2").count, 2)
2525
eq("cleanInput joins intra-para lines", TextSplitter.paragraphs(TextSplitter.cleanInput("a\nb\n\nc\nd")).count, 2)
2626
eq("long paragraph splits at spaces", TextSplitter.paragraphs("aaaa bbbb cccc", maxChars: 6), ["aaaa", "bbbb", "cccc"])
27+
eq("no-whitespace token hard-cuts", TextSplitter.paragraphs("aaaaaaaa", maxChars: 3), ["aaa", "aaa", "aa"])
2728
eq("paragraph within budget stays whole", TextSplitter.paragraphs("짧은 문단입니다", maxChars: 700).count, 1)
2829
eq("empty → none", TextSplitter.paragraphs(" \n ").count, 0)
29-
// dedupMathLeaks (via cleanInput): a math-only line repeated as the next line's prefix is a render leak
30+
// dedupMathLeaks (via cleanInput): a math-only line/run repeated as the next line's prefix is a render leak
3031
eq("cleanInput drops leaked math prefix", TextSplitter.cleanInput("k\nk는 상수입니다."), "k는 상수입니다.")
32+
eq("cleanInput drops multi-line leaked math run", TextSplitter.cleanInput("k\n=\n1\nk=1은 상수입니다."), "k=1은 상수입니다.")
3133
eq("cleanInput keeps non-prefix math", TextSplitter.cleanInput("x\ny는 다릅니다."), "x y는 다릅니다.")
3234

3335
print("TextSplitter.sentenceIndex — map overall progress onto the subtitle text")
@@ -39,6 +41,14 @@ eq("clamped above → last", TextSplitter.sentenceIndex(at: 2.0, in: sents), 2)
3941
eq("single sentence → 0", TextSplitter.sentenceIndex(at: 0.9, in: ["하나뿐."]), 0)
4042
eq("midpoint lands in 2nd (len-weighted)", TextSplitter.sentenceIndex(at: 0.4, in: sents), 1)
4143

44+
print("CrawlLayout.fraction — char-weighted overall progress")
45+
eq("mid of single chunk", CrawlLayout.fraction(chunkLengths: [100], chunkIndex: 1, chunkProgress: 0.5), 0.5)
46+
eq("before playback (idx 0) → 0", CrawlLayout.fraction(chunkLengths: [50, 50], chunkIndex: 0, chunkProgress: 0), 0)
47+
eq("start of 2nd chunk", CrawlLayout.fraction(chunkLengths: [50, 50], chunkIndex: 2, chunkProgress: 0), 0.5)
48+
eq("end of last chunk → 1", CrawlLayout.fraction(chunkLengths: [50, 50], chunkIndex: 2, chunkProgress: 1), 1)
49+
eq("uneven chunks weighted by length", CrawlLayout.fraction(chunkLengths: [30, 70], chunkIndex: 2, chunkProgress: 0.5), 0.65)
50+
eq("empty → 0", CrawlLayout.fraction(chunkLengths: [], chunkIndex: 1, chunkProgress: 0.5), 0)
51+
4252
print("CrawlLayout.crawlOffset — content scrolls up; reading line at the anchor")
4353
eq("progress 0 → anchor*viewport", CrawlLayout.crawlOffset(progress: 0, contentHeight: 1000, viewportHeight: 200, readingAnchor: 0.5), 100)
4454
eq("progress 1 → fully scrolled", CrawlLayout.crawlOffset(progress: 1, contentHeight: 1000, viewportHeight: 200, readingAnchor: 0.5), -900)

0 commit comments

Comments
 (0)